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
22 * Non-abstract since 1.21
27 * @license GNU GPL v2 or later
28 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
31 class ORMTable
extends DBAccessBase
implements IORMTable
{
33 * Cache for instances, used by the singleton method.
36 * @deprecated since 1.21
40 protected static $instanceCache = array();
54 protected $fields = array();
61 protected $fieldPrefix = '';
68 protected $rowClass = 'ORMRow';
75 protected $defaults = array();
78 * ID of the database connection to use for read operations.
79 * Can be changed via @see setReadDb.
85 protected $readDb = DB_SLAVE
;
92 * @param string $tableName
93 * @param string[] $fields
94 * @param array $defaults
95 * @param string|null $rowClass
96 * @param string $fieldPrefix
98 public function __construct( $tableName = '', array $fields = array(),
99 array $defaults = array(), $rowClass = null, $fieldPrefix = ''
101 $this->tableName
= $tableName;
102 $this->fields
= $fields;
103 $this->defaults
= $defaults;
105 if ( is_string( $rowClass ) ) {
106 $this->rowClass
= $rowClass;
109 $this->fieldPrefix
= $fieldPrefix;
113 * @see IORMTable::getName
118 * @throws MWException
120 public function getName() {
121 if ( $this->tableName
=== '' ) {
122 throw new MWException( 'The table name needs to be set' );
125 return $this->tableName
;
129 * Gets the db field prefix.
135 protected function getFieldPrefix() {
136 return $this->fieldPrefix
;
140 * @see IORMTable::getRowClass
146 public function getRowClass() {
147 return $this->rowClass
;
151 * @see ORMTable::getFields
156 * @throws MWException
158 public function getFields() {
159 if ( $this->fields
=== array() ) {
160 throw new MWException( 'The table needs to have one or more fields' );
163 return $this->fields
;
167 * Returns a list of default field values.
168 * field name => field value
174 public function getDefaults() {
175 return $this->defaults
;
179 * Returns a list of the summary fields.
180 * These are fields that cache computed values, such as the amount of linked objects of $type.
181 * This is relevant as one might not want to do actions such as log changes when these get updated.
187 public function getSummaryFields() {
192 * Selects the the specified fields of the records matching the provided
193 * conditions and returns them as DBDataObject. Field names get prefixed.
197 * @param array|string|null $fields
198 * @param array $conditions
199 * @param array $options
200 * @param string|null $functionName
204 public function select( $fields = null, array $conditions = array(),
205 array $options = array(), $functionName = null
207 $res = $this->rawSelect( $fields, $conditions, $options, $functionName );
209 return new ORMResult( $this, $res );
213 * Selects the the specified fields of the records matching the provided
214 * conditions and returns them as DBDataObject. Field names get prefixed.
218 * @param array|string|null $fields
219 * @param array $conditions
220 * @param array $options
221 * @param string|null $functionName
223 * @return array of row objects
224 * @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
226 public function selectObjects( $fields = null, array $conditions = array(),
227 array $options = array(), $functionName = null
229 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
233 foreach ( $result as $record ) {
234 $objects[] = $this->newRow( $record );
241 * Do the actual select.
245 * @param null|string|array $fields
246 * @param array $conditions
247 * @param array $options
248 * @param null|string $functionName
249 * @return ResultWrapper
250 * @throws DBQueryError if the query failed (even if the database was in
251 * ignoreErrors mode).
253 public function rawSelect( $fields = null, array $conditions = array(),
254 array $options = array(), $functionName = null
256 if ( is_null( $fields ) ) {
257 $fields = array_keys( $this->getFields() );
259 $fields = (array)$fields;
262 $dbr = $this->getReadDbConnection();
263 $result = $dbr->select(
265 $this->getPrefixedFields( $fields ),
266 $this->getPrefixedValues( $conditions ),
267 is_null( $functionName ) ? __METHOD__
: $functionName,
271 /* @var Exception $error */
274 if ( $result === false ) {
275 // Database connection was in "ignoreErrors" mode. We don't like that.
276 // So, we emulate the DBQueryError that should have been thrown.
277 $error = new DBQueryError(
282 is_null( $functionName ) ? __METHOD__
: $functionName
286 $this->releaseConnection( $dbr );
289 // Note: construct the error before releasing the connection,
290 // but throw it after.
298 * Selects the the specified fields of the records matching the provided
299 * conditions and returns them as associative arrays.
300 * Provided field names get prefixed.
301 * Returned field names will not have a prefix.
303 * When $collapse is true:
304 * If one field is selected, each item in the result array will be this field.
305 * If two fields are selected, each item in the result array will have as key
306 * the first field and as value the second field.
307 * If more then two fields are selected, each item will be an associative array.
311 * @param array|string|null $fields
312 * @param array $conditions
313 * @param array $options
314 * @param bool $collapse Set to false to always return each result row as associative array.
315 * @param string|null $functionName
317 * @return array of array
319 public function selectFields( $fields = null, array $conditions = array(),
320 array $options = array(), $collapse = true, $functionName = null
324 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
326 foreach ( $result as $record ) {
327 $objects[] = $this->getFieldsFromDBResult( $record );
331 if ( count( $fields ) === 1 ) {
332 $objects = array_map( 'array_shift', $objects );
333 } elseif ( count( $fields ) === 2 ) {
336 foreach ( $objects as $object ) {
337 $o[array_shift( $object )] = array_shift( $object );
348 * Selects the the specified fields of the first matching record.
349 * Field names get prefixed.
353 * @param array|string|null $fields
354 * @param array $conditions
355 * @param array $options
356 * @param string|null $functionName
358 * @return IORMRow|bool False on failure
360 public function selectRow( $fields = null, array $conditions = array(),
361 array $options = array(), $functionName = null
363 $options['LIMIT'] = 1;
365 $objects = $this->select( $fields, $conditions, $options, $functionName );
367 return ( !$objects ||
$objects->isEmpty() ) ?
false : $objects->current();
371 * Selects the the specified fields of the records matching the provided
372 * conditions. Field names do NOT get prefixed.
376 * @param array $fields
377 * @param array $conditions
378 * @param array $options
379 * @param string|null $functionName
383 public function rawSelectRow( array $fields, array $conditions = array(),
384 array $options = array(), $functionName = null
386 $dbr = $this->getReadDbConnection();
388 $result = $dbr->selectRow(
392 is_null( $functionName ) ? __METHOD__
: $functionName,
396 $this->releaseConnection( $dbr );
402 * Selects the the specified fields of the first record matching the provided
403 * conditions and returns it as an associative array, or false when nothing matches.
404 * This method makes use of selectFields and expects the same parameters and
405 * returns the same results (if there are any, if there are none, this method returns false).
406 * @see ORMTable::selectFields
410 * @param array|string|null $fields
411 * @param array $conditions
412 * @param array $options
413 * @param bool $collapse Set to false to always return each result row as associative array.
414 * @param string|null $functionName
416 * @return mixed|array|bool False on failure
418 public function selectFieldsRow( $fields = null, array $conditions = array(),
419 array $options = array(), $collapse = true, $functionName = null
421 $options['LIMIT'] = 1;
423 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
425 return empty( $objects ) ?
false : $objects[0];
429 * Returns if there is at least one record matching the provided conditions.
430 * Condition field names get prefixed.
434 * @param array $conditions
438 public function has( array $conditions = array() ) {
439 return $this->selectRow( array( 'id' ), $conditions ) !== false;
443 * Checks if the table exists
449 public function exists() {
450 $dbr = $this->getReadDbConnection();
451 $exists = $dbr->tableExists( $this->getName() );
452 $this->releaseConnection( $dbr );
458 * Returns the amount of matching records.
459 * Condition field names get prefixed.
461 * Note that this can be expensive on large tables.
462 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
466 * @param array $conditions
467 * @param array $options
471 public function count( array $conditions = array(), array $options = array() ) {
472 $res = $this->rawSelectRow(
473 array( 'rowcount' => 'COUNT(*)' ),
474 $this->getPrefixedValues( $conditions ),
479 return $res->rowcount
;
483 * Removes the object from the database.
487 * @param array $conditions
488 * @param string|null $functionName
490 * @return bool Success indicator
492 public function delete( array $conditions, $functionName = null ) {
493 $dbw = $this->getWriteDbConnection();
495 $result = $dbw->delete(
497 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
498 is_null( $functionName ) ? __METHOD__
: $functionName
499 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
501 $this->releaseConnection( $dbw );
507 * Get API parameters for the fields supported by this object.
511 * @param bool $requireParams
512 * @param bool $setDefaults
516 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
528 $defaults = $this->getDefaults();
530 foreach ( $this->getFields() as $field => $type ) {
531 if ( $field == 'id' ) {
535 $hasDefault = array_key_exists( $field, $defaults );
537 $params[$field] = array(
538 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
539 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
542 if ( $type == 'array' ) {
543 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
546 if ( $setDefaults && $hasDefault ) {
547 $default = is_array( $defaults[$field] )
548 ?
implode( '|', $defaults[$field] )
550 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
558 * Returns an array with the fields and their descriptions.
560 * field name => field description
566 public function getFieldDescriptions() {
571 * Get the database ID used for read operations.
575 * @return int DB_ enum
577 public function getReadDb() {
578 return $this->readDb
;
582 * Set the database ID to use for read operations, use DB_XXX constants or
583 * an index to the load balancer setup.
589 public function setReadDb( $db ) {
594 * Get the ID of the any foreign wiki to use as a target for database operations
598 * @return string|bool The target wiki, in a form that LBFactory understands
599 * (or false if the local wiki is used)
601 public function getTargetWiki() {
606 * Set the ID of the any foreign wiki to use as a target for database operations
608 * @param string|bool $wiki The target wiki, in a form that LBFactory
609 * understands (or false if the local wiki shall be used)
613 public function setTargetWiki( $wiki ) {
618 * Get the database type used for read operations.
619 * This is to be used instead of wfGetDB.
621 * @see LoadBalancer::getConnection
625 * @return DatabaseBase The database object
627 public function getReadDbConnection() {
628 return $this->getConnection( $this->getReadDb(), array() );
632 * Get the database type used for read operations.
633 * This is to be used instead of wfGetDB.
635 * @see LoadBalancer::getConnection
639 * @return DatabaseBase The database object
641 public function getWriteDbConnection() {
642 return $this->getConnection( DB_MASTER
, array() );
646 * Releases the lease on the given database connection. This is useful mainly
647 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
649 * @see LoadBalancer::reuseConnection
651 * @param DatabaseBase $db the database
655 // @codingStandardsIgnoreStart Suppress "useless method overriding" sniffer warning
656 public function releaseConnection( DatabaseBase
$db ) {
657 parent
::releaseConnection( $db ); // just make it public
659 // @codingStandardsIgnoreEnd
662 * Update the records matching the provided conditions by
663 * setting the fields that are keys in the $values param to
664 * their corresponding values.
668 * @param array $values
669 * @param array $conditions
671 * @return bool Success indicator
673 public function update( array $values, array $conditions = array() ) {
674 $dbw = $this->getWriteDbConnection();
676 $result = $dbw->update(
678 $this->getPrefixedValues( $values ),
679 $this->getPrefixedValues( $conditions ),
681 ) !== false; // DatabaseBase::update does not always return true for success as documented...
683 $this->releaseConnection( $dbw );
689 * Computes the values of the summary fields of the objects matching the provided conditions.
693 * @param array|string|null $summaryFields
694 * @param array $conditions
696 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
697 $slave = $this->getReadDb();
698 $this->setReadDb( DB_MASTER
);
703 foreach ( $this->select( null, $conditions ) as $item ) {
704 $item->loadSummaryFields( $summaryFields );
705 $item->setSummaryMode( true );
709 $this->setReadDb( $slave );
713 * Takes in an associative array with field names as keys and
714 * their values as value. The field names are prefixed with the
719 * @param array $values
723 public function getPrefixedValues( array $values ) {
724 $prefixedValues = array();
726 foreach ( $values as $field => $value ) {
727 if ( is_integer( $field ) ) {
728 if ( is_array( $value ) ) {
732 $value = explode( ' ', $value, 2 );
733 $value[0] = $this->getPrefixedField( $value[0] );
734 $prefixedValues[] = implode( ' ', $value );
739 $prefixedValues[$this->getPrefixedField( $field )] = $value;
742 return $prefixedValues;
746 * Takes in a field or array of fields and returns an
747 * array with their prefixed versions, ready for db usage.
751 * @param array|string $fields
755 public function getPrefixedFields( array $fields ) {
756 foreach ( $fields as &$field ) {
757 $field = $this->getPrefixedField( $field );
764 * Takes in a field and returns an it's prefixed version, ready for db usage.
768 * @param string|array $field
772 public function getPrefixedField( $field ) {
773 return $this->getFieldPrefix() . $field;
777 * Takes an array of field names with prefix and returns the unprefixed equivalent.
781 * @param array $fieldNames
785 public function unprefixFieldNames( array $fieldNames ) {
786 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
790 * Takes a field name with prefix and returns the unprefixed equivalent.
794 * @param string $fieldName
798 public function unprefixFieldName( $fieldName ) {
799 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
803 * Get an instance of this class.
806 * @deprecated since 1.21
810 public static function singleton() {
811 $class = get_called_class();
813 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
814 self
::$instanceCache[$class] = new $class;
817 return self
::$instanceCache[$class];
821 * Get an array with fields from a database result,
822 * that can be fed directly to the constructor or
827 * @param stdClass $result
828 * @throws MWException
831 public function getFieldsFromDBResult( stdClass
$result ) {
832 $result = (array)$result;
834 $rawFields = array_combine(
835 $this->unprefixFieldNames( array_keys( $result ) ),
836 array_values( $result )
839 $fieldDefinitions = $this->getFields();
842 foreach ( $rawFields as $name => $value ) {
843 if ( array_key_exists( $name, $fieldDefinitions ) ) {
844 switch ( $fieldDefinitions[$name] ) {
846 $value = (int)$value;
849 $value = (float)$value;
852 if ( is_string( $value ) ) {
853 $value = $value !== '0';
854 } elseif ( is_int( $value ) ) {
855 $value = $value !== 0;
859 if ( is_string( $value ) ) {
860 $value = unserialize( $value );
863 if ( !is_array( $value ) ) {
868 if ( is_string( $value ) ) {
869 $value = unserialize( $value );
873 if ( is_string( $value ) ) {
874 $value = (int)$value;
879 $fields[$name] = $value;
881 throw new MWException( 'Attempted to set unknown field ' . $name );
889 * @see ORMTable::newRowFromFromDBResult
891 * @deprecated since 1.20 use newRowFromDBResult instead
894 * @param stdClass $result
898 public function newFromDBResult( stdClass
$result ) {
899 return self
::newRowFromDBResult( $result );
903 * Get a new instance of the class from a database result.
907 * @param stdClass $result
911 public function newRowFromDBResult( stdClass
$result ) {
912 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
916 * @see ORMTable::newRow
918 * @deprecated since 1.20 use newRow instead
922 * @param bool $loadDefaults
926 public function newFromArray( array $data, $loadDefaults = false ) {
927 return static::newRow( $data, $loadDefaults );
931 * Get a new instance of the class from an array.
935 * @param array $fields
936 * @param bool $loadDefaults
940 public function newRow( array $fields, $loadDefaults = false ) {
941 $class = $this->getRowClass();
943 return new $class( $this, $fields, $loadDefaults );
947 * Return the names of the fields.
953 public function getFieldNames() {
954 return array_keys( $this->getFields() );
958 * Gets if the object can take a certain field.
962 * @param string $name
966 public function canHaveField( $name ) {
967 return array_key_exists( $name, $this->getFields() );
971 * Updates the provided row in the database.
975 * @param IORMRow $row The row to save
976 * @param string|null $functionName
978 * @return bool Success indicator
980 public function updateRow( IORMRow
$row, $functionName = null ) {
981 $dbw = $this->getWriteDbConnection();
983 $success = $dbw->update(
985 $this->getWriteValues( $row ),
986 $this->getPrefixedValues( array( 'id' => $row->getId() ) ),
987 is_null( $functionName ) ? __METHOD__
: $functionName
990 $this->releaseConnection( $dbw );
992 // DatabaseBase::update does not always return true for success as documented...
993 return $success !== false;
997 * Inserts the provided row into the database.
1001 * @param IORMRow $row
1002 * @param string|null $functionName
1003 * @param array|null $options
1005 * @return bool Success indicator
1007 public function insertRow( IORMRow
$row, $functionName = null, array $options = null ) {
1008 $dbw = $this->getWriteDbConnection();
1010 $success = $dbw->insert(
1012 $this->getWriteValues( $row ),
1013 is_null( $functionName ) ? __METHOD__
: $functionName,
1017 // DatabaseBase::insert does not always return true for success as documented...
1018 $success = $success !== false;
1021 $row->setField( 'id', $dbw->insertId() );
1024 $this->releaseConnection( $dbw );
1030 * Gets the fields => values to write to the table.
1034 * @param IORMRow $row
1038 protected function getWriteValues( IORMRow
$row ) {
1041 $rowFields = $row->getFields();
1043 foreach ( $this->getFields() as $name => $type ) {
1044 if ( array_key_exists( $name, $rowFields ) ) {
1045 $value = $rowFields[$name];
1049 $value = (array)$value;
1052 $value = serialize( $value );
1056 $values[$this->getPrefixedField( $name )] = $value;
1064 * Removes the provided row from the database.
1068 * @param IORMRow $row
1069 * @param string|null $functionName
1071 * @return bool Success indicator
1073 public function removeRow( IORMRow
$row, $functionName = null ) {
1074 $success = $this->delete(
1075 array( 'id' => $row->getId() ),
1076 is_null( $functionName ) ? __METHOD__
: $functionName
1079 // DatabaseBase::delete does not always return true for success as documented...
1080 return $success !== false;
1084 * Add an amount (can be negative) to the specified field (needs to be numeric).
1088 * @param array $conditions
1089 * @param string $field
1090 * @param int $amount
1092 * @return bool Success indicator
1093 * @throws MWException
1095 public function addToField( array $conditions, $field, $amount ) {
1096 if ( !array_key_exists( $field, $this->fields
) ) {
1097 throw new MWException( 'Unknown field "' . $field . '" provided' );
1100 if ( $amount == 0 ) {
1104 $absoluteAmount = abs( $amount );
1105 $isNegative = $amount < 0;
1107 $fullField = $this->getPrefixedField( $field );
1109 $dbw = $this->getWriteDbConnection();
1111 $success = $dbw->update(
1113 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
1114 $this->getPrefixedValues( $conditions ),
1116 ) !== false; // DatabaseBase::update does not always return true for success as documented...
1118 $this->releaseConnection( $dbw );