Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / db / ORMTable.php
blob651eadd5c3579097dc801a39a5ffc0aa78aed3b6
1 <?php
3 /**
4 * Abstract base class for representing a single database table.
6 * @since 1.20
8 * @file ORMTable.php
10 * @licence GNU GPL v2 or later
11 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
13 abstract class ORMTable {
15 /**
16 * Returns the name of the database table objects of this type are stored in.
18 * @since 1.20
20 * @return string
22 public abstract function getName();
24 /**
25 * Returns the name of a ORMRow deriving class that
26 * represents single rows in this table.
28 * @since 1.20
30 * @return string
32 public abstract function getRowClass();
34 /**
35 * Gets the db field prefix.
37 * @since 1.20
39 * @return string
41 protected abstract function getFieldPrefix();
43 /**
44 * Returns an array with the fields and their types this object contains.
45 * This corresponds directly to the fields in the database, without prefix.
47 * field name => type
49 * Allowed types:
50 * * id
51 * * str
52 * * int
53 * * float
54 * * bool
55 * * array
57 * @since 1.20
59 * @return array
61 public abstract function getFields();
63 /**
64 * Cache for instances, used by the singleton method.
66 * @since 1.20
67 * @var array of DBTable
69 protected static $instanceCache = array();
71 /**
72 * The database connection to use for read operations.
73 * Can be changed via @see setReadDb.
75 * @since 1.20
76 * @var integer DB_ enum
78 protected $readDb = DB_SLAVE;
80 /**
81 * Returns a list of default field values.
82 * field name => field value
84 * @since 1.20
86 * @return array
88 public function getDefaults() {
89 return array();
92 /**
93 * Returns a list of the summary fields.
94 * These are fields that cache computed values, such as the amount of linked objects of $type.
95 * This is relevant as one might not want to do actions such as log changes when these get updated.
97 * @since 1.20
99 * @return array
101 public function getSummaryFields() {
102 return array();
106 * Selects the the specified fields of the records matching the provided
107 * conditions and returns them as DBDataObject. Field names get prefixed.
109 * @since 1.20
111 * @param array|string|null $fields
112 * @param array $conditions
113 * @param array $options
114 * @param string|null $functionName
116 * @return ORMResult
118 public function select( $fields = null, array $conditions = array(),
119 array $options = array(), $functionName = null ) {
120 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
124 * Selects the the specified fields of the records matching the provided
125 * conditions and returns them as DBDataObject. Field names get prefixed.
127 * @since 1.20
129 * @param array|string|null $fields
130 * @param array $conditions
131 * @param array $options
132 * @param string|null $functionName
134 * @return array of self
136 public function selectObjects( $fields = null, array $conditions = array(),
137 array $options = array(), $functionName = null ) {
138 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
140 $objects = array();
142 foreach ( $result as $record ) {
143 $objects[] = $this->newFromArray( $record );
146 return $objects;
150 * Do the actual select.
152 * @since 1.20
154 * @param null|string|array $fields
155 * @param array $conditions
156 * @param array $options
157 * @param null|string $functionName
159 * @return ResultWrapper
161 public function rawSelect( $fields = null, array $conditions = array(),
162 array $options = array(), $functionName = null ) {
163 if ( is_null( $fields ) ) {
164 $fields = array_keys( $this->getFields() );
166 else {
167 $fields = (array)$fields;
170 return wfGetDB( $this->getReadDb() )->select(
171 $this->getName(),
172 $this->getPrefixedFields( $fields ),
173 $this->getPrefixedValues( $conditions ),
174 is_null( $functionName ) ? __METHOD__ : $functionName,
175 $options
180 * Selects the the specified fields of the records matching the provided
181 * conditions and returns them as associative arrays.
182 * Provided field names get prefixed.
183 * Returned field names will not have a prefix.
185 * When $collapse is true:
186 * If one field is selected, each item in the result array will be this field.
187 * If two fields are selected, each item in the result array will have as key
188 * the first field and as value the second field.
189 * If more then two fields are selected, each item will be an associative array.
191 * @since 1.20
193 * @param array|string|null $fields
194 * @param array $conditions
195 * @param array $options
196 * @param boolean $collapse Set to false to always return each result row as associative array.
197 * @param string|null $functionName
199 * @return array of array
201 public function selectFields( $fields = null, array $conditions = array(),
202 array $options = array(), $collapse = true, $functionName = null ) {
203 $objects = array();
205 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
207 foreach ( $result as $record ) {
208 $objects[] = $this->getFieldsFromDBResult( $record );
211 if ( $collapse ) {
212 if ( count( $fields ) === 1 ) {
213 $objects = array_map( 'array_shift', $objects );
215 elseif ( count( $fields ) === 2 ) {
216 $o = array();
218 foreach ( $objects as $object ) {
219 $o[array_shift( $object )] = array_shift( $object );
222 $objects = $o;
226 return $objects;
230 * Selects the the specified fields of the first matching record.
231 * Field names get prefixed.
233 * @since 1.20
235 * @param array|string|null $fields
236 * @param array $conditions
237 * @param array $options
238 * @param string|null $functionName
240 * @return DBObject|bool False on failure
242 public function selectRow( $fields = null, array $conditions = array(),
243 array $options = array(), $functionName = null ) {
244 $options['LIMIT'] = 1;
246 $objects = $this->select( $fields, $conditions, $options, $functionName );
248 return $objects->isEmpty() ? false : $objects->current();
252 * Selects the the specified fields of the records matching the provided
253 * conditions. Field names do NOT get prefixed.
255 * @since 1.20
257 * @param array $fields
258 * @param array $conditions
259 * @param array $options
260 * @param string|null $functionName
262 * @return ResultWrapper
264 public function rawSelectRow( array $fields, array $conditions = array(),
265 array $options = array(), $functionName = null ) {
266 $dbr = wfGetDB( $this->getReadDb() );
268 return $dbr->selectRow(
269 $this->getName(),
270 $fields,
271 $conditions,
272 is_null( $functionName ) ? __METHOD__ : $functionName,
273 $options
278 * Selects the the specified fields of the first record matching the provided
279 * conditions and returns it as an associative array, or false when nothing matches.
280 * This method makes use of selectFields and expects the same parameters and
281 * returns the same results (if there are any, if there are none, this method returns false).
282 * @see ORMTable::selectFields
284 * @since 1.20
286 * @param array|string|null $fields
287 * @param array $conditions
288 * @param array $options
289 * @param boolean $collapse Set to false to always return each result row as associative array.
290 * @param string|null $functionName
292 * @return mixed|array|bool False on failure
294 public function selectFieldsRow( $fields = null, array $conditions = array(),
295 array $options = array(), $collapse = true, $functionName = null ) {
296 $options['LIMIT'] = 1;
298 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
300 return empty( $objects ) ? false : $objects[0];
304 * Returns if there is at least one record matching the provided conditions.
305 * Condition field names get prefixed.
307 * @since 1.20
309 * @param array $conditions
311 * @return boolean
313 public function has( array $conditions = array() ) {
314 return $this->selectRow( array( 'id' ), $conditions ) !== false;
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.
324 * @since 1.20
326 * @param array $conditions
327 * @param array $options
329 * @return integer
331 public function count( array $conditions = array(), array $options = array() ) {
332 $res = $this->rawSelectRow(
333 array( 'COUNT(*) AS rowcount' ),
334 $this->getPrefixedValues( $conditions ),
335 $options
338 return $res->rowcount;
342 * Removes the object from the database.
344 * @since 1.20
346 * @param array $conditions
347 * @param string|null $functionName
349 * @return boolean Success indicator
351 public function delete( array $conditions, $functionName = null ) {
352 return wfGetDB( DB_MASTER )->delete(
353 $this->getName(),
354 $this->getPrefixedValues( $conditions ),
355 $functionName
360 * Get API parameters for the fields supported by this object.
362 * @since 1.20
364 * @param boolean $requireParams
365 * @param boolean $setDefaults
367 * @return array
369 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
370 $typeMap = array(
371 'id' => 'integer',
372 'int' => 'integer',
373 'float' => 'NULL',
374 'str' => 'string',
375 'bool' => 'integer',
376 'array' => 'string',
377 'blob' => 'string',
380 $params = array();
381 $defaults = $this->getDefaults();
383 foreach ( $this->getFields() as $field => $type ) {
384 if ( $field == 'id' ) {
385 continue;
388 $hasDefault = array_key_exists( $field, $defaults );
390 $params[$field] = array(
391 ApiBase::PARAM_TYPE => $typeMap[$type],
392 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
395 if ( $type == 'array' ) {
396 $params[$field][ApiBase::PARAM_ISMULTI] = true;
399 if ( $setDefaults && $hasDefault ) {
400 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
401 $params[$field][ApiBase::PARAM_DFLT] = $default;
405 return $params;
409 * Returns an array with the fields and their descriptions.
411 * field name => field description
413 * @since 1.20
415 * @return array
417 public function getFieldDescriptions() {
418 return array();
422 * Get the database type used for read operations.
424 * @since 1.20
426 * @return integer DB_ enum
428 public function getReadDb() {
429 return $this->readDb;
433 * Set the database type to use for read operations.
435 * @param integer $db
437 * @since 1.20
439 public function setReadDb( $db ) {
440 $this->readDb = $db;
444 * Update the records matching the provided conditions by
445 * setting the fields that are keys in the $values param to
446 * their corresponding values.
448 * @since 1.20
450 * @param array $values
451 * @param array $conditions
453 * @return boolean Success indicator
455 public function update( array $values, array $conditions = array() ) {
456 $dbw = wfGetDB( DB_MASTER );
458 return $dbw->update(
459 $this->getName(),
460 $this->getPrefixedValues( $values ),
461 $this->getPrefixedValues( $conditions ),
462 __METHOD__
467 * Computes the values of the summary fields of the objects matching the provided conditions.
469 * @since 1.20
471 * @param array|string|null $summaryFields
472 * @param array $conditions
474 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
475 $this->setReadDb( DB_MASTER );
477 foreach ( $this->select( null, $conditions ) as /* ORMRow */ $item ) {
478 $item->loadSummaryFields( $summaryFields );
479 $item->setSummaryMode( true );
480 $item->save();
483 $this->setReadDb( DB_SLAVE );
487 * Takes in an associative array with field names as keys and
488 * their values as value. The field names are prefixed with the
489 * db field prefix.
491 * Field names can also be provided as an array with as first element a table name, such as
492 * $conditions = array(
493 * array( array( 'tablename', 'fieldname' ), $value ),
494 * );
496 * @since 1.20
498 * @param array $values
500 * @return array
502 public function getPrefixedValues( array $values ) {
503 $prefixedValues = array();
505 foreach ( $values as $field => $value ) {
506 if ( is_integer( $field ) ) {
507 if ( is_array( $value ) ) {
508 $field = $value[0];
509 $value = $value[1];
511 else {
512 $value = explode( ' ', $value, 2 );
513 $value[0] = $this->getPrefixedField( $value[0] );
514 $prefixedValues[] = implode( ' ', $value );
515 continue;
519 $prefixedValues[$this->getPrefixedField( $field )] = $value;
522 return $prefixedValues;
526 * Takes in a field or array of fields and returns an
527 * array with their prefixed versions, ready for db usage.
529 * @since 1.20
531 * @param array|string $fields
533 * @return array
535 public function getPrefixedFields( array $fields ) {
536 foreach ( $fields as &$field ) {
537 $field = $this->getPrefixedField( $field );
540 return $fields;
544 * Takes in a field and returns an it's prefixed version, ready for db usage.
546 * @since 1.20
548 * @param string|array $field
550 * @return string
552 public function getPrefixedField( $field ) {
553 return $this->getFieldPrefix() . $field;
557 * Takes an array of field names with prefix and returns the unprefixed equivalent.
559 * @since 1.20
561 * @param array $fieldNames
563 * @return array
565 public function unprefixFieldNames( array $fieldNames ) {
566 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
570 * Takes a field name with prefix and returns the unprefixed equivalent.
572 * @since 1.20
574 * @param string $fieldName
576 * @return string
578 public function unprefixFieldName( $fieldName ) {
579 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
583 * Get an instance of this class.
585 * @since 1.20
587 * @return ORMTable
589 public static function singleton() {
590 $class = function_exists( 'get_called_class' ) ? get_called_class() : self::get_called_class();
592 if ( !array_key_exists( $class, self::$instanceCache ) ) {
593 self::$instanceCache[$class] = new $class;
596 return self::$instanceCache[$class];
600 * Compatibility fallback function so the singleton method works on PHP < 5.3.
601 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
603 * @since 1.20
605 * @return string
607 protected static function get_called_class() {
608 $bt = debug_backtrace();
609 $l = count($bt) - 1;
610 $matches = array();
611 while(empty($matches) && $l > -1){
612 $lines = file($bt[$l]['file']);
613 $callerLine = $lines[$bt[$l]['line']-1];
614 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
615 $callerLine,
616 $matches);
618 if (!isset($matches[1])) $matches[1]=NULL; //for notices
619 if ($matches[1] == 'self') {
620 $line = $bt[$l]['line']-1;
621 while ($line > 0 && strpos($lines[$line], 'class') === false) {
622 $line--;
624 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
626 return $matches[1];
630 * Get an array with fields from a database result,
631 * that can be fed directly to the constructor or
632 * to setFields.
634 * @since 1.20
636 * @param stdClass $result
638 * @return array
640 public function getFieldsFromDBResult( stdClass $result ) {
641 $result = (array)$result;
642 return array_combine(
643 $this->unprefixFieldNames( array_keys( $result ) ),
644 array_values( $result )
649 * Get a new instance of the class from a database result.
651 * @since 1.20
653 * @param stdClass $result
655 * @return ORMRow
657 public function newFromDBResult( stdClass $result ) {
658 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
662 * Get a new instance of the class from an array.
664 * @since 1.20
666 * @param array $data
667 * @param boolean $loadDefaults
669 * @return ORMRow
671 public function newFromArray( array $data, $loadDefaults = false ) {
672 $class = $this->getRowClass();
673 return new $class( $this, $data, $loadDefaults );
677 * Return the names of the fields.
679 * @since 1.20
681 * @return array
683 public function getFieldNames() {
684 return array_keys( $this->getFields() );
688 * Gets if the object can take a certain field.
690 * @since 1.20
692 * @param string $name
694 * @return boolean
696 public function canHaveField( $name ) {
697 return array_key_exists( $name, $this->getFields() );