summaryrefslogtreecommitdiff
path: root/framework/Data/ActiveRecord/TActiveRecordGateway.php
blob: e7ea5e46596cd7e8692e8da3c5aa8af791d3b1c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
/**
 * TActiveRecordGateway, TActiveRecordStatementType, TActiveRecordGatewayEventParameter classes file.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2007 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Id$
 * @package System.Data.ActiveRecord
 */

/**
 * TActiveRecordGateway excutes the SQL command queries and returns the data
 * record as arrays (for most finder methods).
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @version $Id$
 * @package System.Data.ActiveRecord
 * @since 3.1
 */
class TActiveRecordGateway extends TComponent
{
	private $_manager;
	private $_tables=array(); //meta data cache.

	/**
	 * Property name for optional table name in TActiveRecord.
	 */
	const PROPERTY_TABLE_NAME='_tablename';

	/**
	 * Record gateway constructor.
	 * @param TActiveRecordManager $manager
	 */
	public function __construct(TActiveRecordManager $manager)
	{
		$this->_manager=$manager;
	}

	/**
	 * @return TActiveRecordManager record manager.
	 */
	protected function getManager()
	{
		return $this->_manager;
	}

	/**
	 * Gets the table name from the $_tablename property of the active record
	 * class if defined, otherwise use the class name as table name.
	 * @param TActiveRecord active record instance
	 * @return string table name for the given record class.
	 */
	public function getTableName(TActiveRecord $record)
	{
		$class = new ReflectionClass($record);
		if($class->hasProperty(self::PROPERTY_TABLE_NAME))
		{
			$value = $class->getProperty(self::PROPERTY_TABLE_NAME)->getValue();
			if($value===null)
				throw new TActiveRecordException('ar_invalid_tablename_property',
					get_class($record),self::PROPERTY_TABLE_NAME);
			return $value;
		}
		else
			return strtolower(get_class($record));
	}

	/**
	 * @param TActiveRecord active record.
	 * @return TDbMetaData table meta data, null if not found.
	 */
	protected function getCachedMetaData($record)
	{
		$type=get_class($record);
		if(isset($this->_tables[$type]))
			return $this->_tables[$type];
		if(($cache=$this->getManager()->getCache())!==null)
		{
			//force loading of the table inspector to load the required classes
			// before unserializing cached meta data.
			$this->getManager()->getTableInspector($record->getDbConnection());
			$data = $cache->get($this->getMetaDataCacheKey($record));
			if($data !== false && $data !== null)
			{
				$this->_tables[$type] = $data;
				return $data;
			}
		}
	}

	/**
	 * @param TActiveRecord active record.
	 * @return string cache key, using connection string + record class name
	 */
	protected function getMetaDataCacheKey($record)
	{
		$conn = $record->getDbConnection()->getConnectionString();
		return $conn.':'.get_class($record);
	}

	/**
	 * Cache the meta data, tries the application cache if applicable.
	 * @param TActiveRecord active record.
	 * @param TDbMetaData table meta data
	 * @return TDbMetaData table meta data.
	 */
	protected function cacheMetaData($record,$data)
	{
		$type = get_class($record);
		if(($cache=$this->getManager()->getCache())!==null)
			$cache->set($this->getMetaDataCacheKey($record), $data);
		$this->_tables[$type] = $data;
		return $data;
	}

	/**
	 * Gets the meta data for given database and table.
	 */
	public function getMetaData(TActiveRecord $record)
	{
		$type=get_class($record);
		if(!($data = $this->getCachedMetaData($record)))
		{
			$conn = $record->getDbConnection();
			$inspector = $this->getManager()->getTableInspector($conn);
			$table = $this->getTableName($record);
			$data = $this->cacheMetaData($record,$inspector->getTableMetaData($table));
		}
		return $data;
	}

