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 ),
338 return $res->rowcount
;
342 * Removes the object from the database.
346 * @param array $conditions
347 * @param string|null $functionName
349 * @return boolean Success indicator
351 public function delete( array $conditions, $functionName = null ) {
352 $dbw = $this->getWriteDbConnection();
354 $result = $dbw->delete(
356 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
358 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
360 $this->releaseConnection( $dbw );
365 * Get API parameters for the fields supported by this object.
369 * @param boolean $requireParams
370 * @param boolean $setDefaults
374 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
386 $defaults = $this->getDefaults();
388 foreach ( $this->getFields() as $field => $type ) {
389 if ( $field == 'id' ) {
393 $hasDefault = array_key_exists( $field, $defaults );
395 $params[$field] = array(
396 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
397 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
400 if ( $type == 'array' ) {
401 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
404 if ( $setDefaults && $hasDefault ) {
405 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
406 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
414 * Returns an array with the fields and their descriptions.
416 * field name => field description
422 public function getFieldDescriptions() {
427 * Get the database ID used for read operations.
431 * @return integer DB_ enum
433 public function getReadDb() {
434 return $this->readDb
;
438 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
444 public function setReadDb( $db ) {
449 * Get the ID of the any foreign wiki to use as a target for database operations
453 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
455 public function getTargetWiki() {
460 * Set the ID of the any foreign wiki to use as a target for database operations
462 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
466 public function setTargetWiki( $wiki ) {
471 * Get the database type used for read operations.
472 * This is to be used instead of wfGetDB.
474 * @see LoadBalancer::getConnection
478 * @return DatabaseBase The database object
480 public function getReadDbConnection() {
481 return $this->getConnection( $this->getReadDb(), array() );
485 * Get the database type used for read operations.
486 * This is to be used instead of wfGetDB.
488 * @see LoadBalancer::getConnection
492 * @return DatabaseBase The database object
494 public function getWriteDbConnection() {
495 return $this->getConnection( DB_MASTER
, array() );
499 * Releases the lease on the given database connection. This is useful mainly
500 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
502 * @see LoadBalancer::reuseConnection
504 * @param DatabaseBase $db the database
508 public function releaseConnection( DatabaseBase
$db ) {
509 parent
::releaseConnection( $db ); // just make it public
513 * Update the records matching the provided conditions by
514 * setting the fields that are keys in the $values param to
515 * their corresponding values.
519 * @param array $values
520 * @param array $conditions
522 * @return boolean Success indicator
524 public function update( array $values, array $conditions = array() ) {
525 $dbw = $this->getWriteDbConnection();
527 $result = $dbw->update(
529 $this->getPrefixedValues( $values ),
530 $this->getPrefixedValues( $conditions ),
532 ) !== false; // DatabaseBase::update does not always return true for success as documented...
534 $this->releaseConnection( $dbw );
539 * Computes the values of the summary fields of the objects matching the provided conditions.
543 * @param array|string|null $summaryFields
544 * @param array $conditions
546 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
547 $slave = $this->getReadDb();
548 $this->setReadDb( DB_MASTER
);
553 foreach ( $this->select( null, $conditions ) as $item ) {
554 $item->loadSummaryFields( $summaryFields );
555 $item->setSummaryMode( true );
559 $this->setReadDb( $slave );
563 * Takes in an associative array with field names as keys and
564 * their values as value. The field names are prefixed with the
569 * @param array $values
573 public function getPrefixedValues( array $values ) {
574 $prefixedValues = array();
576 foreach ( $values as $field => $value ) {
577 if ( is_integer( $field ) ) {
578 if ( is_array( $value ) ) {
583 $value = explode( ' ', $value, 2 );
584 $value[0] = $this->getPrefixedField( $value[0] );
585 $prefixedValues[] = implode( ' ', $value );
590 $prefixedValues[$this->getPrefixedField( $field )] = $value;
593 return $prefixedValues;
597 * Takes in a field or array of fields and returns an
598 * array with their prefixed versions, ready for db usage.
602 * @param array|string $fields
606 public function getPrefixedFields( array $fields ) {
607 foreach ( $fields as &$field ) {
608 $field = $this->getPrefixedField( $field );
615 * Takes in a field and returns an it's prefixed version, ready for db usage.
619 * @param string|array $field
623 public function getPrefixedField( $field ) {
624 return $this->getFieldPrefix() . $field;
628 * Takes an array of field names with prefix and returns the unprefixed equivalent.
632 * @param array $fieldNames
636 public function unprefixFieldNames( array $fieldNames ) {
637 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
641 * Takes a field name with prefix and returns the unprefixed equivalent.
645 * @param string $fieldName
649 public function unprefixFieldName( $fieldName ) {
650 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
654 * Get an instance of this class.
660 public static function singleton() {
661 $class = get_called_class();
663 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
664 self
::$instanceCache[$class] = new $class;
667 return self
::$instanceCache[$class];
671 * Get an array with fields from a database result,
672 * that can be fed directly to the constructor or
677 * @param stdClass $result
681 public function getFieldsFromDBResult( stdClass
$result ) {
682 $result = (array)$result;
683 return array_combine(
684 $this->unprefixFieldNames( array_keys( $result ) ),
685 array_values( $result )
690 * @see ORMTable::newRowFromFromDBResult
692 * @deprecated use newRowFromDBResult instead
695 * @param stdClass $result
699 public function newFromDBResult( stdClass
$result ) {
700 return self
::newRowFromDBResult( $result );
704 * Get a new instance of the class from a database result.
708 * @param stdClass $result
712 public function newRowFromDBResult( stdClass
$result ) {
713 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
717 * @see ORMTable::newRow
719 * @deprecated use newRow instead
723 * @param boolean $loadDefaults
727 public function newFromArray( array $data, $loadDefaults = false ) {
728 return static::newRow( $data, $loadDefaults );
732 * Get a new instance of the class from an array.
737 * @param boolean $loadDefaults
741 public function newRow( array $data, $loadDefaults = false ) {
742 $class = $this->getRowClass();
743 return new $class( $this, $data, $loadDefaults );
747 * Return the names of the fields.
753 public function getFieldNames() {
754 return array_keys( $this->getFields() );
758 * Gets if the object can take a certain field.
762 * @param string $name
766 public function canHaveField( $name ) {
767 return array_key_exists( $name, $this->getFields() );