Introduce a new hook that allows extensions to add to My Contributions
[mediawiki.git] / includes / db / ORMTable.php
blob951456270a1f192af78ee2efedf6d09b1f8381c5
1 <?php
2 /**
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
20 * @since 1.20
22 * @file ORMTable.php
23 * @ingroup ORM
25 * @licence GNU GPL v2 or later
26 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
29 abstract class ORMTable implements IORMTable {
31 /**
32 * Gets the db field prefix.
34 * @since 1.20
36 * @return string
38 protected abstract function getFieldPrefix();
40 /**
41 * Cache for instances, used by the singleton method.
43 * @since 1.20
44 * @var array of DBTable
46 protected static $instanceCache = array();
48 /**
49 * The database connection to use for read operations.
50 * Can be changed via @see setReadDb.
52 * @since 1.20
53 * @var integer DB_ enum
55 protected $readDb = DB_SLAVE;
57 /**
58 * Returns a list of default field values.
59 * field name => field value
61 * @since 1.20
63 * @return array
65 public function getDefaults() {
66 return array();
69 /**
70 * Returns a list of the summary fields.
71 * These are fields that cache computed values, such as the amount of linked objects of $type.
72 * This is relevant as one might not want to do actions such as log changes when these get updated.
74 * @since 1.20
76 * @return array
78 public function getSummaryFields() {
79 return array();
82 /**
83 * Selects the the specified fields of the records matching the provided
84 * conditions and returns them as DBDataObject. Field names get prefixed.
86 * @since 1.20
88 * @param array|string|null $fields
89 * @param array $conditions
90 * @param array $options
91 * @param string|null $functionName
93 * @return ORMResult
95 public function select( $fields = null, array $conditions = array(),
96 array $options = array(), $functionName = null ) {
97 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
101 * Selects the the specified fields of the records matching the provided
102 * conditions and returns them as DBDataObject. Field names get prefixed.
104 * @since 1.20
106 * @param array|string|null $fields
107 * @param array $conditions
108 * @param array $options
109 * @param string|null $functionName
111 * @return array of self
113 public function selectObjects( $fields = null, array $conditions = array(),
114 array $options = array(), $functionName = null ) {
115 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
117 $objects = array();
119 foreach ( $result as $record ) {
120 $objects[] = $this->newRow( $record );
123 return $objects;
127 * Do the actual select.
129 * @since 1.20
131 * @param null|string|array $fields
132 * @param array $conditions
133 * @param array $options
134 * @param null|string $functionName
136 * @return ResultWrapper
138 public function rawSelect( $fields = null, array $conditions = array(),
139 array $options = array(), $functionName = null ) {
140 if ( is_null( $fields ) ) {
141 $fields = array_keys( $this->getFields() );
143 else {
144 $fields = (array)$fields;
147 return wfGetDB( $this->getReadDb() )->select(
148 $this->getName(),
149 $this->getPrefixedFields( $fields ),
150 $this->getPrefixedValues( $conditions ),
151 is_null( $functionName ) ? __METHOD__ : $functionName,
152 $options
157 * Selects the the specified fields of the records matching the provided
158 * conditions and returns them as associative arrays.
159 * Provided field names get prefixed.
160 * Returned field names will not have a prefix.
162 * When $collapse is true:
163 * If one field is selected, each item in the result array will be this field.
164 * If two fields are selected, each item in the result array will have as key
165 * the first field and as value the second field.
166 * If more then two fields are selected, each item will be an associative array.
168 * @since 1.20
170 * @param array|string|null $fields
171 * @param array $conditions
172 * @param array $options
173 * @param boolean $collapse Set to false to always return each result row as associative array.
174 * @param string|null $functionName
176 * @return array of array
178 public function selectFields( $fields = null, array $conditions = array(),
179 array $options = array(), $collapse = true, $functionName = null ) {
180 $objects = array();
182 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
184 foreach ( $result as $record ) {
185 $objects[] = $this->getFieldsFromDBResult( $record );
188 if ( $collapse ) {
189 if ( count( $fields ) === 1 ) {
190 $objects = array_map( 'array_shift', $objects );
192 elseif ( count( $fields ) === 2 ) {
193 $o = array();
195 foreach ( $objects as $object ) {
196 $o[array_shift( $object )] = array_shift( $object );
199 $objects = $o;
203 return $objects;
207 * Selects the the specified fields of the first matching record.
208 * Field names get prefixed.
210 * @since 1.20
212 * @param array|string|null $fields
213 * @param array $conditions
214 * @param array $options
215 * @param string|null $functionName
217 * @return IORMRow|bool False on failure
219 public function selectRow( $fields = null, array $conditions = array(),
220 array $options = array(), $functionName = null ) {
221 $options['LIMIT'] = 1;
223 $objects = $this->select( $fields, $conditions, $options, $functionName );
225 return $objects->isEmpty() ? false : $objects->current();
229 * Selects the the specified fields of the records matching the provided
230 * conditions. Field names do NOT get prefixed.
232 * @since 1.20
234 * @param array $fields
235 * @param array $conditions
236 * @param array $options
237 * @param string|null $functionName
239 * @return ResultWrapper
241 public function rawSelectRow( array $fields, array $conditions = array(),
242 array $options = array(), $functionName = null ) {
243 $dbr = wfGetDB( $this->getReadDb() );
245 return $dbr->selectRow(
246 $this->getName(),
247 $fields,
248 $conditions,
249 is_null( $functionName ) ? __METHOD__ : $functionName,
250 $options
255 * Selects the the specified fields of the first record matching the provided
256 * conditions and returns it as an associative array, or false when nothing matches.
257 * This method makes use of selectFields and expects the same parameters and
258 * returns the same results (if there are any, if there are none, this method returns false).
259 * @see ORMTable::selectFields
261 * @since 1.20
263 * @param array|string|null $fields
264 * @param array $conditions
265 * @param array $options
266 * @param boolean $collapse Set to false to always return each result row as associative array.
267 * @param string|null $functionName
269 * @return mixed|array|bool False on failure
271 public function selectFieldsRow( $fields = null, array $conditions = array(),
272 array $options = array(), $collapse = true, $functionName = null ) {
273 $options['LIMIT'] = 1;
275 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
277 return empty( $objects ) ? false : $objects[0];
281 * Returns if there is at least one record matching the provided conditions.
282 * Condition field names get prefixed.
284 * @since 1.20
286 * @param array $conditions
288 * @return boolean
290 public function has( array $conditions = array() ) {
291 return $this->selectRow( array( 'id' ), $conditions ) !== false;
295 * Returns the amount of matching records.
296 * Condition field names get prefixed.
298 * Note that this can be expensive on large tables.
299 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
301 * @since 1.20
303 * @param array $conditions
304 * @param array $options
306 * @return integer
308 public function count( array $conditions = array(), array $options = array() ) {
309 $res = $this->rawSelectRow(
310 array( 'COUNT(*) AS rowcount' ),
311 $this->getPrefixedValues( $conditions ),
312 $options
315 return $res->rowcount;
319 * Removes the object from the database.
321 * @since 1.20
323 * @param array $conditions
324 * @param string|null $functionName
326 * @return boolean Success indicator
328 public function delete( array $conditions, $functionName = null ) {
329 return wfGetDB( DB_MASTER )->delete(
330 $this->getName(),
331 $this->getPrefixedValues( $conditions ),
332 $functionName
333 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
337 * Get API parameters for the fields supported by this object.
339 * @since 1.20
341 * @param boolean $requireParams
342 * @param boolean $setDefaults
344 * @return array
346 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
347 $typeMap = array(
348 'id' => 'integer',
349 'int' => 'integer',
350 'float' => 'NULL',
351 'str' => 'string',
352 'bool' => 'integer',
353 'array' => 'string',
354 'blob' => 'string',
357 $params = array();
358 $defaults = $this->getDefaults();
360 foreach ( $this->getFields() as $field => $type ) {
361 if ( $field == 'id' ) {
362 continue;
365 $hasDefault = array_key_exists( $field, $defaults );
367 $params[$field] = array(
368 ApiBase::PARAM_TYPE => $typeMap[$type],
369 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
372 if ( $type == 'array' ) {
373 $params[$field][ApiBase::PARAM_ISMULTI] = true;
376 if ( $setDefaults && $hasDefault ) {
377 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
378 $params[$field][ApiBase::PARAM_DFLT] = $default;
382 return $params;
386 * Returns an array with the fields and their descriptions.
388 * field name => field description
390 * @since 1.20
392 * @return array
394 public function getFieldDescriptions() {
395 return array();
399 * Get the database type used for read operations.
401 * @since 1.20
403 * @return integer DB_ enum
405 public function getReadDb() {
406 return $this->readDb;
410 * Set the database type to use for read operations.
412 * @param integer $db
414 * @since 1.20
416 public function setReadDb( $db ) {
417 $this->readDb = $db;
421 * Update the records matching the provided conditions by
422 * setting the fields that are keys in the $values param to
423 * their corresponding values.
425 * @since 1.20
427 * @param array $values
428 * @param array $conditions
430 * @return boolean Success indicator
432 public function update( array $values, array $conditions = array() ) {
433 $dbw = wfGetDB( DB_MASTER );
435 return $dbw->update(
436 $this->getName(),
437 $this->getPrefixedValues( $values ),
438 $this->getPrefixedValues( $conditions ),
439 __METHOD__
440 ) !== false; // DatabaseBase::update does not always return true for success as documented...
444 * Computes the values of the summary fields of the objects matching the provided conditions.
446 * @since 1.20
448 * @param array|string|null $summaryFields
449 * @param array $conditions
451 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
452 $this->setReadDb( DB_MASTER );
454 foreach ( $this->select( null, $conditions ) as /* IORMRow */ $item ) {
455 $item->loadSummaryFields( $summaryFields );
456 $item->setSummaryMode( true );
457 $item->save();
460 $this->setReadDb( DB_SLAVE );
464 * Takes in an associative array with field names as keys and
465 * their values as value. The field names are prefixed with the
466 * db field prefix.
468 * @since 1.20
470 * @param array $values
472 * @return array
474 public function getPrefixedValues( array $values ) {
475 $prefixedValues = array();
477 foreach ( $values as $field => $value ) {
478 if ( is_integer( $field ) ) {
479 if ( is_array( $value ) ) {
480 $field = $value[0];
481 $value = $value[1];
483 else {
484 $value = explode( ' ', $value, 2 );
485 $value[0] = $this->getPrefixedField( $value[0] );
486 $prefixedValues[] = implode( ' ', $value );
487 continue;
491 $prefixedValues[$this->getPrefixedField( $field )] = $value;
494 return $prefixedValues;
498 * Takes in a field or array of fields and returns an
499 * array with their prefixed versions, ready for db usage.
501 * @since 1.20
503 * @param array|string $fields
505 * @return array
507 public function getPrefixedFields( array $fields ) {
508 foreach ( $fields as &$field ) {
509 $field = $this->getPrefixedField( $field );
512 return $fields;
516 * Takes in a field and returns an it's prefixed version, ready for db usage.
518 * @since 1.20
520 * @param string|array $field
522 * @return string
524 public function getPrefixedField( $field ) {
525 return $this->getFieldPrefix() . $field;
529 * Takes an array of field names with prefix and returns the unprefixed equivalent.
531 * @since 1.20
533 * @param array $fieldNames
535 * @return array
537 public function unprefixFieldNames( array $fieldNames ) {
538 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
542 * Takes a field name with prefix and returns the unprefixed equivalent.
544 * @since 1.20
546 * @param string $fieldName
548 * @return string
550 public function unprefixFieldName( $fieldName ) {
551 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
555 * Get an instance of this class.
557 * @since 1.20
559 * @return IORMTable
561 public static function singleton() {
562 $class = function_exists( 'get_called_class' ) ? get_called_class() : self::get_called_class();
564 if ( !array_key_exists( $class, self::$instanceCache ) ) {
565 self::$instanceCache[$class] = new $class;
568 return self::$instanceCache[$class];
572 * Compatibility fallback function so the singleton method works on PHP < 5.3.
573 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
575 * @since 1.20
577 * @return string
579 protected static function get_called_class() {
580 $bt = debug_backtrace();
581 $l = count($bt) - 1;
582 $matches = array();
583 while(empty($matches) && $l > -1){
584 $lines = file($bt[$l]['file']);
585 $callerLine = $lines[$bt[$l]['line']-1];
586 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
587 $callerLine,
588 $matches);
590 if (!isset($matches[1])) $matches[1]=NULL; //for notices
591 if ($matches[1] == 'self') {
592 $line = $bt[$l]['line']-1;
593 while ($line > 0 && strpos($lines[$line], 'class') === false) {
594 $line--;
596 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
598 return $matches[1];
602 * Get an array with fields from a database result,
603 * that can be fed directly to the constructor or
604 * to setFields.
606 * @since 1.20
608 * @param stdClass $result
610 * @return array
612 public function getFieldsFromDBResult( stdClass $result ) {
613 $result = (array)$result;
614 return array_combine(
615 $this->unprefixFieldNames( array_keys( $result ) ),
616 array_values( $result )
621 * @see ORMTable::newRowFromFromDBResult
623 * @deprecated use newRowFromFromDBResult instead
624 * @since 1.20
626 * @param stdClass $result
628 * @return IORMRow
630 public function newFromDBResult( stdClass $result ) {
631 return self::newRowFromFromDBResult( $result );
635 * Get a new instance of the class from a database result.
637 * @since 1.20
639 * @param stdClass $result
641 * @return IORMRow
643 public function newRowFromDBResult( stdClass $result ) {
644 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
648 * @see ORMTable::newRow
650 * @deprecated use newRow instead
651 * @since 1.20
653 * @param array $data
654 * @param boolean $loadDefaults
656 * @return IORMRow
658 public function newFromArray( array $data, $loadDefaults = false ) {
659 return static::newRow( $data, $loadDefaults );
663 * Get a new instance of the class from an array.
665 * @since 1.20
667 * @param array $data
668 * @param boolean $loadDefaults
670 * @return IORMRow
672 public function newRow( array $data, $loadDefaults = false ) {
673 $class = $this->getRowClass();
674 return new $class( $this, $data, $loadDefaults );
678 * Return the names of the fields.
680 * @since 1.20
682 * @return array
684 public function getFieldNames() {
685 return array_keys( $this->getFields() );
689 * Gets if the object can take a certain field.
691 * @since 1.20
693 * @param string $name
695 * @return boolean
697 public function canHaveField( $name ) {
698 return array_key_exists( $name, $this->getFields() );