3 * Abstract base class for representing a single database table.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * @licence GNU GPL v2 or later
25 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
28 abstract class ORMTable
{
31 * Returns the name of the database table objects of this type are stored in.
37 public abstract function getName();
40 * Returns the name of a ORMRow deriving class that
41 * represents single rows in this table.
47 public abstract function getRowClass();
50 * Gets the db field prefix.
56 protected abstract function getFieldPrefix();
59 * Returns an array with the fields and their types this object contains.
60 * This corresponds directly to the fields in the database, without prefix.
76 public abstract function getFields();
79 * Cache for instances, used by the singleton method.
82 * @var array of DBTable
84 protected static $instanceCache = array();
87 * The database connection to use for read operations.
88 * Can be changed via @see setReadDb.
91 * @var integer DB_ enum
93 protected $readDb = DB_SLAVE
;
96 * Returns a list of default field values.
97 * field name => field value
103 public function getDefaults() {
108 * Returns a list of the summary fields.
109 * These are fields that cache computed values, such as the amount of linked objects of $type.
110 * This is relevant as one might not want to do actions such as log changes when these get updated.
116 public function getSummaryFields() {
121 * Selects the the specified fields of the records matching the provided
122 * conditions and returns them as DBDataObject. Field names get prefixed.
126 * @param array|string|null $fields
127 * @param array $conditions
128 * @param array $options
129 * @param string|null $functionName
133 public function select( $fields = null, array $conditions = array(),
134 array $options = array(), $functionName = null ) {
135 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
139 * Selects the the specified fields of the records matching the provided
140 * conditions and returns them as DBDataObject. Field names get prefixed.
144 * @param array|string|null $fields
145 * @param array $conditions
146 * @param array $options
147 * @param string|null $functionName
149 * @return array of self
151 public function selectObjects( $fields = null, array $conditions = array(),
152 array $options = array(), $functionName = null ) {
153 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
157 foreach ( $result as $record ) {
158 $objects[] = $this->newFromArray( $record );
165 * Do the actual select.
169 * @param null|string|array $fields
170 * @param array $conditions
171 * @param array $options
172 * @param null|string $functionName
174 * @return ResultWrapper
176 public function rawSelect( $fields = null, array $conditions = array(),
177 array $options = array(), $functionName = null ) {
178 if ( is_null( $fields ) ) {
179 $fields = array_keys( $this->getFields() );
182 $fields = (array)$fields;
185 return wfGetDB( $this->getReadDb() )->select(
187 $this->getPrefixedFields( $fields ),
188 $this->getPrefixedValues( $conditions ),
189 is_null( $functionName ) ? __METHOD__
: $functionName,
195 * Selects the the specified fields of the records matching the provided
196 * conditions and returns them as associative arrays.
197 * Provided field names get prefixed.
198 * Returned field names will not have a prefix.
200 * When $collapse is true:
201 * If one field is selected, each item in the result array will be this field.
202 * If two fields are selected, each item in the result array will have as key
203 * the first field and as value the second field.
204 * If more then two fields are selected, each item will be an associative array.
208 * @param array|string|null $fields
209 * @param array $conditions
210 * @param array $options
211 * @param boolean $collapse Set to false to always return each result row as associative array.
212 * @param string|null $functionName
214 * @return array of array
216 public function selectFields( $fields = null, array $conditions = array(),
217 array $options = array(), $collapse = true, $functionName = null ) {
220 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
222 foreach ( $result as $record ) {
223 $objects[] = $this->getFieldsFromDBResult( $record );
227 if ( count( $fields ) === 1 ) {
228 $objects = array_map( 'array_shift', $objects );
230 elseif ( count( $fields ) === 2 ) {
233 foreach ( $objects as $object ) {
234 $o[array_shift( $object )] = array_shift( $object );
245 * Selects the the specified fields of the first matching record.
246 * Field names get prefixed.
250 * @param array|string|null $fields
251 * @param array $conditions
252 * @param array $options
253 * @param string|null $functionName
255 * @return DBObject|bool False on failure
257 public function selectRow( $fields = null, array $conditions = array(),
258 array $options = array(), $functionName = null ) {
259 $options['LIMIT'] = 1;
261 $objects = $this->select( $fields, $conditions, $options, $functionName );
263 return $objects->isEmpty() ?
false : $objects->current();
267 * Selects the the specified fields of the records matching the provided
268 * conditions. Field names do NOT get prefixed.
272 * @param array $fields
273 * @param array $conditions
274 * @param array $options
275 * @param string|null $functionName
277 * @return ResultWrapper
279 public function rawSelectRow( array $fields, array $conditions = array(),
280 array $options = array(), $functionName = null ) {
281 $dbr = wfGetDB( $this->getReadDb() );
283 return $dbr->selectRow(
287 is_null( $functionName ) ? __METHOD__
: $functionName,
293 * Selects the the specified fields of the first record matching the provided
294 * conditions and returns it as an associative array, or false when nothing matches.
295 * This method makes use of selectFields and expects the same parameters and
296 * returns the same results (if there are any, if there are none, this method returns false).
297 * @see ORMTable::selectFields
301 * @param array|string|null $fields
302 * @param array $conditions
303 * @param array $options
304 * @param boolean $collapse Set to false to always return each result row as associative array.
305 * @param string|null $functionName
307 * @return mixed|array|bool False on failure
309 public function selectFieldsRow( $fields = null, array $conditions = array(),
310 array $options = array(), $collapse = true, $functionName = null ) {
311 $options['LIMIT'] = 1;
313 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
315 return empty( $objects ) ?
false : $objects[0];
319 * Returns if there is at least one record matching the provided conditions.
320 * Condition field names get prefixed.
324 * @param array $conditions
328 public function has( array $conditions = array() ) {
329 return $this->selectRow( array( 'id' ), $conditions ) !== false;
333 * Returns the amount of matching records.
334 * Condition field names get prefixed.
336 * Note that this can be expensive on large tables.
337 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
341 * @param array $conditions
342 * @param array $options
346 public function count( array $conditions = array(), array $options = array() ) {
347 $res = $this->rawSelectRow(
348 array( 'COUNT(*) AS rowcount' ),
349 $this->getPrefixedValues( $conditions ),
353 return $res->rowcount
;
357 * Removes the object from the database.
361 * @param array $conditions
362 * @param string|null $functionName
364 * @return boolean Success indicator
366 public function delete( array $conditions, $functionName = null ) {
367 return wfGetDB( DB_MASTER
)->delete(
369 $this->getPrefixedValues( $conditions ),
375 * Get API parameters for the fields supported by this object.
379 * @param boolean $requireParams
380 * @param boolean $setDefaults
384 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
396 $defaults = $this->getDefaults();
398 foreach ( $this->getFields() as $field => $type ) {
399 if ( $field == 'id' ) {
403 $hasDefault = array_key_exists( $field, $defaults );
405 $params[$field] = array(
406 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
407 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
410 if ( $type == 'array' ) {
411 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
414 if ( $setDefaults && $hasDefault ) {
415 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
416 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
424 * Returns an array with the fields and their descriptions.
426 * field name => field description
432 public function getFieldDescriptions() {
437 * Get the database type used for read operations.
441 * @return integer DB_ enum
443 public function getReadDb() {
444 return $this->readDb
;
448 * Set the database type to use for read operations.
454 public function setReadDb( $db ) {
459 * Update the records matching the provided conditions by
460 * setting the fields that are keys in the $values param to
461 * their corresponding values.
465 * @param array $values
466 * @param array $conditions
468 * @return boolean Success indicator
470 public function update( array $values, array $conditions = array() ) {
471 $dbw = wfGetDB( DB_MASTER
);
475 $this->getPrefixedValues( $values ),
476 $this->getPrefixedValues( $conditions ),
482 * Computes the values of the summary fields of the objects matching the provided conditions.
486 * @param array|string|null $summaryFields
487 * @param array $conditions
489 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
490 $this->setReadDb( DB_MASTER
);
492 foreach ( $this->select( null, $conditions ) as /* ORMRow */ $item ) {
493 $item->loadSummaryFields( $summaryFields );
494 $item->setSummaryMode( true );
498 $this->setReadDb( DB_SLAVE
);
502 * Takes in an associative array with field names as keys and
503 * their values as value. The field names are prefixed with the
506 * Field names can also be provided as an array with as first element a table name, such as
507 * $conditions = array(
508 * array( array( 'tablename', 'fieldname' ), $value ),
513 * @param array $values
517 public function getPrefixedValues( array $values ) {
518 $prefixedValues = array();
520 foreach ( $values as $field => $value ) {
521 if ( is_integer( $field ) ) {
522 if ( is_array( $value ) ) {
527 $value = explode( ' ', $value, 2 );
528 $value[0] = $this->getPrefixedField( $value[0] );
529 $prefixedValues[] = implode( ' ', $value );
534 $prefixedValues[$this->getPrefixedField( $field )] = $value;
537 return $prefixedValues;
541 * Takes in a field or array of fields and returns an
542 * array with their prefixed versions, ready for db usage.
546 * @param array|string $fields
550 public function getPrefixedFields( array $fields ) {
551 foreach ( $fields as &$field ) {
552 $field = $this->getPrefixedField( $field );
559 * Takes in a field and returns an it's prefixed version, ready for db usage.
563 * @param string|array $field
567 public function getPrefixedField( $field ) {
568 return $this->getFieldPrefix() . $field;
572 * Takes an array of field names with prefix and returns the unprefixed equivalent.
576 * @param array $fieldNames
580 public function unprefixFieldNames( array $fieldNames ) {
581 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
585 * Takes a field name with prefix and returns the unprefixed equivalent.
589 * @param string $fieldName
593 public function unprefixFieldName( $fieldName ) {
594 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
598 * Get an instance of this class.
604 public static function singleton() {
605 $class = function_exists( 'get_called_class' ) ?
get_called_class() : self
::get_called_class();
607 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
608 self
::$instanceCache[$class] = new $class;
611 return self
::$instanceCache[$class];
615 * Compatibility fallback function so the singleton method works on PHP < 5.3.
616 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
622 protected static function get_called_class() {
623 $bt = debug_backtrace();
626 while(empty($matches) && $l > -1){
627 $lines = file($bt[$l]['file']);
628 $callerLine = $lines[$bt[$l]['line']-1];
629 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
633 if (!isset($matches[1])) $matches[1]=NULL; //for notices
634 if ($matches[1] == 'self') {
635 $line = $bt[$l]['line']-1;
636 while ($line > 0 && strpos($lines[$line], 'class') === false) {
639 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
645 * Get an array with fields from a database result,
646 * that can be fed directly to the constructor or
651 * @param stdClass $result
655 public function getFieldsFromDBResult( stdClass
$result ) {
656 $result = (array)$result;
657 return array_combine(
658 $this->unprefixFieldNames( array_keys( $result ) ),
659 array_values( $result )
664 * Get a new instance of the class from a database result.
668 * @param stdClass $result
672 public function newFromDBResult( stdClass
$result ) {
673 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
677 * Get a new instance of the class from an array.
682 * @param boolean $loadDefaults
686 public function newFromArray( array $data, $loadDefaults = false ) {
687 $class = $this->getRowClass();
688 return new $class( $this, $data, $loadDefaults );
692 * Return the names of the fields.
698 public function getFieldNames() {
699 return array_keys( $this->getFields() );
703 * Gets if the object can take a certain field.
707 * @param string $name
711 public function canHaveField( $name ) {
712 return array_key_exists( $name, $this->getFields() );