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.
83 * @var integer DB_ enum
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(), array $defaults = array(), $rowClass = null, $fieldPrefix = '' ) {
99 $this->tableName
= $tableName;
100 $this->fields
= $fields;
101 $this->defaults
= $defaults;
103 if ( is_string( $rowClass ) ) {
104 $this->rowClass
= $rowClass;
107 $this->fieldPrefix
= $fieldPrefix;
111 * @see IORMTable::getName
116 * @throws MWException
118 public function getName() {
119 if ( $this->tableName
=== '' ) {
120 throw new MWException( 'The table name needs to be set' );
123 return $this->tableName
;
127 * Gets the db field prefix.
133 protected function getFieldPrefix() {
134 return $this->fieldPrefix
;
138 * @see IORMTable::getRowClass
144 public function getRowClass() {
145 return $this->rowClass
;
149 * @see ORMTable::getFields
154 * @throws MWException
156 public function getFields() {
157 if ( $this->fields
=== array() ) {
158 throw new MWException( 'The table needs to have one or more fields' );
161 return $this->fields
;
165 * Returns a list of default field values.
166 * field name => field value
172 public function getDefaults() {
173 return $this->defaults
;
177 * Returns a list of the summary fields.
178 * These are fields that cache computed values, such as the amount of linked objects of $type.
179 * This is relevant as one might not want to do actions such as log changes when these get updated.
185 public function getSummaryFields() {
190 * Selects the the specified fields of the records matching the provided
191 * conditions and returns them as DBDataObject. Field names get prefixed.
195 * @param array|string|null $fields
196 * @param array $conditions
197 * @param array $options
198 * @param string|null $functionName
202 public function select( $fields = null, array $conditions = array(),
203 array $options = array(), $functionName = null
205 $res = $this->rawSelect( $fields, $conditions, $options, $functionName );
207 return new ORMResult( $this, $res );
211 * Selects the the specified fields of the records matching the provided
212 * conditions and returns them as DBDataObject. Field names get prefixed.
216 * @param array|string|null $fields
217 * @param array $conditions
218 * @param array $options
219 * @param string|null $functionName
221 * @return array of row objects
222 * @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
224 public function selectObjects( $fields = null, array $conditions = array(),
225 array $options = array(), $functionName = null
227 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
231 foreach ( $result as $record ) {
232 $objects[] = $this->newRow( $record );
239 * Do the actual select.
243 * @param null|string|array $fields
244 * @param array $conditions
245 * @param array $options
246 * @param null|string $functionName
248 * @return ResultWrapper
249 * @throws DBQueryError if the quey failed (even if the database was in ignoreErrors mode).
251 public function rawSelect( $fields = null, array $conditions = array(),
252 array $options = array(), $functionName = null
254 if ( is_null( $fields ) ) {
255 $fields = array_keys( $this->getFields() );
257 $fields = (array)$fields;
260 $dbr = $this->getReadDbConnection();
261 $result = $dbr->select(
263 $this->getPrefixedFields( $fields ),
264 $this->getPrefixedValues( $conditions ),
265 is_null( $functionName ) ? __METHOD__
: $functionName,
269 /* @var Exception $error */
272 if ( $result === false ) {
273 // Database connection was in "ignoreErrors" mode. We don't like that.
274 // So, we emulate the DBQueryError that should have been thrown.
275 $error = new DBQueryError(
280 is_null( $functionName ) ? __METHOD__
: $functionName
284 $this->releaseConnection( $dbr );
287 // Note: construct the error before releasing the connection,
288 // but throw it after.
296 * Selects the the specified fields of the records matching the provided
297 * conditions and returns them as associative arrays.
298 * Provided field names get prefixed.
299 * Returned field names will not have a prefix.
301 * When $collapse is true:
302 * If one field is selected, each item in the result array will be this field.
303 * If two fields are selected, each item in the result array will have as key
304 * the first field and as value the second field.
305 * If more then two fields are selected, each item will be an associative array.
309 * @param array|string|null $fields
310 * @param array $conditions
311 * @param array $options
312 * @param boolean $collapse Set to false to always return each result row as associative array.
313 * @param string|null $functionName
315 * @return array of array
317 public function selectFields( $fields = null, array $conditions = array(),
318 array $options = array(), $collapse = true, $functionName = null
322 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
324 foreach ( $result as $record ) {
325 $objects[] = $this->getFieldsFromDBResult( $record );
329 if ( count( $fields ) === 1 ) {
330 $objects = array_map( 'array_shift', $objects );
331 } elseif ( count( $fields ) === 2 ) {
334 foreach ( $objects as $object ) {
335 $o[array_shift( $object )] = array_shift( $object );
346 * Selects the the specified fields of the first matching record.
347 * Field names get prefixed.
351 * @param array|string|null $fields
352 * @param array $conditions
353 * @param array $options
354 * @param string|null $functionName
356 * @return IORMRow|bool False on failure
358 public function selectRow( $fields = null, array $conditions = array(),
359 array $options = array(), $functionName = null
361 $options['LIMIT'] = 1;
363 $objects = $this->select( $fields, $conditions, $options, $functionName );
365 return ( !$objects ||
$objects->isEmpty() ) ?
false : $objects->current();
369 * Selects the the specified fields of the records matching the provided
370 * conditions. Field names do NOT get prefixed.
374 * @param array $fields
375 * @param array $conditions
376 * @param array $options
377 * @param string|null $functionName
379 * @return ResultWrapper
381 public function rawSelectRow( array $fields, array $conditions = array(),
382 array $options = array(), $functionName = null
384 $dbr = $this->getReadDbConnection();
386 $result = $dbr->selectRow(
390 is_null( $functionName ) ? __METHOD__
: $functionName,
394 $this->releaseConnection( $dbr );
400 * Selects the the specified fields of the first record matching the provided
401 * conditions and returns it as an associative array, or false when nothing matches.
402 * This method makes use of selectFields and expects the same parameters and
403 * returns the same results (if there are any, if there are none, this method returns false).
404 * @see ORMTable::selectFields
408 * @param array|string|null $fields
409 * @param array $conditions
410 * @param array $options
411 * @param boolean $collapse Set to false to always return each result row as associative array.
412 * @param string|null $functionName
414 * @return mixed|array|bool False on failure
416 public function selectFieldsRow( $fields = null, array $conditions = array(),
417 array $options = array(), $collapse = true, $functionName = null
419 $options['LIMIT'] = 1;
421 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
423 return empty( $objects ) ?
false : $objects[0];
427 * Returns if there is at least one record matching the provided conditions.
428 * Condition field names get prefixed.
432 * @param array $conditions
436 public function has( array $conditions = array() ) {
437 return $this->selectRow( array( 'id' ), $conditions ) !== false;
441 * Checks if the table exists
447 public function exists() {
448 $dbr = $this->getReadDbConnection();
449 $exists = $dbr->tableExists( $this->getName() );
450 $this->releaseConnection( $dbr );
456 * Returns the amount of matching records.
457 * Condition field names get prefixed.
459 * Note that this can be expensive on large tables.
460 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
464 * @param array $conditions
465 * @param array $options
469 public function count( array $conditions = array(), array $options = array() ) {
470 $res = $this->rawSelectRow(
471 array( 'rowcount' => 'COUNT(*)' ),
472 $this->getPrefixedValues( $conditions ),
477 return $res->rowcount
;
481 * Removes the object from the database.
485 * @param array $conditions
486 * @param string|null $functionName
488 * @return boolean Success indicator
490 public function delete( array $conditions, $functionName = null ) {
491 $dbw = $this->getWriteDbConnection();
493 $result = $dbw->delete(
495 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
496 is_null( $functionName ) ? __METHOD__
: $functionName
497 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
499 $this->releaseConnection( $dbw );
505 * Get API parameters for the fields supported by this object.
509 * @param boolean $requireParams
510 * @param boolean $setDefaults
514 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
526 $defaults = $this->getDefaults();
528 foreach ( $this->getFields() as $field => $type ) {
529 if ( $field == 'id' ) {
533 $hasDefault = array_key_exists( $field, $defaults );
535 $params[$field] = array(
536 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
537 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
540 if ( $type == 'array' ) {
541 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
544 if ( $setDefaults && $hasDefault ) {
545 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
546 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
554 * Returns an array with the fields and their descriptions.
556 * field name => field description
562 public function getFieldDescriptions() {
567 * Get the database ID used for read operations.
571 * @return integer DB_ enum
573 public function getReadDb() {
574 return $this->readDb
;
578 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
584 public function setReadDb( $db ) {
589 * Get the ID of the any foreign wiki to use as a target for database operations
593 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
595 public function getTargetWiki() {
600 * Set the ID of the any foreign wiki to use as a target for database operations
602 * @param string|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
606 public function setTargetWiki( $wiki ) {
611 * Get the database type used for read operations.
612 * This is to be used instead of wfGetDB.
614 * @see LoadBalancer::getConnection
618 * @return DatabaseBase The database object
620 public function getReadDbConnection() {
621 return $this->getConnection( $this->getReadDb(), array() );
625 * Get the database type used for read operations.
626 * This is to be used instead of wfGetDB.
628 * @see LoadBalancer::getConnection
632 * @return DatabaseBase The database object
634 public function getWriteDbConnection() {
635 return $this->getConnection( DB_MASTER
, array() );
639 * Releases the lease on the given database connection. This is useful mainly
640 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
642 * @see LoadBalancer::reuseConnection
644 * @param DatabaseBase $db the database
648 public function releaseConnection( DatabaseBase
$db ) {
649 parent
::releaseConnection( $db ); // just make it public
653 * Update the records matching the provided conditions by
654 * setting the fields that are keys in the $values param to
655 * their corresponding values.
659 * @param array $values
660 * @param array $conditions
662 * @return boolean Success indicator
664 public function update( array $values, array $conditions = array() ) {
665 $dbw = $this->getWriteDbConnection();
667 $result = $dbw->update(
669 $this->getPrefixedValues( $values ),
670 $this->getPrefixedValues( $conditions ),
672 ) !== false; // DatabaseBase::update does not always return true for success as documented...
674 $this->releaseConnection( $dbw );
680 * Computes the values of the summary fields of the objects matching the provided conditions.
684 * @param array|string|null $summaryFields
685 * @param array $conditions
687 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
688 $slave = $this->getReadDb();
689 $this->setReadDb( DB_MASTER
);
694 foreach ( $this->select( null, $conditions ) as $item ) {
695 $item->loadSummaryFields( $summaryFields );
696 $item->setSummaryMode( true );
700 $this->setReadDb( $slave );
704 * Takes in an associative array with field names as keys and
705 * their values as value. The field names are prefixed with the
710 * @param array $values
714 public function getPrefixedValues( array $values ) {
715 $prefixedValues = array();
717 foreach ( $values as $field => $value ) {
718 if ( is_integer( $field ) ) {
719 if ( is_array( $value ) ) {
723 $value = explode( ' ', $value, 2 );
724 $value[0] = $this->getPrefixedField( $value[0] );
725 $prefixedValues[] = implode( ' ', $value );
730 $prefixedValues[$this->getPrefixedField( $field )] = $value;
733 return $prefixedValues;
737 * Takes in a field or array of fields and returns an
738 * array with their prefixed versions, ready for db usage.
742 * @param array|string $fields
746 public function getPrefixedFields( array $fields ) {
747 foreach ( $fields as &$field ) {
748 $field = $this->getPrefixedField( $field );
755 * Takes in a field and returns an it's prefixed version, ready for db usage.
759 * @param string|array $field
763 public function getPrefixedField( $field ) {
764 return $this->getFieldPrefix() . $field;
768 * Takes an array of field names with prefix and returns the unprefixed equivalent.
772 * @param array $fieldNames
776 public function unprefixFieldNames( array $fieldNames ) {
777 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
781 * Takes a field name with prefix and returns the unprefixed equivalent.
785 * @param string $fieldName
789 public function unprefixFieldName( $fieldName ) {
790 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
794 * Get an instance of this class.
797 * @deprecated since 1.21
801 public static function singleton() {
802 $class = get_called_class();
804 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
805 self
::$instanceCache[$class] = new $class;
808 return self
::$instanceCache[$class];
812 * Get an array with fields from a database result,
813 * that can be fed directly to the constructor or
818 * @param stdClass $result
822 public function getFieldsFromDBResult( stdClass
$result ) {
823 $result = (array)$result;
825 $rawFields = array_combine(
826 $this->unprefixFieldNames( array_keys( $result ) ),
827 array_values( $result )
830 $fieldDefinitions = $this->getFields();
833 foreach ( $rawFields as $name => $value ) {
834 if ( array_key_exists( $name, $fieldDefinitions ) ) {
835 switch ( $fieldDefinitions[$name] ) {
837 $value = (int)$value;
840 $value = (float)$value;
843 if ( is_string( $value ) ) {
844 $value = $value !== '0';
845 } elseif ( is_int( $value ) ) {
846 $value = $value !== 0;
850 if ( is_string( $value ) ) {
851 $value = unserialize( $value );
854 if ( !is_array( $value ) ) {
859 if ( is_string( $value ) ) {
860 $value = unserialize( $value );
864 if ( is_string( $value ) ) {
865 $value = (int)$value;
870 $fields[$name] = $value;
872 throw new MWException( 'Attempted to set unknown field ' . $name );
880 * @see ORMTable::newRowFromFromDBResult
882 * @deprecated use newRowFromDBResult instead
885 * @param stdClass $result
889 public function newFromDBResult( stdClass
$result ) {
890 return self
::newRowFromDBResult( $result );
894 * Get a new instance of the class from a database result.
898 * @param stdClass $result
902 public function newRowFromDBResult( stdClass
$result ) {
903 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
907 * @see ORMTable::newRow
909 * @deprecated use newRow instead
913 * @param boolean $loadDefaults
917 public function newFromArray( array $data, $loadDefaults = false ) {
918 return static::newRow( $data, $loadDefaults );
922 * Get a new instance of the class from an array.
926 * @param array $fields
927 * @param boolean $loadDefaults
931 public function newRow( array $fields, $loadDefaults = false ) {
932 $class = $this->getRowClass();
934 return new $class( $this, $fields, $loadDefaults );
938 * Return the names of the fields.
944 public function getFieldNames() {
945 return array_keys( $this->getFields() );
949 * Gets if the object can take a certain field.
953 * @param string $name
957 public function canHaveField( $name ) {
958 return array_key_exists( $name, $this->getFields() );
962 * Updates the provided row in the database.
966 * @param IORMRow $row The row to save
967 * @param string|null $functionName
969 * @return boolean Success indicator
971 public function updateRow( IORMRow
$row, $functionName = null ) {
972 $dbw = $this->getWriteDbConnection();
974 $success = $dbw->update(
976 $this->getWriteValues( $row ),
977 $this->getPrefixedValues( array( 'id' => $row->getId() ) ),
978 is_null( $functionName ) ? __METHOD__
: $functionName
981 $this->releaseConnection( $dbw );
983 // DatabaseBase::update does not always return true for success as documented...
984 return $success !== false;
988 * Inserts the provided row into the database.
992 * @param IORMRow $row
993 * @param string|null $functionName
994 * @param array|null $options
996 * @return boolean Success indicator
998 public function insertRow( IORMRow
$row, $functionName = null, array $options = null ) {
999 $dbw = $this->getWriteDbConnection();
1001 $success = $dbw->insert(
1003 $this->getWriteValues( $row ),
1004 is_null( $functionName ) ? __METHOD__
: $functionName,
1008 // DatabaseBase::insert does not always return true for success as documented...
1009 $success = $success !== false;
1012 $row->setField( 'id', $dbw->insertId() );
1015 $this->releaseConnection( $dbw );
1021 * Gets the fields => values to write to the table.
1025 * @param IORMRow $row
1029 protected function getWriteValues( IORMRow
$row ) {
1032 $rowFields = $row->getFields();
1034 foreach ( $this->getFields() as $name => $type ) {
1035 if ( array_key_exists( $name, $rowFields ) ) {
1036 $value = $rowFields[$name];
1040 $value = (array)$value;
1043 $value = serialize( $value );
1047 $values[$this->getPrefixedField( $name )] = $value;
1055 * Removes the provided row from the database.
1059 * @param IORMRow $row
1060 * @param string|null $functionName
1062 * @return boolean Success indicator
1064 public function removeRow( IORMRow
$row, $functionName = null ) {
1065 $success = $this->delete(
1066 array( 'id' => $row->getId() ),
1067 is_null( $functionName ) ? __METHOD__
: $functionName
1070 // DatabaseBase::delete does not always return true for success as documented...
1071 return $success !== false;
1075 * Add an amount (can be negative) to the specified field (needs to be numeric).
1079 * @param array $conditions
1080 * @param string $field
1081 * @param integer $amount
1083 * @return boolean Success indicator
1084 * @throws MWException
1086 public function addToField( array $conditions, $field, $amount ) {
1087 if ( !array_key_exists( $field, $this->fields
) ) {
1088 throw new MWException( 'Unknown field "' . $field . '" provided' );
1091 if ( $amount == 0 ) {
1095 $absoluteAmount = abs( $amount );
1096 $isNegative = $amount < 0;
1098 $fullField = $this->getPrefixedField( $field );
1100 $dbw = $this->getWriteDbConnection();
1102 $success = $dbw->update(
1104 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
1105 $this->getPrefixedValues( $conditions ),
1107 ) !== false; // DatabaseBase::update does not always return true for success as documented...
1109 $this->releaseConnection( $dbw );