	/**
	 * Returns record data matching the given primary key(s). If the table uses
	 * composite key, specify the name value pairs as an array.
	 * @param TActiveRecord active record instance.
	 * @param array primary name value pairs
	 * @return array record data
	 */
	public function findRecordByPK(TActiveRecord $record,$keys)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getFindByPkCommand($record->getDbConnection(),$keys);
		$this->raiseCommandEvent(TActiveRecordStatementType::Select,$command,$record,$keys);
		return $meta->postQueryRow($command->queryRow());
	}

	/**
	 * Returns record data matching the given critera. If $iterator is true, it will
	 * return multiple rows as TDbDataReader otherwise it returns the <b>first</b> row data.
	 * @param TActiveRecord active record finder instance.
	 * @param TActiveRecordCriteria search criteria.
	 * @param boolean true to return multiple rows as iterator, false returns first row.
	 * @return mixed matching data.
	 */
	public function findRecordsByCriteria(TActiveRecord $record, $criteria, $iterator=false)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getFindByCriteriaCommand($record->getDbConnection(),$criteria);
		$this->raiseCommandEvent(TActiveRecordStatementType::Select,$command,$record,$criteria);
		return $iterator ? $meta->postQuery($command->query()) : $meta->postQueryRow($command->queryRow());
	}

	/**
	 * Return record data from sql query.
	 * @param TActiveRecord active record finder instance.
	 * @param string SQL string
	 * @param array query parameters.
	 * @return TDbDataReader result iterator.
	 */
	public function findRecordsBySql(TActiveRecord $record, $sql,$parameters=array())
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getFindBySqlCommand($record->getDbConnection(),$sql,$parameters);
		$this->raiseCommandEvent(TActiveRecordStatementType::Select,$command,$record,$parameters);
		return $meta->postQuery($command->query());
	}

	/**
	 * Returns the number of records that match the given criteria.
	 * @param TActiveRecord active record finder instance.
	 * @param TActiveRecordCriteria search criteria
	 * @return int number of records.
	 */
	public function countRecords(TActiveRecord $record, $criteria)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getCountRecordsCommand($record->getDbConnection(),$criteria);
		$this->raiseCommandEvent(TActiveRecordStatementType::Select,$command,$record,$criteria);
		return intval($command->queryScalar());
	}

	/**
	 * Insert a new record.
	 * @param TActiveRecord new record.
	 * @return int number of rows affected.
	 */
	public function insert(TActiveRecord $record)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getInsertCommand($record->getDbConnection(),$record);
		$this->raiseCommandEvent(TActiveRecordStatementType::Insert,$command,$record);
		$rowsAffected = $command->execute();
		if($rowsAffected===1)
			$meta->updatePostInsert($record->getDbConnection(),$record);
		return $rowsAffected;
	}

	/**
	 * Update the record.
	 * @param TActiveRecord dirty record.
	 * @return int number of rows affected.
	 */
	public function update(TActiveRecord $record)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getUpdateCommand($record->getDbConnection(),$record);
		$this->raiseCommandEvent(TActiveRecordStatementType::Update,$command,$record);
		return $command->execute();
	}

	/**
	 * Delete the record.
	 * @param TActiveRecord record to be deleted.
	 * @return int number of rows affected.
	 */
	public function delete(TActiveRecord $record)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getDeleteCommand($record->getDbConnection(),$record);
		$this->raiseCommandEvent(TActiveRecordStatementType::Delete,$command,$record);
		return $command->execute();
	}

	/**
	 * Delete multiple records using primary keys.
	 * @param TActiveRecord finder instance.
	 * @return int number of rows deleted.
	 */
	public function deleteRecordsByPk(TActiveRecord $record, $keys)
	{
		$meta = $this->getMetaData($record);
		$command = $meta->getDeleteByPkCommand($record->getDBConnection(),$keys);
		$this->raiseCommandEvent(TActiveRecordStatementType::Delete,$command,$record,$keys);
		return $command->execute();
	}

	/**
	 * Raise the corresponding command event, insert, update, delete or select.
	 * @param string command type
	 * @param TDbCommand sql command to be executed.
	 * @param TActiveRecord active record
	 * @param mixed data for the command.
	 */
	protected function raiseCommandEvent($type,$command,$record=null,$data=null)
	{
		$param = new TActiveRecordGatewayEventParameter($type,$command,$record,$data);
		$manager = $record->getRecordManager();
		$event = 'on'.$type;
		$manager->{$event}($param);
	}
}

/**
 * Command statement types.
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @version $Id$
 * @package System.Data.ActiveRecord
 * @since 3.1
 */
class TActiveRecordStatementType
{
	const Insert='Insert';
	const Update='Update';
	const Delete='Delete';
	const Select='Select';
}

/**
 * Active Record command event parameter.
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @version $Id$
 * @package System.Data.ActiveRecord
 * @since 3.1
 */
class TActiveRecordGatewayEventParameter extends TActiveRecordEventParameter
{
	private $_type;
	private $_command;
	private $_record;
	private $_data;

	/**
	 * New gateway command event parameter.
	 */
	public function __construct($type,$command,$record=null,$data=null)
	{
		$this->_type=$type;
		$this->_command=$command;
		$this->_data=$data;
		$this->_record=$record;
	}

	/**
	 * @return string TActiveRecordStateType
	 */
	public function getType()
	{
		return $this->_type;
	}

	/**
	 * @return TDbCommand command to be executed.
	 */
	public function getCommand()
	{
		return $this->_command;
	}

	/**
	 * @return TActiveRecord active record.
	 */
	public function getRecord()
	{
		return $this->_record;
	}

	/**
	 * @return mixed command data.
	 */
	public function getData()
	{
		return $this->_data;
	}
}

?>