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
{
34 * Cache for instances, used by the singleton method.
37 * @deprecated since 1.21
41 protected static $instanceCache = array();
55 protected $fields = array();
62 protected $fieldPrefix = '';
69 protected $rowClass = 'ORMRow';
76 protected $defaults = array();
79 * ID of the database connection to use for read operations.
80 * Can be changed via @see setReadDb.
84 * @var integer DB_ enum
86 protected $readDb = DB_SLAVE
;
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
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.
134 protected function getFieldPrefix() {
135 return $this->fieldPrefix
;
139 * @see IORMTable::getRowClass
145 public function getRowClass() {
146 return $this->rowClass
;
150 * @see ORMTable::getFields
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
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.
186 public function getSummaryFields() {
191 * Selects the the specified fields of the records matching the provided
192 * conditions and returns them as DBDataObject. Field names get prefixed.
196 * @param array|string|null $fields
197 * @param array $conditions
198 * @param array $options
199 * @param string|null $functionName
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.
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 );
229 foreach ( $result as $record ) {
230 $objects[] = $this->newRow( $record );
237 * Do the actual select.
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() );
255 $fields = (array)$fields;
258 $dbr = $this->getReadDbConnection();
259 $result = $dbr->select(
261 $this->getPrefixedFields( $fields ),
262 $this->getPrefixedValues( $conditions ),
263 is_null( $functionName ) ? __METHOD__
: $functionName,
267 /* @var Exception $error */
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(
278 is_null( $functionName ) ? __METHOD__
: $functionName
282 $this->releaseConnection( $dbr );
285 // Note: construct the error before releasing the connection,
286 // but throw it after.
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.
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 ) {
319 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
321 foreach ( $result as $record ) {
322 $objects[] = $this->getFieldsFromDBResult( $record );
326 if ( count( $fields ) === 1 ) {
327 $objects = array_map( 'array_shift', $objects );
329 elseif ( count( $fields ) === 2 ) {
332 foreach ( $objects as $object ) {
333 $o[array_shift( $object )] = array_shift( $object );
344 * Selects the the specified fields of the first matching record.
345 * Field names get prefixed.
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.
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(
386 is_null( $functionName ) ? __METHOD__
: $functionName,
390 $this->releaseConnection( $dbr );
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
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.
426 * @param array $conditions
430 public function has( array $conditions = array() ) {
431 return $this->selectRow( array( 'id' ), $conditions ) !== false;
435 * Checks if the table exists
441 public function exists() {
442 $dbr = $this->getReadDbConnection();
443 $exists = $dbr->tableExists( $this->getName() );
444 $this->releaseConnection( $dbr );
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.
458 * @param array $conditions
459 * @param array $options
463 public function count( array $conditions = array(), array $options = array() ) {
464 $res = $this->rawSelectRow(
465 array( 'rowcount' => 'COUNT(*)' ),
466 $this->getPrefixedValues( $conditions ),
471 return $res->rowcount
;
475 * Removes the object from the database.
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(
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 );
498 * Get API parameters for the fields supported by this object.
502 * @param boolean $requireParams
503 * @param boolean $setDefaults
507 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
519 $defaults = $this->getDefaults();
521 foreach ( $this->getFields() as $field => $type ) {
522 if ( $field == 'id' ) {
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;
547 * Returns an array with the fields and their descriptions.
549 * field name => field description
555 public function getFieldDescriptions() {
560 * Get the database ID used for read operations.
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.
577 public function setReadDb( $db ) {
582 * Get the ID of the any foreign wiki to use as a target for database operations
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() {
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)
599 public function setTargetWiki( $wiki ) {
604 * Get the database type used for read operations.
605 * This is to be used instead of wfGetDB.
607 * @see LoadBalancer::getConnection
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
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
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.
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(
662 $this->getPrefixedValues( $values ),
663 $this->getPrefixedValues( $conditions ),
665 ) !== false; // DatabaseBase::update does not always return true for success as documented...
667 $this->releaseConnection( $dbw );
672 * Computes the values of the summary fields of the objects matching the provided conditions.
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
);
686 foreach ( $this->select( null, $conditions ) as $item ) {
687 $item->loadSummaryFields( $summaryFields );
688 $item->setSummaryMode( true );
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
702 * @param array $values
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 ) ) {
716 $value = explode( ' ', $value, 2 );
717 $value[0] = $this->getPrefixedField( $value[0] );
718 $prefixedValues[] = implode( ' ', $value );
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.
735 * @param array|string $fields
739 public function getPrefixedFields( array $fields ) {
740 foreach ( $fields as &$field ) {
741 $field = $this->getPrefixedField( $field );
748 * Takes in a field and returns an it's prefixed version, ready for db usage.
752 * @param string|array $field
756 public function getPrefixedField( $field ) {
757 return $this->getFieldPrefix() . $field;
761 * Takes an array of field names with prefix and returns the unprefixed equivalent.
765 * @param array $fieldNames
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.
778 * @param string $fieldName
782 public function unprefixFieldName( $fieldName ) {
783 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
787 * Get an instance of this class.
790 * @deprecated since 1.21
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
811 * @param stdClass $result
815 public function getFieldsFromDBResult( stdClass
$result ) {
816 $result = (array)$result;
818 $rawFields = array_combine(
819 $this->unprefixFieldNames( array_keys( $result ) ),
820 array_values( $result )
823 $fieldDefinitions = $this->getFields();
826 foreach ( $rawFields as $name => $value ) {
827 if ( array_key_exists( $name, $fieldDefinitions ) ) {
828 switch ( $fieldDefinitions[$name] ) {
830 $value = (int)$value;
833 $value = (float)$value;
836 if ( is_string( $value ) ) {
837 $value = $value !== '0';
838 } elseif ( is_int( $value ) ) {
839 $value = $value !== 0;
843 if ( is_string( $value ) ) {
844 $value = unserialize( $value );
847 if ( !is_array( $value ) ) {
852 if ( is_string( $value ) ) {
853 $value = unserialize( $value );
857 if ( is_string( $value ) ) {
858 $value = (int)$value;
863 $fields[$name] = $value;
865 throw new MWException( 'Attempted to set unknown field ' . $name );
873 * @see ORMTable::newRowFromFromDBResult
875 * @deprecated use newRowFromDBResult instead
878 * @param stdClass $result
882 public function newFromDBResult( stdClass
$result ) {
883 return self
::newRowFromDBResult( $result );
887 * Get a new instance of the class from a database result.
891 * @param stdClass $result
895 public function newRowFromDBResult( stdClass
$result ) {
896 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
900 * @see ORMTable::newRow
902 * @deprecated use newRow instead
906 * @param boolean $loadDefaults
910 public function newFromArray( array $data, $loadDefaults = false ) {
911 return static::newRow( $data, $loadDefaults );
915 * Get a new instance of the class from an array.
919 * @param array $fields
920 * @param boolean $loadDefaults
924 public function newRow( array $fields, $loadDefaults = false ) {
925 $class = $this->getRowClass();
927 return new $class( $this, $fields, $loadDefaults );
931 * Return the names of the fields.
937 public function getFieldNames() {
938 return array_keys( $this->getFields() );
942 * Gets if the object can take a certain field.
946 * @param string $name
950 public function canHaveField( $name ) {
951 return array_key_exists( $name, $this->getFields() );
955 * Updated the provided row in the database.
959 * @param IORMRow $row The row to save
960 * @param string|null $functionName
962 * @return boolean Success indicator
964 public function updateRow( IORMRow
$row, $functionName = null ) {
965 $dbw = $this->getWriteDbConnection();
967 $success = $dbw->update(
969 $this->getWriteValues( $row ),
970 $this->getPrefixedValues( array( 'id' => $row->getId() ) ),
971 is_null( $functionName ) ? __METHOD__
: $functionName
974 $this->releaseConnection( $dbw );
976 // DatabaseBase::update does not always return true for success as documented...
977 return $success !== false;
981 * Inserts the provided row into the database.
985 * @param IORMRow $row
986 * @param string|null $functionName
987 * @param array|null $options
989 * @return boolean Success indicator
991 public function insertRow( IORMRow
$row, $functionName = null, array $options = null ) {
992 $dbw = $this->getWriteDbConnection();
994 $success = $dbw->insert(
996 $this->getWriteValues( $row ),
997 is_null( $functionName ) ? __METHOD__
: $functionName,
1001 // DatabaseBase::insert does not always return true for success as documented...
1002 $success = $success !== false;
1005 $row->setField( 'id', $dbw->insertId() );
1008 $this->releaseConnection( $dbw );
1014 * Gets the fields => values to write to the table.
1018 * @param IORMRow $row
1022 protected function getWriteValues( IORMRow
$row ) {
1025 $rowFields = $row->getFields();
1027 foreach ( $this->getFields() as $name => $type ) {
1028 if ( array_key_exists( $name, $rowFields ) ) {
1029 $value = $rowFields[$name];
1033 $value = (array)$value;
1036 $value = serialize( $value );
1040 $values[$this->getPrefixedField( $name )] = $value;
1048 * Removes the provided row from the database.
1052 * @param IORMRow $row
1053 * @param string|null $functionName
1055 * @return boolean Success indicator
1057 public function removeRow( IORMRow
$row, $functionName = null ) {
1058 $success = $this->delete(
1059 array( 'id' => $row->getId() ),
1060 is_null( $functionName ) ? __METHOD__
: $functionName
1063 // DatabaseBase::delete does not always return true for success as documented...
1064 return $success !== false;
1068 * Add an amount (can be negative) to the specified field (needs to be numeric).
1072 * @param array $conditions
1073 * @param string $field
1074 * @param integer $amount
1076 * @return boolean Success indicator
1077 * @throws MWException
1079 public function addToField( array $conditions, $field, $amount ) {
1080 if ( !array_key_exists( $field, $this->fields
) ) {
1081 throw new MWException( 'Unknown field "' . $field . '" provided' );
1084 if ( $amount == 0 ) {
1088 $absoluteAmount = abs( $amount );
1089 $isNegative = $amount < 0;
1091 $fullField = $this->getPrefixedField( $field );
1093 $dbw = $this->getWriteDbConnection();
1095 $success = $dbw->update(
1097 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
1098 $this->getPrefixedValues( $conditions ),
1100 ) !== false; // DatabaseBase::update does not always return true for success as documented...
1102 $this->releaseConnection( $dbw );