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
26 * @license GNU GPL v2 or later
27 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
30 abstract class ORMTable
extends DBAccessBase
implements IORMTable
{
33 * Gets the db field prefix.
39 protected abstract function getFieldPrefix();
42 * Cache for instances, used by the singleton method.
45 * @var array of DBTable
47 protected static $instanceCache = array();
50 * ID of the database connection to use for read operations.
51 * Can be changed via @see setReadDb.
54 * @var integer DB_ enum
56 protected $readDb = DB_SLAVE
;
59 * Returns a list of default field values.
60 * field name => field value
66 public function getDefaults() {
71 * Returns a list of the summary fields.
72 * These are fields that cache computed values, such as the amount of linked objects of $type.
73 * This is relevant as one might not want to do actions such as log changes when these get updated.
79 public function getSummaryFields() {
84 * Selects the the specified fields of the records matching the provided
85 * conditions and returns them as DBDataObject. Field names get prefixed.
89 * @param array|string|null $fields
90 * @param array $conditions
91 * @param array $options
92 * @param string|null $functionName
96 public function select( $fields = null, array $conditions = array(),
97 array $options = array(), $functionName = null ) {
98 $res = $this->rawSelect( $fields, $conditions, $options, $functionName );
99 return new ORMResult( $this, $res );
103 * Selects the the specified fields of the records matching the provided
104 * conditions and returns them as DBDataObject. Field names get prefixed.
108 * @param array|string|null $fields
109 * @param array $conditions
110 * @param array $options
111 * @param string|null $functionName
113 * @return array of row objects
114 * @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
116 public function selectObjects( $fields = null, array $conditions = array(),
117 array $options = array(), $functionName = null ) {
118 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
122 foreach ( $result as $record ) {
123 $objects[] = $this->newRow( $record );
130 * Do the actual select.
134 * @param null|string|array $fields
135 * @param array $conditions
136 * @param array $options
137 * @param null|string $functionName
139 * @return ResultWrapper
140 * @throws DBQueryError if the quey failed (even if the database was in ignoreErrors mode).
142 public function rawSelect( $fields = null, array $conditions = array(),
143 array $options = array(), $functionName = null ) {
144 if ( is_null( $fields ) ) {
145 $fields = array_keys( $this->getFields() );
148 $fields = (array)$fields;
151 $dbr = $this->getReadDbConnection();
152 $result = $dbr->select(
154 $this->getPrefixedFields( $fields ),
155 $this->getPrefixedValues( $conditions ),
156 is_null( $functionName ) ? __METHOD__
: $functionName,
160 /* @var Exception $error */
163 if ( $result === false ) {
164 // Database connection was in "ignoreErrors" mode. We don't like that.
165 // So, we emulate the DBQueryError that should have been thrown.
166 $error = new DBQueryError(
171 is_null( $functionName ) ? __METHOD__
: $functionName
175 $this->releaseConnection( $dbr );
178 // Note: construct the error before releasing the connection,
179 // but throw it after.
187 * Selects the the specified fields of the records matching the provided
188 * conditions and returns them as associative arrays.
189 * Provided field names get prefixed.
190 * Returned field names will not have a prefix.
192 * When $collapse is true:
193 * If one field is selected, each item in the result array will be this field.
194 * If two fields are selected, each item in the result array will have as key
195 * the first field and as value the second field.
196 * If more then two fields are selected, each item will be an associative array.
200 * @param array|string|null $fields
201 * @param array $conditions
202 * @param array $options
203 * @param boolean $collapse Set to false to always return each result row as associative array.
204 * @param string|null $functionName
206 * @return array of array
208 public function selectFields( $fields = null, array $conditions = array(),
209 array $options = array(), $collapse = true, $functionName = null ) {
212 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
214 foreach ( $result as $record ) {
215 $objects[] = $this->getFieldsFromDBResult( $record );
219 if ( count( $fields ) === 1 ) {
220 $objects = array_map( 'array_shift', $objects );
222 elseif ( count( $fields ) === 2 ) {
225 foreach ( $objects as $object ) {
226 $o[array_shift( $object )] = array_shift( $object );
237 * Selects the the specified fields of the first matching record.
238 * Field names get prefixed.
242 * @param array|string|null $fields
243 * @param array $conditions
244 * @param array $options
245 * @param string|null $functionName
247 * @return IORMRow|bool False on failure
249 public function selectRow( $fields = null, array $conditions = array(),
250 array $options = array(), $functionName = null ) {
251 $options['LIMIT'] = 1;
253 $objects = $this->select( $fields, $conditions, $options, $functionName );
255 return ( !$objects ||
$objects->isEmpty() ) ?
false : $objects->current();
259 * Selects the the specified fields of the records matching the provided
260 * conditions. Field names do NOT get prefixed.
264 * @param array $fields
265 * @param array $conditions
266 * @param array $options
267 * @param string|null $functionName
269 * @return ResultWrapper
271 public function rawSelectRow( array $fields, array $conditions = array(),
272 array $options = array(), $functionName = null ) {
273 $dbr = $this->getReadDbConnection();
275 $result = $dbr->selectRow(
279 is_null( $functionName ) ? __METHOD__
: $functionName,
283 $this->releaseConnection( $dbr );
288 * Selects the the specified fields of the first record matching the provided
289 * conditions and returns it as an associative array, or false when nothing matches.
290 * This method makes use of selectFields and expects the same parameters and
291 * returns the same results (if there are any, if there are none, this method returns false).
292 * @see ORMTable::selectFields
296 * @param array|string|null $fields
297 * @param array $conditions
298 * @param array $options
299 * @param boolean $collapse Set to false to always return each result row as associative array.
300 * @param string|null $functionName
302 * @return mixed|array|bool False on failure
304 public function selectFieldsRow( $fields = null, array $conditions = array(),
305 array $options = array(), $collapse = true, $functionName = null ) {
306 $options['LIMIT'] = 1;
308 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
310 return empty( $objects ) ?
false : $objects[0];
314 * Returns if there is at least one record matching the provided conditions.
315 * Condition field names get prefixed.
319 * @param array $conditions
323 public function has( array $conditions = array() ) {
324 return $this->selectRow( array( 'id' ), $conditions ) !== false;
328 * Checks if the table exists
334 public function exists() {
335 $dbr = $this->getReadDbConnection();
336 $exists = $dbr->tableExists( $this->getName() );
337 $this->releaseConnection( $dbr );
343 * Returns the amount of matching records.
344 * Condition field names get prefixed.
346 * Note that this can be expensive on large tables.
347 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
351 * @param array $conditions
352 * @param array $options
356 public function count( array $conditions = array(), array $options = array() ) {
357 $res = $this->rawSelectRow(
358 array( 'rowcount' => 'COUNT(*)' ),
359 $this->getPrefixedValues( $conditions ),
364 return $res->rowcount
;
368 * Removes the object from the database.
372 * @param array $conditions
373 * @param string|null $functionName
375 * @return boolean Success indicator
377 public function delete( array $conditions, $functionName = null ) {
378 $dbw = $this->getWriteDbConnection();
380 $result = $dbw->delete(
382 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
383 is_null( $functionName ) ? __METHOD__
: $functionName
384 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
386 $this->releaseConnection( $dbw );
391 * Get API parameters for the fields supported by this object.
395 * @param boolean $requireParams
396 * @param boolean $setDefaults
400 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
412 $defaults = $this->getDefaults();
414 foreach ( $this->getFields() as $field => $type ) {
415 if ( $field == 'id' ) {
419 $hasDefault = array_key_exists( $field, $defaults );
421 $params[$field] = array(
422 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
423 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
426 if ( $type == 'array' ) {
427 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
430 if ( $setDefaults && $hasDefault ) {
431 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
432 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
440 * Returns an array with the fields and their descriptions.
442 * field name => field description
448 public function getFieldDescriptions() {
453 * Get the database ID used for read operations.
457 * @return integer DB_ enum
459 public function getReadDb() {
460 return $this->readDb
;
464 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
470 public function setReadDb( $db ) {
475 * Get the ID of the any foreign wiki to use as a target for database operations
479 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
481 public function getTargetWiki() {
486 * Set the ID of the any foreign wiki to use as a target for database operations
488 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
492 public function setTargetWiki( $wiki ) {
497 * Get the database type used for read operations.
498 * This is to be used instead of wfGetDB.
500 * @see LoadBalancer::getConnection
504 * @return DatabaseBase The database object
506 public function getReadDbConnection() {
507 return $this->getConnection( $this->getReadDb(), array() );
511 * Get the database type used for read operations.
512 * This is to be used instead of wfGetDB.
514 * @see LoadBalancer::getConnection
518 * @return DatabaseBase The database object
520 public function getWriteDbConnection() {
521 return $this->getConnection( DB_MASTER
, array() );
525 * Releases the lease on the given database connection. This is useful mainly
526 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
528 * @see LoadBalancer::reuseConnection
530 * @param DatabaseBase $db the database
534 public function releaseConnection( DatabaseBase
$db ) {
535 parent
::releaseConnection( $db ); // just make it public
539 * Update the records matching the provided conditions by
540 * setting the fields that are keys in the $values param to
541 * their corresponding values.
545 * @param array $values
546 * @param array $conditions
548 * @return boolean Success indicator
550 public function update( array $values, array $conditions = array() ) {
551 $dbw = $this->getWriteDbConnection();
553 $result = $dbw->update(
555 $this->getPrefixedValues( $values ),
556 $this->getPrefixedValues( $conditions ),
558 ) !== false; // DatabaseBase::update does not always return true for success as documented...
560 $this->releaseConnection( $dbw );
565 * Computes the values of the summary fields of the objects matching the provided conditions.
569 * @param array|string|null $summaryFields
570 * @param array $conditions
572 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
573 $slave = $this->getReadDb();
574 $this->setReadDb( DB_MASTER
);
579 foreach ( $this->select( null, $conditions ) as $item ) {
580 $item->loadSummaryFields( $summaryFields );
581 $item->setSummaryMode( true );
585 $this->setReadDb( $slave );
589 * Takes in an associative array with field names as keys and
590 * their values as value. The field names are prefixed with the
595 * @param array $values
599 public function getPrefixedValues( array $values ) {
600 $prefixedValues = array();
602 foreach ( $values as $field => $value ) {
603 if ( is_integer( $field ) ) {
604 if ( is_array( $value ) ) {
609 $value = explode( ' ', $value, 2 );
610 $value[0] = $this->getPrefixedField( $value[0] );
611 $prefixedValues[] = implode( ' ', $value );
616 $prefixedValues[$this->getPrefixedField( $field )] = $value;
619 return $prefixedValues;
623 * Takes in a field or array of fields and returns an
624 * array with their prefixed versions, ready for db usage.
628 * @param array|string $fields
632 public function getPrefixedFields( array $fields ) {
633 foreach ( $fields as &$field ) {
634 $field = $this->getPrefixedField( $field );
641 * Takes in a field and returns an it's prefixed version, ready for db usage.
645 * @param string|array $field
649 public function getPrefixedField( $field ) {
650 return $this->getFieldPrefix() . $field;
654 * Takes an array of field names with prefix and returns the unprefixed equivalent.
658 * @param array $fieldNames
662 public function unprefixFieldNames( array $fieldNames ) {
663 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
667 * Takes a field name with prefix and returns the unprefixed equivalent.
671 * @param string $fieldName
675 public function unprefixFieldName( $fieldName ) {
676 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
680 * Get an instance of this class.
686 public static function singleton() {
687 $class = get_called_class();
689 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
690 self
::$instanceCache[$class] = new $class;
693 return self
::$instanceCache[$class];
697 * Get an array with fields from a database result,
698 * that can be fed directly to the constructor or
703 * @param stdClass $result
707 public function getFieldsFromDBResult( stdClass
$result ) {
708 $result = (array)$result;
709 return array_combine(
710 $this->unprefixFieldNames( array_keys( $result ) ),
711 array_values( $result )
716 * @see ORMTable::newRowFromFromDBResult
718 * @deprecated use newRowFromDBResult instead
721 * @param stdClass $result
725 public function newFromDBResult( stdClass
$result ) {
726 return self
::newRowFromDBResult( $result );
730 * Get a new instance of the class from a database result.
734 * @param stdClass $result
738 public function newRowFromDBResult( stdClass
$result ) {
739 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
743 * @see ORMTable::newRow
745 * @deprecated use newRow instead
749 * @param boolean $loadDefaults
753 public function newFromArray( array $data, $loadDefaults = false ) {
754 return static::newRow( $data, $loadDefaults );
758 * Get a new instance of the class from an array.
763 * @param boolean $loadDefaults
767 public function newRow( array $data, $loadDefaults = false ) {
768 $class = $this->getRowClass();
769 return new $class( $this, $data, $loadDefaults );
773 * Return the names of the fields.
779 public function getFieldNames() {
780 return array_keys( $this->getFields() );
784 * Gets if the object can take a certain field.
788 * @param string $name
792 public function canHaveField( $name ) {
793 return array_key_exists( $name, $this->getFields() );