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 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
102 * Selects the the specified fields of the records matching the provided
103 * conditions and returns them as DBDataObject. Field names get prefixed.
107 * @param array|string|null $fields
108 * @param array $conditions
109 * @param array $options
110 * @param string|null $functionName
112 * @return array of self
114 public function selectObjects( $fields = null, array $conditions = array(),
115 array $options = array(), $functionName = null ) {
116 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
120 foreach ( $result as $record ) {
121 $objects[] = $this->newRow( $record );
128 * Do the actual select.
132 * @param null|string|array $fields
133 * @param array $conditions
134 * @param array $options
135 * @param null|string $functionName
137 * @return ResultWrapper
139 public function rawSelect( $fields = null, array $conditions = array(),
140 array $options = array(), $functionName = null ) {
141 if ( is_null( $fields ) ) {
142 $fields = array_keys( $this->getFields() );
145 $fields = (array)$fields;
148 $dbr = $this->getReadDbConnection();
149 $result = $dbr->select(
151 $this->getPrefixedFields( $fields ),
152 $this->getPrefixedValues( $conditions ),
153 is_null( $functionName ) ? __METHOD__
: $functionName,
157 $this->releaseConnection( $dbr );
162 * Selects the the specified fields of the records matching the provided
163 * conditions and returns them as associative arrays.
164 * Provided field names get prefixed.
165 * Returned field names will not have a prefix.
167 * When $collapse is true:
168 * If one field is selected, each item in the result array will be this field.
169 * If two fields are selected, each item in the result array will have as key
170 * the first field and as value the second field.
171 * If more then two fields are selected, each item will be an associative array.
175 * @param array|string|null $fields
176 * @param array $conditions
177 * @param array $options
178 * @param boolean $collapse Set to false to always return each result row as associative array.
179 * @param string|null $functionName
181 * @return array of array
183 public function selectFields( $fields = null, array $conditions = array(),
184 array $options = array(), $collapse = true, $functionName = null ) {
187 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
189 foreach ( $result as $record ) {
190 $objects[] = $this->getFieldsFromDBResult( $record );
194 if ( count( $fields ) === 1 ) {
195 $objects = array_map( 'array_shift', $objects );
197 elseif ( count( $fields ) === 2 ) {
200 foreach ( $objects as $object ) {
201 $o[array_shift( $object )] = array_shift( $object );
212 * Selects the the specified fields of the first matching record.
213 * Field names get prefixed.
217 * @param array|string|null $fields
218 * @param array $conditions
219 * @param array $options
220 * @param string|null $functionName
222 * @return IORMRow|bool False on failure
224 public function selectRow( $fields = null, array $conditions = array(),
225 array $options = array(), $functionName = null ) {
226 $options['LIMIT'] = 1;
228 $objects = $this->select( $fields, $conditions, $options, $functionName );
230 return $objects->isEmpty() ?
false : $objects->current();
234 * Selects the the specified fields of the records matching the provided
235 * conditions. Field names do NOT get prefixed.
239 * @param array $fields
240 * @param array $conditions
241 * @param array $options
242 * @param string|null $functionName
244 * @return ResultWrapper
246 public function rawSelectRow( array $fields, array $conditions = array(),
247 array $options = array(), $functionName = null ) {
248 $dbr = $this->getReadDbConnection();
250 $result = $dbr->selectRow(
254 is_null( $functionName ) ? __METHOD__
: $functionName,
258 $this->releaseConnection( $dbr );
263 * Selects the the specified fields of the first record matching the provided
264 * conditions and returns it as an associative array, or false when nothing matches.
265 * This method makes use of selectFields and expects the same parameters and
266 * returns the same results (if there are any, if there are none, this method returns false).
267 * @see ORMTable::selectFields
271 * @param array|string|null $fields
272 * @param array $conditions
273 * @param array $options
274 * @param boolean $collapse Set to false to always return each result row as associative array.
275 * @param string|null $functionName
277 * @return mixed|array|bool False on failure
279 public function selectFieldsRow( $fields = null, array $conditions = array(),
280 array $options = array(), $collapse = true, $functionName = null ) {
281 $options['LIMIT'] = 1;
283 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
285 return empty( $objects ) ?
false : $objects[0];
289 * Returns if there is at least one record matching the provided conditions.
290 * Condition field names get prefixed.
294 * @param array $conditions
298 public function has( array $conditions = array() ) {
299 return $this->selectRow( array( 'id' ), $conditions ) !== false;
303 * Checks if the table exists
309 public function exists() {
310 $dbr = $this->getReadDbConnection();
311 $exists = $dbr->tableExists( $this->getName() );
312 $this->releaseConnection( $dbr );
318 * Returns the amount of matching records.
319 * Condition field names get prefixed.
321 * Note that this can be expensive on large tables.
322 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
326 * @param array $conditions
327 * @param array $options
331 public function count( array $conditions = array(), array $options = array() ) {
332 $res = $this->rawSelectRow(
333 array( 'rowcount' => 'COUNT(*)' ),
334 $this->getPrefixedValues( $conditions ),
339 return $res->rowcount
;
343 * Removes the object from the database.
347 * @param array $conditions
348 * @param string|null $functionName
350 * @return boolean Success indicator
352 public function delete( array $conditions, $functionName = null ) {
353 $dbw = $this->getWriteDbConnection();
355 $result = $dbw->delete(
357 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
358 is_null( $functionName ) ? __METHOD__
: $functionName
359 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
361 $this->releaseConnection( $dbw );
366 * Get API parameters for the fields supported by this object.
370 * @param boolean $requireParams
371 * @param boolean $setDefaults
375 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
387 $defaults = $this->getDefaults();
389 foreach ( $this->getFields() as $field => $type ) {
390 if ( $field == 'id' ) {
394 $hasDefault = array_key_exists( $field, $defaults );
396 $params[$field] = array(
397 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
398 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
401 if ( $type == 'array' ) {
402 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
405 if ( $setDefaults && $hasDefault ) {
406 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
407 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
415 * Returns an array with the fields and their descriptions.
417 * field name => field description
423 public function getFieldDescriptions() {
428 * Get the database ID used for read operations.
432 * @return integer DB_ enum
434 public function getReadDb() {
435 return $this->readDb
;
439 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
445 public function setReadDb( $db ) {
450 * Get the ID of the any foreign wiki to use as a target for database operations
454 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
456 public function getTargetWiki() {
461 * Set the ID of the any foreign wiki to use as a target for database operations
463 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
467 public function setTargetWiki( $wiki ) {
472 * Get the database type used for read operations.
473 * This is to be used instead of wfGetDB.
475 * @see LoadBalancer::getConnection
479 * @return DatabaseBase The database object
481 public function getReadDbConnection() {
482 return $this->getConnection( $this->getReadDb(), array() );
486 * Get the database type used for read operations.
487 * This is to be used instead of wfGetDB.
489 * @see LoadBalancer::getConnection
493 * @return DatabaseBase The database object
495 public function getWriteDbConnection() {
496 return $this->getConnection( DB_MASTER
, array() );
500 * Releases the lease on the given database connection. This is useful mainly
501 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
503 * @see LoadBalancer::reuseConnection
505 * @param DatabaseBase $db the database
509 public function releaseConnection( DatabaseBase
$db ) {
510 parent
::releaseConnection( $db ); // just make it public
514 * Update the records matching the provided conditions by
515 * setting the fields that are keys in the $values param to
516 * their corresponding values.
520 * @param array $values
521 * @param array $conditions
523 * @return boolean Success indicator
525 public function update( array $values, array $conditions = array() ) {
526 $dbw = $this->getWriteDbConnection();
528 $result = $dbw->update(
530 $this->getPrefixedValues( $values ),
531 $this->getPrefixedValues( $conditions ),
533 ) !== false; // DatabaseBase::update does not always return true for success as documented...
535 $this->releaseConnection( $dbw );
540 * Computes the values of the summary fields of the objects matching the provided conditions.
544 * @param array|string|null $summaryFields
545 * @param array $conditions
547 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
548 $slave = $this->getReadDb();
549 $this->setReadDb( DB_MASTER
);
554 foreach ( $this->select( null, $conditions ) as $item ) {
555 $item->loadSummaryFields( $summaryFields );
556 $item->setSummaryMode( true );
560 $this->setReadDb( $slave );
564 * Takes in an associative array with field names as keys and
565 * their values as value. The field names are prefixed with the
570 * @param array $values
574 public function getPrefixedValues( array $values ) {
575 $prefixedValues = array();
577 foreach ( $values as $field => $value ) {
578 if ( is_integer( $field ) ) {
579 if ( is_array( $value ) ) {
584 $value = explode( ' ', $value, 2 );
585 $value[0] = $this->getPrefixedField( $value[0] );
586 $prefixedValues[] = implode( ' ', $value );
591 $prefixedValues[$this->getPrefixedField( $field )] = $value;
594 return $prefixedValues;
598 * Takes in a field or array of fields and returns an
599 * array with their prefixed versions, ready for db usage.
603 * @param array|string $fields
607 public function getPrefixedFields( array $fields ) {
608 foreach ( $fields as &$field ) {
609 $field = $this->getPrefixedField( $field );
616 * Takes in a field and returns an it's prefixed version, ready for db usage.
620 * @param string|array $field
624 public function getPrefixedField( $field ) {
625 return $this->getFieldPrefix() . $field;
629 * Takes an array of field names with prefix and returns the unprefixed equivalent.
633 * @param array $fieldNames
637 public function unprefixFieldNames( array $fieldNames ) {
638 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
642 * Takes a field name with prefix and returns the unprefixed equivalent.
646 * @param string $fieldName
650 public function unprefixFieldName( $fieldName ) {
651 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
655 * Get an instance of this class.
661 public static function singleton() {
662 $class = get_called_class();
664 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
665 self
::$instanceCache[$class] = new $class;
668 return self
::$instanceCache[$class];
672 * Get an array with fields from a database result,
673 * that can be fed directly to the constructor or
678 * @param stdClass $result
682 public function getFieldsFromDBResult( stdClass
$result ) {
683 $result = (array)$result;
684 return array_combine(
685 $this->unprefixFieldNames( array_keys( $result ) ),
686 array_values( $result )
691 * @see ORMTable::newRowFromFromDBResult
693 * @deprecated use newRowFromDBResult instead
696 * @param stdClass $result
700 public function newFromDBResult( stdClass
$result ) {
701 return self
::newRowFromDBResult( $result );
705 * Get a new instance of the class from a database result.
709 * @param stdClass $result
713 public function newRowFromDBResult( stdClass
$result ) {
714 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
718 * @see ORMTable::newRow
720 * @deprecated use newRow instead
724 * @param boolean $loadDefaults
728 public function newFromArray( array $data, $loadDefaults = false ) {
729 return static::newRow( $data, $loadDefaults );
733 * Get a new instance of the class from an array.
738 * @param boolean $loadDefaults
742 public function newRow( array $data, $loadDefaults = false ) {
743 $class = $this->getRowClass();
744 return new $class( $this, $data, $loadDefaults );
748 * Return the names of the fields.
754 public function getFieldNames() {
755 return array_keys( $this->getFields() );
759 * Gets if the object can take a certain field.
763 * @param string $name
767 public function canHaveField( $name ) {
768 return array_key_exists( $name, $this->getFields() );