(bug 31565) Option to use group members on Special:UserRights
[mediawiki.git] / includes / db / ORMTable.php
blob0756ce83f439438ed3e2cf2b1f026843eefa66c7
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
23 * @file ORMTable.php
24 * @ingroup ORM
26 * @license GNU GPL v2 or later
27 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
30 abstract class ORMTable implements IORMTable {
32 /**
33 * Gets the db field prefix.
35 * @since 1.20
37 * @return string
39 protected abstract function getFieldPrefix();
41 /**
42 * Cache for instances, used by the singleton method.
44 * @since 1.20
45 * @var array of DBTable
47 protected static $instanceCache = array();
49 /**
50 * ID of the database connection to use for read operations.
51 * Can be changed via @see setReadDb.
53 * @since 1.20
54 * @var integer DB_ enum
56 protected $readDb = DB_SLAVE;
58 /**
59 * The ID of any foreign wiki to use as a target for database operations,
60 * or false to use the local wiki.
62 * @since 1.20
63 * @var String|bool
65 protected $wiki = false;
67 /**
68 * Returns a list of default field values.
69 * field name => field value
71 * @since 1.20
73 * @return array
75 public function getDefaults() {
76 return array();
79 /**
80 * Returns a list of the summary fields.
81 * These are fields that cache computed values, such as the amount of linked objects of $type.
82 * This is relevant as one might not want to do actions such as log changes when these get updated.
84 * @since 1.20
86 * @return array
88 public function getSummaryFields() {
89 return array();
92 /**
93 * Selects the the specified fields of the records matching the provided
94 * conditions and returns them as DBDataObject. Field names get prefixed.
96 * @since 1.20
98 * @param array|string|null $fields
99 * @param array $conditions
100 * @param array $options
101 * @param string|null $functionName
103 * @return ORMResult
105 public function select( $fields = null, array $conditions = array(),
106 array $options = array(), $functionName = null ) {
107 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
111 * Selects the the specified fields of the records matching the provided
112 * conditions and returns them as DBDataObject. Field names get prefixed.
114 * @since 1.20
116 * @param array|string|null $fields
117 * @param array $conditions
118 * @param array $options
119 * @param string|null $functionName
121 * @return array of self
123 public function selectObjects( $fields = null, array $conditions = array(),
124 array $options = array(), $functionName = null ) {
125 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
127 $objects = array();
129 foreach ( $result as $record ) {
130 $objects[] = $this->newRow( $record );
133 return $objects;
137 * Do the actual select.
139 * @since 1.20
141 * @param null|string|array $fields
142 * @param array $conditions
143 * @param array $options
144 * @param null|string $functionName
146 * @return ResultWrapper
148 public function rawSelect( $fields = null, array $conditions = array(),
149 array $options = array(), $functionName = null ) {
150 if ( is_null( $fields ) ) {
151 $fields = array_keys( $this->getFields() );
153 else {
154 $fields = (array)$fields;
157 $dbr = $this->getReadDbConnection();
158 $result = $dbr->select(
159 $this->getName(),
160 $this->getPrefixedFields( $fields ),
161 $this->getPrefixedValues( $conditions ),
162 is_null( $functionName ) ? __METHOD__ : $functionName,
163 $options
166 $this->releaseConnection( $dbr );
167 return $result;
171 * Selects the the specified fields of the records matching the provided
172 * conditions and returns them as associative arrays.
173 * Provided field names get prefixed.
174 * Returned field names will not have a prefix.
176 * When $collapse is true:
177 * If one field is selected, each item in the result array will be this field.
178 * If two fields are selected, each item in the result array will have as key
179 * the first field and as value the second field.
180 * If more then two fields are selected, each item will be an associative array.
182 * @since 1.20
184 * @param array|string|null $fields
185 * @param array $conditions
186 * @param array $options
187 * @param boolean $collapse Set to false to always return each result row as associative array.
188 * @param string|null $functionName
190 * @return array of array
192 public function selectFields( $fields = null, array $conditions = array(),
193 array $options = array(), $collapse = true, $functionName = null ) {
194 $objects = array();
196 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
198 foreach ( $result as $record ) {
199 $objects[] = $this->getFieldsFromDBResult( $record );
202 if ( $collapse ) {
203 if ( count( $fields ) === 1 ) {
204 $objects = array_map( 'array_shift', $objects );
206 elseif ( count( $fields ) === 2 ) {
207 $o = array();
209 foreach ( $objects as $object ) {
210 $o[array_shift( $object )] = array_shift( $object );
213 $objects = $o;
217 return $objects;
221 * Selects the the specified fields of the first matching record.
222 * Field names get prefixed.
224 * @since 1.20
226 * @param array|string|null $fields
227 * @param array $conditions
228 * @param array $options
229 * @param string|null $functionName
231 * @return IORMRow|bool False on failure
233 public function selectRow( $fields = null, array $conditions = array(),
234 array $options = array(), $functionName = null ) {
235 $options['LIMIT'] = 1;
237 $objects = $this->select( $fields, $conditions, $options, $functionName );
239 return $objects->isEmpty() ? false : $objects->current();
243 * Selects the the specified fields of the records matching the provided
244 * conditions. Field names do NOT get prefixed.
246 * @since 1.20
248 * @param array $fields
249 * @param array $conditions
250 * @param array $options
251 * @param string|null $functionName
253 * @return ResultWrapper
255 public function rawSelectRow( array $fields, array $conditions = array(),
256 array $options = array(), $functionName = null ) {
257 $dbr = $this->getReadDbConnection();
259 $result = $dbr->selectRow(
260 $this->getName(),
261 $fields,
262 $conditions,
263 is_null( $functionName ) ? __METHOD__ : $functionName,
264 $options
267 $this->releaseConnection( $dbr );
268 return $result;
272 * Selects the the specified fields of the first record matching the provided
273 * conditions and returns it as an associative array, or false when nothing matches.
274 * This method makes use of selectFields and expects the same parameters and
275 * returns the same results (if there are any, if there are none, this method returns false).
276 * @see ORMTable::selectFields
278 * @since 1.20
280 * @param array|string|null $fields
281 * @param array $conditions
282 * @param array $options
283 * @param boolean $collapse Set to false to always return each result row as associative array.
284 * @param string|null $functionName
286 * @return mixed|array|bool False on failure
288 public function selectFieldsRow( $fields = null, array $conditions = array(),
289 array $options = array(), $collapse = true, $functionName = null ) {
290 $options['LIMIT'] = 1;
292 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
294 return empty( $objects ) ? false : $objects[0];
298 * Returns if there is at least one record matching the provided conditions.
299 * Condition field names get prefixed.
301 * @since 1.20
303 * @param array $conditions
305 * @return boolean
307 public function has( array $conditions = array() ) {
308 return $this->selectRow( array( 'id' ), $conditions ) !== false;
312 * Returns the amount of matching records.
313 * Condition field names get prefixed.
315 * Note that this can be expensive on large tables.
316 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
318 * @since 1.20
320 * @param array $conditions
321 * @param array $options
323 * @return integer
325 public function count( array $conditions = array(), array $options = array() ) {
326 $res = $this->rawSelectRow(
327 array( 'rowcount' => 'COUNT(*)' ),
328 $this->getPrefixedValues( $conditions ),
329 $options
332 return $res->rowcount;
336 * Removes the object from the database.
338 * @since 1.20
340 * @param array $conditions
341 * @param string|null $functionName
343 * @return boolean Success indicator
345 public function delete( array $conditions, $functionName = null ) {
346 $dbw = $this->getWriteDbConnection();
348 $result = $dbw->delete(
349 $this->getName(),
350 $conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
351 $functionName
352 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
354 $this->releaseConnection( $dbw );
355 return $result;
359 * Get API parameters for the fields supported by this object.
361 * @since 1.20
363 * @param boolean $requireParams
364 * @param boolean $setDefaults
366 * @return array
368 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
369 $typeMap = array(
370 'id' => 'integer',
371 'int' => 'integer',
372 'float' => 'NULL',
373 'str' => 'string',
374 'bool' => 'integer',
375 'array' => 'string',
376 'blob' => 'string',
379 $params = array();
380 $defaults = $this->getDefaults();
382 foreach ( $this->getFields() as $field => $type ) {
383 if ( $field == 'id' ) {
384 continue;
387 $hasDefault = array_key_exists( $field, $defaults );
389 $params[$field] = array(
390 ApiBase::PARAM_TYPE => $typeMap[$type],
391 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
394 if ( $type == 'array' ) {
395 $params[$field][ApiBase::PARAM_ISMULTI] = true;
398 if ( $setDefaults && $hasDefault ) {
399 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
400 $params[$field][ApiBase::PARAM_DFLT] = $default;
404 return $params;
408 * Returns an array with the fields and their descriptions.
410 * field name => field description
412 * @since 1.20
414 * @return array
416 public function getFieldDescriptions() {
417 return array();
421 * Get the database ID used for read operations.
423 * @since 1.20
425 * @return integer DB_ enum
427 public function getReadDb() {
428 return $this->readDb;
432 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
434 * @param integer $db
436 * @since 1.20
438 public function setReadDb( $db ) {
439 $this->readDb = $db;
443 * Get the ID of the any foreign wiki to use as a target for database operations
445 * @since 1.20
447 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
449 public function getTargetWiki() {
450 return $this->wiki;
454 * Set the ID of the any foreign wiki to use as a target for database operations
456 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
458 * @since 1.20
460 public function setTargetWiki( $wiki ) {
461 $this->wiki = $wiki;
465 * Get the database type used for read operations.
466 * This is to be used instead of wfGetDB.
468 * @see LoadBalancer::getConnection
470 * @since 1.20
472 * @return DatabaseBase The database object
474 public function getReadDbConnection() {
475 return $this->getLoadBalancer()->getConnection( $this->getReadDb(), array(), $this->getTargetWiki() );
479 * Get the database type used for read operations.
480 * This is to be used instead of wfGetDB.
482 * @see LoadBalancer::getConnection
484 * @since 1.20
486 * @return DatabaseBase The database object
488 public function getWriteDbConnection() {
489 return $this->getLoadBalancer()->getConnection( DB_MASTER, array(), $this->getTargetWiki() );
493 * Get the database type used for read operations.
495 * @see wfGetLB
497 * @since 1.20
499 * @return LoadBalancer The database load balancer object
501 public function getLoadBalancer() {
502 return wfGetLB( $this->getTargetWiki() );
506 * Releases the lease on the given database connection. This is useful mainly
507 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
509 * @see LoadBalancer::reuseConnection
511 * @param DatabaseBase $db the database
513 * @since 1.20
515 public function releaseConnection( DatabaseBase $db ) {
516 if ( $this->wiki !== false ) {
517 // recycle connection to foreign wiki
518 $this->getLoadBalancer()->reuseConnection( $db );
523 * Update the records matching the provided conditions by
524 * setting the fields that are keys in the $values param to
525 * their corresponding values.
527 * @since 1.20
529 * @param array $values
530 * @param array $conditions
532 * @return boolean Success indicator
534 public function update( array $values, array $conditions = array() ) {
535 $dbw = $this->getWriteDbConnection();
537 $result = $dbw->update(
538 $this->getName(),
539 $this->getPrefixedValues( $values ),
540 $this->getPrefixedValues( $conditions ),
541 __METHOD__
542 ) !== false; // DatabaseBase::update does not always return true for success as documented...
544 $this->releaseConnection( $dbw );
545 return $result;
549 * Computes the values of the summary fields of the objects matching the provided conditions.
551 * @since 1.20
553 * @param array|string|null $summaryFields
554 * @param array $conditions
556 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
557 $slave = $this->getReadDb();
558 $this->setReadDb( DB_MASTER );
561 * @var IORMRow $item
563 foreach ( $this->select( null, $conditions ) as $item ) {
564 $item->loadSummaryFields( $summaryFields );
565 $item->setSummaryMode( true );
566 $item->save();
569 $this->setReadDb( $slave );
573 * Takes in an associative array with field names as keys and
574 * their values as value. The field names are prefixed with the
575 * db field prefix.
577 * @since 1.20
579 * @param array $values
581 * @return array
583 public function getPrefixedValues( array $values ) {
584 $prefixedValues = array();
586 foreach ( $values as $field => $value ) {
587 if ( is_integer( $field ) ) {
588 if ( is_array( $value ) ) {
589 $field = $value[0];
590 $value = $value[1];
592 else {
593 $value = explode( ' ', $value, 2 );
594 $value[0] = $this->getPrefixedField( $value[0] );
595 $prefixedValues[] = implode( ' ', $value );
596 continue;
600 $prefixedValues[$this->getPrefixedField( $field )] = $value;
603 return $prefixedValues;
607 * Takes in a field or array of fields and returns an
608 * array with their prefixed versions, ready for db usage.
610 * @since 1.20
612 * @param array|string $fields
614 * @return array
616 public function getPrefixedFields( array $fields ) {
617 foreach ( $fields as &$field ) {
618 $field = $this->getPrefixedField( $field );
621 return $fields;
625 * Takes in a field and returns an it's prefixed version, ready for db usage.
627 * @since 1.20
629 * @param string|array $field
631 * @return string
633 public function getPrefixedField( $field ) {
634 return $this->getFieldPrefix() . $field;
638 * Takes an array of field names with prefix and returns the unprefixed equivalent.
640 * @since 1.20
642 * @param array $fieldNames
644 * @return array
646 public function unprefixFieldNames( array $fieldNames ) {
647 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
651 * Takes a field name with prefix and returns the unprefixed equivalent.
653 * @since 1.20
655 * @param string $fieldName
657 * @return string
659 public function unprefixFieldName( $fieldName ) {
660 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
664 * Get an instance of this class.
666 * @since 1.20
668 * @return IORMTable
670 public static function singleton() {
671 $class = get_called_class();
673 if ( !array_key_exists( $class, self::$instanceCache ) ) {
674 self::$instanceCache[$class] = new $class;
677 return self::$instanceCache[$class];
681 * Get an array with fields from a database result,
682 * that can be fed directly to the constructor or
683 * to setFields.
685 * @since 1.20
687 * @param stdClass $result
689 * @return array
691 public function getFieldsFromDBResult( stdClass $result ) {
692 $result = (array)$result;
693 return array_combine(
694 $this->unprefixFieldNames( array_keys( $result ) ),
695 array_values( $result )
700 * @see ORMTable::newRowFromFromDBResult
702 * @deprecated use newRowFromDBResult instead
703 * @since 1.20
705 * @param stdClass $result
707 * @return IORMRow
709 public function newFromDBResult( stdClass $result ) {
710 return self::newRowFromDBResult( $result );
714 * Get a new instance of the class from a database result.
716 * @since 1.20
718 * @param stdClass $result
720 * @return IORMRow
722 public function newRowFromDBResult( stdClass $result ) {
723 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
727 * @see ORMTable::newRow
729 * @deprecated use newRow instead
730 * @since 1.20
732 * @param array $data
733 * @param boolean $loadDefaults
735 * @return IORMRow
737 public function newFromArray( array $data, $loadDefaults = false ) {
738 return static::newRow( $data, $loadDefaults );
742 * Get a new instance of the class from an array.
744 * @since 1.20
746 * @param array $data
747 * @param boolean $loadDefaults
749 * @return IORMRow
751 public function newRow( array $data, $loadDefaults = false ) {
752 $class = $this->getRowClass();
753 return new $class( $this, $data, $loadDefaults );
757 * Return the names of the fields.
759 * @since 1.20
761 * @return array
763 public function getFieldNames() {
764 return array_keys( $this->getFields() );
768 * Gets if the object can take a certain field.
770 * @since 1.20
772 * @param string $name
774 * @return boolean
776 public function canHaveField( $name ) {
777 return array_key_exists( $name, $this->getFields() );