Merge "(bug 43801) add a getter for ICU version to ICUCollation"
[mediawiki.git] / includes / db / ORMTable.php
blob06f88c1829393864cd7d2bf8fc9610352c3aa2a0
1 <?php
2 /**
3 * Abstract base class for representing a single database table.
4 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
21 * @since 1.20
22 * Non-abstract since 1.21
24 * @file ORMTable.php
25 * @ingroup ORM
27 * @license GNU GPL v2 or later
28 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
31 class ORMTable extends DBAccessBase implements IORMTable {
33 /**
34 * Cache for instances, used by the singleton method.
36 * @since 1.20
37 * @deprecated since 1.21
39 * @var ORMTable[]
41 protected static $instanceCache = array();
43 /**
44 * @since 1.21
46 * @var string
48 protected $tableName;
50 /**
51 * @since 1.21
53 * @var string[]
55 protected $fields = array();
57 /**
58 * @since 1.21
60 * @var string
62 protected $fieldPrefix = '';
64 /**
65 * @since 1.21
67 * @var string
69 protected $rowClass = 'ORMRow';
71 /**
72 * @since 1.21
74 * @var array
76 protected $defaults = array();
78 /**
79 * ID of the database connection to use for read operations.
80 * Can be changed via @see setReadDb.
82 * @since 1.20
84 * @var integer DB_ enum
86 protected $readDb = DB_SLAVE;
88 /**
89 * Constructor.
91 * @since 1.21
93 * @param string $tableName
94 * @param string[] $fields
95 * @param array $defaults
96 * @param string|null $rowClass
97 * @param string $fieldPrefix
99 public function __construct( $tableName = '', array $fields = array(), array $defaults = array(), $rowClass = null, $fieldPrefix = '' ) {
100 $this->tableName = $tableName;
101 $this->fields = $fields;
102 $this->defaults = $defaults;
104 if ( is_string( $rowClass ) ) {
105 $this->rowClass = $rowClass;
108 $this->fieldPrefix = $fieldPrefix;
112 * @see IORMTable::getName
114 * @since 1.21
116 * @return string
117 * @throws MWException
119 public function getName() {
120 if ( $this->tableName === '' ) {
121 throw new MWException( 'The table name needs to be set' );
124 return $this->tableName;
128 * Gets the db field prefix.
130 * @since 1.20
132 * @return string
134 protected function getFieldPrefix() {
135 return $this->fieldPrefix;
139 * @see IORMTable::getRowClass
141 * @since 1.21
143 * @return string
145 public function getRowClass() {
146 return $this->rowClass;
150 * @see ORMTable::getFields
152 * @since 1.21
154 * @return array
155 * @throws MWException
157 public function getFields() {
158 if ( $this->fields === array() ) {
159 throw new MWException( 'The table needs to have one or more fields' );
162 return $this->fields;
166 * Returns a list of default field values.
167 * field name => field value
169 * @since 1.20
171 * @return array
173 public function getDefaults() {
174 return $this->defaults;
178 * Returns a list of the summary fields.
179 * These are fields that cache computed values, such as the amount of linked objects of $type.
180 * This is relevant as one might not want to do actions such as log changes when these get updated.
182 * @since 1.20
184 * @return array
186 public function getSummaryFields() {
187 return array();
191 * Selects the the specified fields of the records matching the provided
192 * conditions and returns them as DBDataObject. Field names get prefixed.
194 * @since 1.20
196 * @param array|string|null $fields
197 * @param array $conditions
198 * @param array $options
199 * @param string|null $functionName
201 * @return ORMResult
203 public function select( $fields = null, array $conditions = array(),
204 array $options = array(), $functionName = null ) {
205 $res = $this->rawSelect( $fields, $conditions, $options, $functionName );
206 return new ORMResult( $this, $res );
210 * Selects the the specified fields of the records matching the provided
211 * conditions and returns them as DBDataObject. Field names get prefixed.
213 * @since 1.20
215 * @param array|string|null $fields
216 * @param array $conditions
217 * @param array $options
218 * @param string|null $functionName
220 * @return array of row objects
221 * @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
223 public function selectObjects( $fields = null, array $conditions = array(),
224 array $options = array(), $functionName = null ) {
225 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
227 $objects = array();
229 foreach ( $result as $record ) {
230 $objects[] = $this->newRow( $record );
233 return $objects;
237 * Do the actual select.
239 * @since 1.20
241 * @param null|string|array $fields
242 * @param array $conditions
243 * @param array $options
244 * @param null|string $functionName
246 * @return ResultWrapper
247 * @throws DBQueryError if the quey failed (even if the database was in ignoreErrors mode).
249 public function rawSelect( $fields = null, array $conditions = array(),
250 array $options = array(), $functionName = null ) {
251 if ( is_null( $fields ) ) {
252 $fields = array_keys( $this->getFields() );
254 else {
255 $fields = (array)$fields;
258 $dbr = $this->getReadDbConnection();
259 $result = $dbr->select(
260 $this->getName(),
261 $this->getPrefixedFields( $fields ),
262 $this->getPrefixedValues( $conditions ),
263 is_null( $functionName ) ? __METHOD__ : $functionName,
264 $options
267 /* @var Exception $error */
268 $error = null;
270 if ( $result === false ) {
271 // Database connection was in "ignoreErrors" mode. We don't like that.
272 // So, we emulate the DBQueryError that should have been thrown.
273 $error = new DBQueryError(
274 $dbr,
275 $dbr->lastError(),
276 $dbr->lastErrno(),
277 $dbr->lastQuery(),
278 is_null( $functionName ) ? __METHOD__ : $functionName
282 $this->releaseConnection( $dbr );
284 if ( $error ) {
285 // Note: construct the error before releasing the connection,
286 // but throw it after.
287 throw $error;
290 return $result;
294 * Selects the the specified fields of the records matching the provided
295 * conditions and returns them as associative arrays.
296 * Provided field names get prefixed.
297 * Returned field names will not have a prefix.
299 * When $collapse is true:
300 * If one field is selected, each item in the result array will be this field.
301 * If two fields are selected, each item in the result array will have as key
302 * the first field and as value the second field.
303 * If more then two fields are selected, each item will be an associative array.
305 * @since 1.20
307 * @param array|string|null $fields
308 * @param array $conditions
309 * @param array $options
310 * @param boolean $collapse Set to false to always return each result row as associative array.
311 * @param string|null $functionName
313 * @return array of array
315 public function selectFields( $fields = null, array $conditions = array(),
316 array $options = array(), $collapse = true, $functionName = null ) {
317 $objects = array();
319 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
321 foreach ( $result as $record ) {
322 $objects[] = $this->getFieldsFromDBResult( $record );
325 if ( $collapse ) {
326 if ( count( $fields ) === 1 ) {
327 $objects = array_map( 'array_shift', $objects );
329 elseif ( count( $fields ) === 2 ) {
330 $o = array();
332 foreach ( $objects as $object ) {
333 $o[array_shift( $object )] = array_shift( $object );
336 $objects = $o;
340 return $objects;
344 * Selects the the specified fields of the first matching record.
345 * Field names get prefixed.
347 * @since 1.20
349 * @param array|string|null $fields
350 * @param array $conditions
351 * @param array $options
352 * @param string|null $functionName
354 * @return IORMRow|bool False on failure
356 public function selectRow( $fields = null, array $conditions = array(),
357 array $options = array(), $functionName = null ) {
358 $options['LIMIT'] = 1;
360 $objects = $this->select( $fields, $conditions, $options, $functionName );
362 return ( !$objects || $objects->isEmpty() ) ? false : $objects->current();
366 * Selects the the specified fields of the records matching the provided
367 * conditions. Field names do NOT get prefixed.
369 * @since 1.20
371 * @param array $fields
372 * @param array $conditions
373 * @param array $options
374 * @param string|null $functionName
376 * @return ResultWrapper
378 public function rawSelectRow( array $fields, array $conditions = array(),
379 array $options = array(), $functionName = null ) {
380 $dbr = $this->getReadDbConnection();
382 $result = $dbr->selectRow(
383 $this->getName(),
384 $fields,
385 $conditions,
386 is_null( $functionName ) ? __METHOD__ : $functionName,
387 $options
390 $this->releaseConnection( $dbr );
391 return $result;
395 * Selects the the specified fields of the first record matching the provided
396 * conditions and returns it as an associative array, or false when nothing matches.
397 * This method makes use of selectFields and expects the same parameters and
398 * returns the same results (if there are any, if there are none, this method returns false).
399 * @see ORMTable::selectFields
401 * @since 1.20
403 * @param array|string|null $fields
404 * @param array $conditions
405 * @param array $options
406 * @param boolean $collapse Set to false to always return each result row as associative array.
407 * @param string|null $functionName
409 * @return mixed|array|bool False on failure
411 public function selectFieldsRow( $fields = null, array $conditions = array(),
412 array $options = array(), $collapse = true, $functionName = null ) {
413 $options['LIMIT'] = 1;
415 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
417 return empty( $objects ) ? false : $objects[0];
421 * Returns if there is at least one record matching the provided conditions.
422 * Condition field names get prefixed.
424 * @since 1.20
426 * @param array $conditions
428 * @return boolean
430 public function has( array $conditions = array() ) {
431 return $this->selectRow( array( 'id' ), $conditions ) !== false;
435 * Checks if the table exists
437 * @since 1.21
439 * @return boolean
441 public function exists() {
442 $dbr = $this->getReadDbConnection();
443 $exists = $dbr->tableExists( $this->getName() );
444 $this->releaseConnection( $dbr );
446 return $exists;
450 * Returns the amount of matching records.
451 * Condition field names get prefixed.
453 * Note that this can be expensive on large tables.
454 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
456 * @since 1.20
458 * @param array $conditions
459 * @param array $options
461 * @return integer
463 public function count( array $conditions = array(), array $options = array() ) {
464 $res = $this->rawSelectRow(
465 array( 'rowcount' => 'COUNT(*)' ),
466 $this->getPrefixedValues( $conditions ),
467 $options,
468 __METHOD__
471 return $res->rowcount;
475 * Removes the object from the database.
477 * @since 1.20
479 * @param array $conditions
480 * @param string|null $functionName
482 * @return boolean Success indicator
484 public function delete( array $conditions, $functionName = null ) {
485 $dbw = $this->getWriteDbConnection();
487 $result = $dbw->delete(
488 $this->getName(),
489 $conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
490 is_null( $functionName ) ? __METHOD__ : $functionName
491 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
493 $this->releaseConnection( $dbw );
494 return $result;
498 * Get API parameters for the fields supported by this object.
500 * @since 1.20
502 * @param boolean $requireParams
503 * @param boolean $setDefaults
505 * @return array
507 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
508 $typeMap = array(
509 'id' => 'integer',
510 'int' => 'integer',
511 'float' => 'NULL',
512 'str' => 'string',
513 'bool' => 'integer',
514 'array' => 'string',
515 'blob' => 'string',
518 $params = array();
519 $defaults = $this->getDefaults();
521 foreach ( $this->getFields() as $field => $type ) {
522 if ( $field == 'id' ) {
523 continue;
526 $hasDefault = array_key_exists( $field, $defaults );
528 $params[$field] = array(
529 ApiBase::PARAM_TYPE => $typeMap[$type],
530 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
533 if ( $type == 'array' ) {
534 $params[$field][ApiBase::PARAM_ISMULTI] = true;
537 if ( $setDefaults && $hasDefault ) {
538 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
539 $params[$field][ApiBase::PARAM_DFLT] = $default;
543 return $params;
547 * Returns an array with the fields and their descriptions.
549 * field name => field description
551 * @since 1.20
553 * @return array
555 public function getFieldDescriptions() {
556 return array();
560 * Get the database ID used for read operations.
562 * @since 1.20
564 * @return integer DB_ enum
566 public function getReadDb() {
567 return $this->readDb;
571 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
573 * @param integer $db
575 * @since 1.20
577 public function setReadDb( $db ) {
578 $this->readDb = $db;
582 * Get the ID of the any foreign wiki to use as a target for database operations
584 * @since 1.20
586 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
588 public function getTargetWiki() {
589 return $this->wiki;
593 * Set the ID of the any foreign wiki to use as a target for database operations
595 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
597 * @since 1.20
599 public function setTargetWiki( $wiki ) {
600 $this->wiki = $wiki;
604 * Get the database type used for read operations.
605 * This is to be used instead of wfGetDB.
607 * @see LoadBalancer::getConnection
609 * @since 1.20
611 * @return DatabaseBase The database object
613 public function getReadDbConnection() {
614 return $this->getConnection( $this->getReadDb(), array() );
618 * Get the database type used for read operations.
619 * This is to be used instead of wfGetDB.
621 * @see LoadBalancer::getConnection
623 * @since 1.20
625 * @return DatabaseBase The database object
627 public function getWriteDbConnection() {
628 return $this->getConnection( DB_MASTER, array() );
632 * Releases the lease on the given database connection. This is useful mainly
633 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
635 * @see LoadBalancer::reuseConnection
637 * @param DatabaseBase $db the database
639 * @since 1.20
641 public function releaseConnection( DatabaseBase $db ) {
642 parent::releaseConnection( $db ); // just make it public
646 * Update the records matching the provided conditions by
647 * setting the fields that are keys in the $values param to
648 * their corresponding values.
650 * @since 1.20
652 * @param array $values
653 * @param array $conditions
655 * @return boolean Success indicator
657 public function update( array $values, array $conditions = array() ) {
658 $dbw = $this->getWriteDbConnection();
660 $result = $dbw->update(
661 $this->getName(),
662 $this->getPrefixedValues( $values ),
663 $this->getPrefixedValues( $conditions ),
664 __METHOD__
665 ) !== false; // DatabaseBase::update does not always return true for success as documented...
667 $this->releaseConnection( $dbw );
668 return $result;
672 * Computes the values of the summary fields of the objects matching the provided conditions.
674 * @since 1.20
676 * @param array|string|null $summaryFields
677 * @param array $conditions
679 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
680 $slave = $this->getReadDb();
681 $this->setReadDb( DB_MASTER );
684 * @var IORMRow $item
686 foreach ( $this->select( null, $conditions ) as $item ) {
687 $item->loadSummaryFields( $summaryFields );
688 $item->setSummaryMode( true );
689 $item->save();
692 $this->setReadDb( $slave );
696 * Takes in an associative array with field names as keys and
697 * their values as value. The field names are prefixed with the
698 * db field prefix.
700 * @since 1.20
702 * @param array $values
704 * @return array
706 public function getPrefixedValues( array $values ) {
707 $prefixedValues = array();
709 foreach ( $values as $field => $value ) {
710 if ( is_integer( $field ) ) {
711 if ( is_array( $value ) ) {
712 $field = $value[0];
713 $value = $value[1];
715 else {
716 $value = explode( ' ', $value, 2 );
717 $value[0] = $this->getPrefixedField( $value[0] );
718 $prefixedValues[] = implode( ' ', $value );
719 continue;
723 $prefixedValues[$this->getPrefixedField( $field )] = $value;
726 return $prefixedValues;
730 * Takes in a field or array of fields and returns an
731 * array with their prefixed versions, ready for db usage.
733 * @since 1.20
735 * @param array|string $fields
737 * @return array
739 public function getPrefixedFields( array $fields ) {
740 foreach ( $fields as &$field ) {
741 $field = $this->getPrefixedField( $field );
744 return $fields;
748 * Takes in a field and returns an it's prefixed version, ready for db usage.
750 * @since 1.20
752 * @param string|array $field
754 * @return string
756 public function getPrefixedField( $field ) {
757 return $this->getFieldPrefix() . $field;
761 * Takes an array of field names with prefix and returns the unprefixed equivalent.
763 * @since 1.20
765 * @param array $fieldNames
767 * @return array
769 public function unprefixFieldNames( array $fieldNames ) {
770 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
774 * Takes a field name with prefix and returns the unprefixed equivalent.
776 * @since 1.20
778 * @param string $fieldName
780 * @return string
782 public function unprefixFieldName( $fieldName ) {
783 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
787 * Get an instance of this class.
789 * @since 1.20
790 * @deprecated since 1.21
792 * @return IORMTable
794 public static function singleton() {
795 $class = get_called_class();
797 if ( !array_key_exists( $class, self::$instanceCache ) ) {
798 self::$instanceCache[$class] = new $class;
801 return self::$instanceCache[$class];
805 * Get an array with fields from a database result,
806 * that can be fed directly to the constructor or
807 * to setFields.
809 * @since 1.20
811 * @param stdClass $result
813 * @return array
815 public function getFieldsFromDBResult( stdClass $result ) {
816 $result = (array)$result;
817 return array_combine(
818 $this->unprefixFieldNames( array_keys( $result ) ),
819 array_values( $result )
824 * @see ORMTable::newRowFromFromDBResult
826 * @deprecated use newRowFromDBResult instead
827 * @since 1.20
829 * @param stdClass $result
831 * @return IORMRow
833 public function newFromDBResult( stdClass $result ) {
834 return self::newRowFromDBResult( $result );
838 * Get a new instance of the class from a database result.
840 * @since 1.20
842 * @param stdClass $result
844 * @return IORMRow
846 public function newRowFromDBResult( stdClass $result ) {
847 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
851 * @see ORMTable::newRow
853 * @deprecated use newRow instead
854 * @since 1.20
856 * @param array $data
857 * @param boolean $loadDefaults
859 * @return IORMRow
861 public function newFromArray( array $data, $loadDefaults = false ) {
862 return static::newRow( $data, $loadDefaults );
866 * Get a new instance of the class from an array.
868 * @since 1.20
870 * @param array $data
871 * @param boolean $loadDefaults
873 * @return IORMRow
875 public function newRow( array $data, $loadDefaults = false ) {
876 $class = $this->getRowClass();
877 return new $class( $this, $data, $loadDefaults );
881 * Return the names of the fields.
883 * @since 1.20
885 * @return array
887 public function getFieldNames() {
888 return array_keys( $this->getFields() );
892 * Gets if the object can take a certain field.
894 * @since 1.20
896 * @param string $name
898 * @return boolean
900 public function canHaveField( $name ) {
901 return array_key_exists( $name, $this->getFields() );