a77074ffca7626e52e3684a852e4916d41b07764
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 * @licence GNU GPL v2 or later
27 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
30 abstract class ORMTable
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 * 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 return wfGetDB( $this->getReadDb() )->select(
150 $this->getPrefixedFields( $fields ),
151 $this->getPrefixedValues( $conditions ),
152 is_null( $functionName ) ? __METHOD__
: $functionName,
158 * Selects the the specified fields of the records matching the provided
159 * conditions and returns them as associative arrays.
160 * Provided field names get prefixed.
161 * Returned field names will not have a prefix.
163 * When $collapse is true:
164 * If one field is selected, each item in the result array will be this field.
165 * If two fields are selected, each item in the result array will have as key
166 * the first field and as value the second field.
167 * If more then two fields are selected, each item will be an associative array.
171 * @param array|string|null $fields
172 * @param array $conditions
173 * @param array $options
174 * @param boolean $collapse Set to false to always return each result row as associative array.
175 * @param string|null $functionName
177 * @return array of array
179 public function selectFields( $fields = null, array $conditions = array(),
180 array $options = array(), $collapse = true, $functionName = null ) {
183 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
185 foreach ( $result as $record ) {
186 $objects[] = $this->getFieldsFromDBResult( $record );
190 if ( count( $fields ) === 1 ) {
191 $objects = array_map( 'array_shift', $objects );
193 elseif ( count( $fields ) === 2 ) {
196 foreach ( $objects as $object ) {
197 $o[array_shift( $object )] = array_shift( $object );
208 * Selects the the specified fields of the first matching record.
209 * Field names get prefixed.
213 * @param array|string|null $fields
214 * @param array $conditions
215 * @param array $options
216 * @param string|null $functionName
218 * @return IORMRow|bool False on failure
220 public function selectRow( $fields = null, array $conditions = array(),
221 array $options = array(), $functionName = null ) {
222 $options['LIMIT'] = 1;
224 $objects = $this->select( $fields, $conditions, $options, $functionName );
226 return $objects->isEmpty() ?
false : $objects->current();
230 * Selects the the specified fields of the records matching the provided
231 * conditions. Field names do NOT get prefixed.
235 * @param array $fields
236 * @param array $conditions
237 * @param array $options
238 * @param string|null $functionName
240 * @return ResultWrapper
242 public function rawSelectRow( array $fields, array $conditions = array(),
243 array $options = array(), $functionName = null ) {
244 $dbr = wfGetDB( $this->getReadDb() );
246 return $dbr->selectRow(
250 is_null( $functionName ) ? __METHOD__
: $functionName,
256 * Selects the the specified fields of the first record matching the provided
257 * conditions and returns it as an associative array, or false when nothing matches.
258 * This method makes use of selectFields and expects the same parameters and
259 * returns the same results (if there are any, if there are none, this method returns false).
260 * @see ORMTable::selectFields
264 * @param array|string|null $fields
265 * @param array $conditions
266 * @param array $options
267 * @param boolean $collapse Set to false to always return each result row as associative array.
268 * @param string|null $functionName
270 * @return mixed|array|bool False on failure
272 public function selectFieldsRow( $fields = null, array $conditions = array(),
273 array $options = array(), $collapse = true, $functionName = null ) {
274 $options['LIMIT'] = 1;
276 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
278 return empty( $objects ) ?
false : $objects[0];
282 * Returns if there is at least one record matching the provided conditions.
283 * Condition field names get prefixed.
287 * @param array $conditions
291 public function has( array $conditions = array() ) {
292 return $this->selectRow( array( 'id' ), $conditions ) !== false;
296 * Returns the amount of matching records.
297 * Condition field names get prefixed.
299 * Note that this can be expensive on large tables.
300 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
304 * @param array $conditions
305 * @param array $options
309 public function count( array $conditions = array(), array $options = array() ) {
310 $res = $this->rawSelectRow(
311 array( 'rowcount' => 'COUNT(*)' ),
312 $this->getPrefixedValues( $conditions ),
316 return $res->rowcount
;
320 * Removes the object from the database.
324 * @param array $conditions
325 * @param string|null $functionName
327 * @return boolean Success indicator
329 public function delete( array $conditions, $functionName = null ) {
330 return wfGetDB( DB_MASTER
)->delete(
332 $conditions === array() ?
'*' : $this->getPrefixedValues( $conditions ),
334 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
338 * Get API parameters for the fields supported by this object.
342 * @param boolean $requireParams
343 * @param boolean $setDefaults
347 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
359 $defaults = $this->getDefaults();
361 foreach ( $this->getFields() as $field => $type ) {
362 if ( $field == 'id' ) {
366 $hasDefault = array_key_exists( $field, $defaults );
368 $params[$field] = array(
369 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
370 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
373 if ( $type == 'array' ) {
374 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
377 if ( $setDefaults && $hasDefault ) {
378 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
379 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
387 * Returns an array with the fields and their descriptions.
389 * field name => field description
395 public function getFieldDescriptions() {
400 * Get the database type used for read operations.
404 * @return integer DB_ enum
406 public function getReadDb() {
407 return $this->readDb
;
411 * Set the database type to use for read operations.
417 public function setReadDb( $db ) {
422 * Update the records matching the provided conditions by
423 * setting the fields that are keys in the $values param to
424 * their corresponding values.
428 * @param array $values
429 * @param array $conditions
431 * @return boolean Success indicator
433 public function update( array $values, array $conditions = array() ) {
434 $dbw = wfGetDB( DB_MASTER
);
438 $this->getPrefixedValues( $values ),
439 $this->getPrefixedValues( $conditions ),
441 ) !== false; // DatabaseBase::update does not always return true for success as documented...
445 * Computes the values of the summary fields of the objects matching the provided conditions.
449 * @param array|string|null $summaryFields
450 * @param array $conditions
452 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
453 $this->setReadDb( DB_MASTER
);
458 foreach ( $this->select( null, $conditions ) as $item ) {
459 $item->loadSummaryFields( $summaryFields );
460 $item->setSummaryMode( true );
464 $this->setReadDb( DB_SLAVE
);
468 * Takes in an associative array with field names as keys and
469 * their values as value. The field names are prefixed with the
474 * @param array $values
478 public function getPrefixedValues( array $values ) {
479 $prefixedValues = array();
481 foreach ( $values as $field => $value ) {
482 if ( is_integer( $field ) ) {
483 if ( is_array( $value ) ) {
488 $value = explode( ' ', $value, 2 );
489 $value[0] = $this->getPrefixedField( $value[0] );
490 $prefixedValues[] = implode( ' ', $value );
495 $prefixedValues[$this->getPrefixedField( $field )] = $value;
498 return $prefixedValues;
502 * Takes in a field or array of fields and returns an
503 * array with their prefixed versions, ready for db usage.
507 * @param array|string $fields
511 public function getPrefixedFields( array $fields ) {
512 foreach ( $fields as &$field ) {
513 $field = $this->getPrefixedField( $field );
520 * Takes in a field and returns an it's prefixed version, ready for db usage.
524 * @param string|array $field
528 public function getPrefixedField( $field ) {
529 return $this->getFieldPrefix() . $field;
533 * Takes an array of field names with prefix and returns the unprefixed equivalent.
537 * @param array $fieldNames
541 public function unprefixFieldNames( array $fieldNames ) {
542 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
546 * Takes a field name with prefix and returns the unprefixed equivalent.
550 * @param string $fieldName
554 public function unprefixFieldName( $fieldName ) {
555 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
559 * Get an instance of this class.
565 public static function singleton() {
566 $class = get_called_class();
568 if ( !array_key_exists( $class, self
::$instanceCache ) ) {
569 self
::$instanceCache[$class] = new $class;
572 return self
::$instanceCache[$class];
576 * Get an array with fields from a database result,
577 * that can be fed directly to the constructor or
582 * @param stdClass $result
586 public function getFieldsFromDBResult( stdClass
$result ) {
587 $result = (array)$result;
588 return array_combine(
589 $this->unprefixFieldNames( array_keys( $result ) ),
590 array_values( $result )
595 * @see ORMTable::newRowFromFromDBResult
597 * @deprecated use newRowFromDBResult instead
600 * @param stdClass $result
604 public function newFromDBResult( stdClass
$result ) {
605 return self
::newRowFromDBResult( $result );
609 * Get a new instance of the class from a database result.
613 * @param stdClass $result
617 public function newRowFromDBResult( stdClass
$result ) {
618 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
622 * @see ORMTable::newRow
624 * @deprecated use newRow instead
628 * @param boolean $loadDefaults
632 public function newFromArray( array $data, $loadDefaults = false ) {
633 return static::newRow( $data, $loadDefaults );
637 * Get a new instance of the class from an array.
642 * @param boolean $loadDefaults
646 public function newRow( array $data, $loadDefaults = false ) {
647 $class = $this->getRowClass();
648 return new $class( $this, $data, $loadDefaults );
652 * Return the names of the fields.
658 public function getFieldNames() {
659 return array_keys( $this->getFields() );
663 * Gets if the object can take a certain field.
667 * @param string $name
671 public function canHaveField( $name ) {
672 return array_key_exists( $name, $this->getFields() );