4 * Abstract base class for representing a single database table.
10 * @licence GNU GPL v2 or later
11 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
13 abstract class ORMTable
{
16 * Returns the name of the database table objects of this type are stored in.
22 public abstract function getName();
25 * Returns the name of a ORMRow deriving class that
26 * represents single rows in this table.
32 public abstract function getRowClass();
35 * Gets the db field prefix.
41 protected abstract function getFieldPrefix();
44 * Returns an array with the fields and their types this object contains.
45 * This corresponds directly to the fields in the database, without prefix.
61 public abstract function getFields();
64 * Cache for instances, used by the singleton method.
67 * @var array of DBTable
69 protected static $instanceCache = array();
72 * The database connection to use for read operations.
73 * Can be changed via @see setReadDb.
76 * @var integer DB_ enum
78 protected $readDb = DB_SLAVE
;
81 * Returns a list of default field values.
82 * field name => field value
88 public function getDefaults() {
93 * Returns a list of the summary fields.
94 * These are fields that cache computed values, such as the amount of linked objects of $type.
95 * This is relevant as one might not want to do actions such as log changes when these get updated.
101 public function getSummaryFields() {
106 * Selects the the specified fields of the records matching the provided
107 * conditions and returns them as DBDataObject. Field names get prefixed.
111 * @param array|string|null $fields
112 * @param array $conditions
113 * @param array $options
114 * @param string|null $functionName
118 public function select( $fields = null, array $conditions = array(),
119 array $options = array(), $functionName = null ) {
120 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
124 * Selects the the specified fields of the records matching the provided
125 * conditions and returns them as DBDataObject. Field names get prefixed.
129 * @param array|string|null $fields
130 * @param array $conditions
131 * @param array $options
132 * @param string|null $functionName
134 * @return array of self
136 public function selectObjects( $fields = null, array $conditions = array(),
137 array $options = array(), $functionName = null ) {
138 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
142 foreach ( $result as $record ) {
143 $objects[] = $this->newFromArray( $record );
150 * Do the actual select.
154 * @param null|string|array $fields
155 * @param array $conditions
156 * @param array $options
157 * @param null|string $functionName
159 * @return ResultWrapper
161 public function rawSelect( $fields = null, array $conditions = array(),
162 array $options = array(), $functionName = null ) {
163 if ( is_null( $fields ) ) {
164 $fields = array_keys( $this->getFields() );
167 $fields = (array)$fields;
170 return wfGetDB( $this->getReadDb() )->select(
172 $this->getPrefixedFields( $fields ),
173 $this->getPrefixedValues( $conditions ),
174 is_null( $functionName ) ? __METHOD__
: $functionName,
180 * Selects the the specified fields of the records matching the provided
181 * conditions and returns them as associative arrays.
182 * Provided field names get prefixed.
183 * Returned field names will not have a prefix.
185 * When $collapse is true:
186 * If one field is selected, each item in the result array will be this field.
187 * If two fields are selected, each item in the result array will have as key
188 * the first field and as value the second field.
189 * If more then two fields are selected, each item will be an associative array.
193 * @param array|string|null $fields
194 * @param array $conditions
195 * @param array $options
196 * @param boolean $collapse Set to false to always return each result row as associative array.
197 * @param string|null $functionName
199 * @return array of array
201 public function selectFields( $fields = null, array $conditions = array(),
202 array $options = array(), $collapse = true, $functionName = null ) {
205 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
207 foreach ( $result as $record ) {
208 $objects[] = $this->getFieldsFromDBResult( $record );
212 if ( count( $fields ) === 1 ) {
213 $objects = array_map( 'array_shift', $objects );
215 elseif ( count( $fields ) === 2 ) {
218 foreach ( $objects as $object ) {
219 $o[array_shift( $object )] = array_shift( $object );
230 * Selects the the specified fields of the first matching record.
231 * Field names get prefixed.
235 * @param array|string|null $fields
236 * @param array $conditions
237 * @param array $options
238 * @param string|null $functionName
240 * @return DBObject|bool False on failure
242 public function selectRow( $fields = null, array $conditions = array(),
243 array $options = array(), $functionName = null ) {
244 $options['LIMIT'] = 1;
246 $objects = $this->select( $fields, $conditions, $options, $functionName );
248 return $objects->isEmpty() ?
false : $objects->current();
252 * Selects the the specified fields of the records matching the provided
253 * conditions. Field names do NOT get prefixed.
257 * @param array $fields
258 * @param array $conditions
259 * @param array $options
260 * @param string|null $functionName
262 * @return ResultWrapper
264 public function rawSelectRow( array $fields, array $conditions = array(),
265 array $options = array(), $functionName = null ) {
266 $dbr = wfGetDB( $this->getReadDb() );
268 return $dbr->selectRow(
272 is_null( $functionName ) ? __METHOD__
: $functionName,
278 * Selects the the specified fields of the first record matching the provided
279 * conditions and returns it as an associative array, or false when nothing matches.
280 * This method makes use of selectFields and expects the same parameters and
281 * returns the same results (if there are any, if there are none, this method returns false).
282 * @see ORMTable::selectFields
286 * @param array|string|null $fields
287 * @param array $conditions
288 * @param array $options
289 * @param boolean $collapse Set to false to always return each result row as associative array.
290 * @param string|null $functionName
292 * @return mixed|array|bool False on failure
294 public function selectFieldsRow( $fields = null, array $conditions = array(),
295 array $options = array(), $collapse = true, $functionName = null ) {
296 $options['LIMIT'] = 1;
298 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
300 return empty( $objects ) ?
false : $objects[0];
304 * Returns if there is at least one record matching the provided conditions.
305 * Condition field names get prefixed.
309 * @param array $conditions
313 public function has( array $conditions = array() ) {
314 return $this->selectRow( array( 'id' ), $conditions ) !== false;
318 * Returns the amount of matching records.
319 * Condition field names get prefixed.
321 * Note that this can be expensive on large tables.
322 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
326 * @param array $conditions
327 * @param array $options
331 public function count( array $conditions = array(), array $options = array() ) {
332 $res = $this->rawSelectRow(
333 array( 'COUNT(*) AS rowcount' ),
334 $this->getPrefixedValues( $conditions ),
338 return $res->rowcount
;
342 * Removes the object from the database.
346 * @param array $conditions
347 * @param string|null $functionName
349 * @return boolean Success indicator
351 public function delete( array $conditions, $functionName = null ) {
352 return wfGetDB( DB_MASTER
)->delete(
354 $this->getPrefixedValues( $conditions ),
360 * Get API parameters for the fields supported by this object.
364 * @param boolean $requireParams
365 * @param boolean $setDefaults
369 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
381 $defaults = $this->getDefaults();
383 foreach ( $this->getFields() as $field => $type ) {
384 if ( $field == 'id' ) {
388 $hasDefault = array_key_exists( $field, $defaults );
390 $params[$field] = array(
391 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
392 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
395 if ( $type == 'array' ) {
396 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
399 if ( $setDefaults && $hasDefault ) {
400 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
401 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
409 * Returns an array with the fields and their descriptions.
411 * field name => field description
417 public function getFieldDescriptions() {
422 * Get the database type used for read operations.
426 * @return integer DB_ enum
428 public function getReadDb() {
429 return $this->readDb
;
433 * Set the database type to use for read operations.
439 public function setReadDb( $db ) {
444 * Update the records matching the provided conditions by
445 * setting the fields that are keys in the $values param to
446 * their corresponding values.
450 * @param array $values
451 * @param array $conditions
453 * @return boolean Success indicator
455 public function update( array $values, array $conditions = array() ) {
456 $dbw = wfGetDB( DB_MASTER
);
460 $this->getPrefixedValues( $values ),
461 $this->getPrefixedValues( $conditions ),
467 * Computes the values of the summary fields of the objects matching the provided conditions.
471 * @param array|string|null $summaryFields
472 * @param array $conditions
474 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
475 $this->setReadDb( DB_MASTER
);
477 foreach ( $this->select( null, $conditions ) as /* ORMRow */ $item ) {
478 $item->loadSummaryFields( $summaryFields );
479 $item->setSummaryMode( true );
483 $this->setReadDb( DB_SLAVE
);
487 * Takes in an associative array with field names as keys and
488 * their values as value. The field names are prefixed with the
491 * Field names can also be provided as an array with as first element a table name, such as
492 * $conditions = array(
493 * array( array( 'tablename', 'fieldname' ), $value ),
498 * @param array $values
502 public function getPrefixedValues( array $values ) {
503 $prefixedValues = array();
505 foreach ( $values as $field => $value ) {
506 if ( is_integer( $field ) ) {
507 if ( is_array( $value ) ) {
512 $value = explode( ' ', $value, 2 );
513 $value[0] = $this->getPrefixedField( $value[0] );
514 $prefixedValues[] = implode( ' ', $value );
519 $prefixedValues[$this->getPrefixedField( $field )] = $value;
522 return $prefixedValues;
526 * Takes in a field or array of fields and returns an
527 * array with their prefixed versions, ready for db usage.
531 * @param array|string $fields
535 public function getPrefixedFields( array $fields ) {
536 foreach ( $fields as &$field ) {
537 $field = $this->getPrefixedField( $field );
544 * Takes in a field and returns an it's prefixed version, ready for db usage.
548 * @param string|array $field
552 public function getPrefixedField( $field ) {
553 return $this->getFieldPrefix() . $field;
557 * Takes an array of field names with prefix and returns the unprefixed equivalent.
561 * @param array $fieldNames
565 public function unprefixFieldNames( array $fieldNames ) {
566 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
570 * Takes a field name with prefix and returns the unprefixed equivalent.
574 * @param string $fieldName
578 public function unprefixFieldName( $fieldName ) {
579 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
583 * Get an instance of this class.
589 public static function singleton() {
590 $class = function_exists( 'get_called_class' ) ?
get_called_class() : self
::get_called_class();
592 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
593 self
::$instanceCache[$class] = new $class;
596 return self
::$instanceCache[$class];
600 * Compatibility fallback function so the singleton method works on PHP < 5.3.
601 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
607 protected static function get_called_class() {
608 $bt = debug_backtrace();
611 while(empty($matches) && $l > -1){
612 $lines = file($bt[$l]['file']);
613 $callerLine = $lines[$bt[$l]['line']-1];
614 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
618 if (!isset($matches[1])) $matches[1]=NULL; //for notices
619 if ($matches[1] == 'self') {
620 $line = $bt[$l]['line']-1;
621 while ($line > 0 && strpos($lines[$line], 'class') === false) {
624 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
630 * Get an array with fields from a database result,
631 * that can be fed directly to the constructor or
636 * @param stdClass $result
640 public function getFieldsFromDBResult( stdClass
$result ) {
641 $result = (array)$result;
642 return array_combine(
643 $this->unprefixFieldNames( array_keys( $result ) ),
644 array_values( $result )
649 * Get a new instance of the class from a database result.
653 * @param stdClass $result
657 public function newFromDBResult( stdClass
$result ) {
658 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
662 * Get a new instance of the class from an array.
667 * @param boolean $loadDefaults
671 public function newFromArray( array $data, $loadDefaults = false ) {
672 $class = $this->getRowClass();
673 return new $class( $this, $data, $loadDefaults );
677 * Return the names of the fields.
683 public function getFieldNames() {
684 return array_keys( $this->getFields() );
688 * Gets if the object can take a certain field.
692 * @param string $name
696 public function canHaveField( $name ) {
697 return array_key_exists( $name, $this->getFields() );