Merge "[FileBackend] Refactored Swift backend to use ProcessCacheLRU."
[lhc/web/wiklou.git] / includes / db / ORMTable.php
1 <?php
2 /**
3 * Abstract base class for representing a single database table.
4 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
5 *
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.
10 *
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.
15 *
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
20 *
21 * @since 1.20
22 *
23 * @file ORMTable.php
24 * @ingroup ORM
25 *
26 * @licence GNU GPL v2 or later
27 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
28 */
29
30 abstract class ORMTable implements IORMTable {
31
32 /**
33 * Gets the db field prefix.
34 *
35 * @since 1.20
36 *
37 * @return string
38 */
39 protected abstract function getFieldPrefix();
40
41 /**
42 * Cache for instances, used by the singleton method.
43 *
44 * @since 1.20
45 * @var array of DBTable
46 */
47 protected static $instanceCache = array();
48
49 /**
50 * The database connection to use for read operations.
51 * Can be changed via @see setReadDb.
52 *
53 * @since 1.20
54 * @var integer DB_ enum
55 */
56 protected $readDb = DB_SLAVE;
57
58 /**
59 * Returns a list of default field values.
60 * field name => field value
61 *
62 * @since 1.20
63 *
64 * @return array
65 */
66 public function getDefaults() {
67 return array();
68 }
69
70 /**
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.
74 *
75 * @since 1.20
76 *
77 * @return array
78 */
79 public function getSummaryFields() {
80 return array();
81 }
82
83 /**
84 * Selects the the specified fields of the records matching the provided
85 * conditions and returns them as DBDataObject. Field names get prefixed.
86 *
87 * @since 1.20
88 *
89 * @param array|string|null $fields
90 * @param array $conditions
91 * @param array $options
92 * @param string|null $functionName
93 *
94 * @return ORMResult
95 */
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 ) );
99 }
100
101 /**
102 * Selects the the specified fields of the records matching the provided
103 * conditions and returns them as DBDataObject. Field names get prefixed.
104 *
105 * @since 1.20
106 *
107 * @param array|string|null $fields
108 * @param array $conditions
109 * @param array $options
110 * @param string|null $functionName
111 *
112 * @return array of self
113 */
114 public function selectObjects( $fields = null, array $conditions = array(),
115 array $options = array(), $functionName = null ) {
116 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
117
118 $objects = array();
119
120 foreach ( $result as $record ) {
121 $objects[] = $this->newRow( $record );
122 }
123
124 return $objects;
125 }
126
127 /**
128 * Do the actual select.
129 *
130 * @since 1.20
131 *
132 * @param null|string|array $fields
133 * @param array $conditions
134 * @param array $options
135 * @param null|string $functionName
136 *
137 * @return ResultWrapper
138 */
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() );
143 }
144 else {
145 $fields = (array)$fields;
146 }
147
148 return wfGetDB( $this->getReadDb() )->select(
149 $this->getName(),
150 $this->getPrefixedFields( $fields ),
151 $this->getPrefixedValues( $conditions ),
152 is_null( $functionName ) ? __METHOD__ : $functionName,
153 $options
154 );
155 }
156
157 /**
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.
162 *
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.
168 *
169 * @since 1.20
170 *
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
176 *
177 * @return array of array
178 */
179 public function selectFields( $fields = null, array $conditions = array(),
180 array $options = array(), $collapse = true, $functionName = null ) {
181 $objects = array();
182
183 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
184
185 foreach ( $result as $record ) {
186 $objects[] = $this->getFieldsFromDBResult( $record );
187 }
188
189 if ( $collapse ) {
190 if ( count( $fields ) === 1 ) {
191 $objects = array_map( 'array_shift', $objects );
192 }
193 elseif ( count( $fields ) === 2 ) {
194 $o = array();
195
196 foreach ( $objects as $object ) {
197 $o[array_shift( $object )] = array_shift( $object );
198 }
199
200 $objects = $o;
201 }
202 }
203
204 return $objects;
205 }
206
207 /**
208 * Selects the the specified fields of the first matching record.
209 * Field names get prefixed.
210 *
211 * @since 1.20
212 *
213 * @param array|string|null $fields
214 * @param array $conditions
215 * @param array $options
216 * @param string|null $functionName
217 *
218 * @return IORMRow|bool False on failure
219 */
220 public function selectRow( $fields = null, array $conditions = array(),
221 array $options = array(), $functionName = null ) {
222 $options['LIMIT'] = 1;
223
224 $objects = $this->select( $fields, $conditions, $options, $functionName );
225
226 return $objects->isEmpty() ? false : $objects->current();
227 }
228
229 /**
230 * Selects the the specified fields of the records matching the provided
231 * conditions. Field names do NOT get prefixed.
232 *
233 * @since 1.20
234 *
235 * @param array $fields
236 * @param array $conditions
237 * @param array $options
238 * @param string|null $functionName
239 *
240 * @return ResultWrapper
241 */
242 public function rawSelectRow( array $fields, array $conditions = array(),
243 array $options = array(), $functionName = null ) {
244 $dbr = wfGetDB( $this->getReadDb() );
245
246 return $dbr->selectRow(
247 $this->getName(),
248 $fields,
249 $conditions,
250 is_null( $functionName ) ? __METHOD__ : $functionName,
251 $options
252 );
253 }
254
255 /**
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
261 *
262 * @since 1.20
263 *
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
269 *
270 * @return mixed|array|bool False on failure
271 */
272 public function selectFieldsRow( $fields = null, array $conditions = array(),
273 array $options = array(), $collapse = true, $functionName = null ) {
274 $options['LIMIT'] = 1;
275
276 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
277
278 return empty( $objects ) ? false : $objects[0];
279 }
280
281 /**
282 * Returns if there is at least one record matching the provided conditions.
283 * Condition field names get prefixed.
284 *
285 * @since 1.20
286 *
287 * @param array $conditions
288 *
289 * @return boolean
290 */
291 public function has( array $conditions = array() ) {
292 return $this->selectRow( array( 'id' ), $conditions ) !== false;
293 }
294
295 /**
296 * Returns the amount of matching records.
297 * Condition field names get prefixed.
298 *
299 * Note that this can be expensive on large tables.
300 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
301 *
302 * @since 1.20
303 *
304 * @param array $conditions
305 * @param array $options
306 *
307 * @return integer
308 */
309 public function count( array $conditions = array(), array $options = array() ) {
310 $res = $this->rawSelectRow(
311 array( 'rowcount' => 'COUNT(*)' ),
312 $this->getPrefixedValues( $conditions ),
313 $options
314 );
315
316 return $res->rowcount;
317 }
318
319 /**
320 * Removes the object from the database.
321 *
322 * @since 1.20
323 *
324 * @param array $conditions
325 * @param string|null $functionName
326 *
327 * @return boolean Success indicator
328 */
329 public function delete( array $conditions, $functionName = null ) {
330 return wfGetDB( DB_MASTER )->delete(
331 $this->getName(),
332 $conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
333 $functionName
334 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
335 }
336
337 /**
338 * Get API parameters for the fields supported by this object.
339 *
340 * @since 1.20
341 *
342 * @param boolean $requireParams
343 * @param boolean $setDefaults
344 *
345 * @return array
346 */
347 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
348 $typeMap = array(
349 'id' => 'integer',
350 'int' => 'integer',
351 'float' => 'NULL',
352 'str' => 'string',
353 'bool' => 'integer',
354 'array' => 'string',
355 'blob' => 'string',
356 );
357
358 $params = array();
359 $defaults = $this->getDefaults();
360
361 foreach ( $this->getFields() as $field => $type ) {
362 if ( $field == 'id' ) {
363 continue;
364 }
365
366 $hasDefault = array_key_exists( $field, $defaults );
367
368 $params[$field] = array(
369 ApiBase::PARAM_TYPE => $typeMap[$type],
370 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
371 );
372
373 if ( $type == 'array' ) {
374 $params[$field][ApiBase::PARAM_ISMULTI] = true;
375 }
376
377 if ( $setDefaults && $hasDefault ) {
378 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
379 $params[$field][ApiBase::PARAM_DFLT] = $default;
380 }
381 }
382
383 return $params;
384 }
385
386 /**
387 * Returns an array with the fields and their descriptions.
388 *
389 * field name => field description
390 *
391 * @since 1.20
392 *
393 * @return array
394 */
395 public function getFieldDescriptions() {
396 return array();
397 }
398
399 /**
400 * Get the database type used for read operations.
401 *
402 * @since 1.20
403 *
404 * @return integer DB_ enum
405 */
406 public function getReadDb() {
407 return $this->readDb;
408 }
409
410 /**
411 * Set the database type to use for read operations.
412 *
413 * @param integer $db
414 *
415 * @since 1.20
416 */
417 public function setReadDb( $db ) {
418 $this->readDb = $db;
419 }
420
421 /**
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.
425 *
426 * @since 1.20
427 *
428 * @param array $values
429 * @param array $conditions
430 *
431 * @return boolean Success indicator
432 */
433 public function update( array $values, array $conditions = array() ) {
434 $dbw = wfGetDB( DB_MASTER );
435
436 return $dbw->update(
437 $this->getName(),
438 $this->getPrefixedValues( $values ),
439 $this->getPrefixedValues( $conditions ),
440 __METHOD__
441 ) !== false; // DatabaseBase::update does not always return true for success as documented...
442 }
443
444 /**
445 * Computes the values of the summary fields of the objects matching the provided conditions.
446 *
447 * @since 1.20
448 *
449 * @param array|string|null $summaryFields
450 * @param array $conditions
451 */
452 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
453 $this->setReadDb( DB_MASTER );
454
455 /**
456 * @var IORMRow $item
457 */
458 foreach ( $this->select( null, $conditions ) as $item ) {
459 $item->loadSummaryFields( $summaryFields );
460 $item->setSummaryMode( true );
461 $item->save();
462 }
463
464 $this->setReadDb( DB_SLAVE );
465 }
466
467 /**
468 * Takes in an associative array with field names as keys and
469 * their values as value. The field names are prefixed with the
470 * db field prefix.
471 *
472 * @since 1.20
473 *
474 * @param array $values
475 *
476 * @return array
477 */
478 public function getPrefixedValues( array $values ) {
479 $prefixedValues = array();
480
481 foreach ( $values as $field => $value ) {
482 if ( is_integer( $field ) ) {
483 if ( is_array( $value ) ) {
484 $field = $value[0];
485 $value = $value[1];
486 }
487 else {
488 $value = explode( ' ', $value, 2 );
489 $value[0] = $this->getPrefixedField( $value[0] );
490 $prefixedValues[] = implode( ' ', $value );
491 continue;
492 }
493 }
494
495 $prefixedValues[$this->getPrefixedField( $field )] = $value;
496 }
497
498 return $prefixedValues;
499 }
500
501 /**
502 * Takes in a field or array of fields and returns an
503 * array with their prefixed versions, ready for db usage.
504 *
505 * @since 1.20
506 *
507 * @param array|string $fields
508 *
509 * @return array
510 */
511 public function getPrefixedFields( array $fields ) {
512 foreach ( $fields as &$field ) {
513 $field = $this->getPrefixedField( $field );
514 }
515
516 return $fields;
517 }
518
519 /**
520 * Takes in a field and returns an it's prefixed version, ready for db usage.
521 *
522 * @since 1.20
523 *
524 * @param string|array $field
525 *
526 * @return string
527 */
528 public function getPrefixedField( $field ) {
529 return $this->getFieldPrefix() . $field;
530 }
531
532 /**
533 * Takes an array of field names with prefix and returns the unprefixed equivalent.
534 *
535 * @since 1.20
536 *
537 * @param array $fieldNames
538 *
539 * @return array
540 */
541 public function unprefixFieldNames( array $fieldNames ) {
542 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
543 }
544
545 /**
546 * Takes a field name with prefix and returns the unprefixed equivalent.
547 *
548 * @since 1.20
549 *
550 * @param string $fieldName
551 *
552 * @return string
553 */
554 public function unprefixFieldName( $fieldName ) {
555 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
556 }
557
558 /**
559 * Get an instance of this class.
560 *
561 * @since 1.20
562 *
563 * @return IORMTable
564 */
565 public static function singleton() {
566 $class = get_called_class();
567
568 if ( !array_key_exists( $class, self::$instanceCache ) ) {
569 self::$instanceCache[$class] = new $class;
570 }
571
572 return self::$instanceCache[$class];
573 }
574
575 /**
576 * Get an array with fields from a database result,
577 * that can be fed directly to the constructor or
578 * to setFields.
579 *
580 * @since 1.20
581 *
582 * @param stdClass $result
583 *
584 * @return array
585 */
586 public function getFieldsFromDBResult( stdClass $result ) {
587 $result = (array)$result;
588 return array_combine(
589 $this->unprefixFieldNames( array_keys( $result ) ),
590 array_values( $result )
591 );
592 }
593
594 /**
595 * @see ORMTable::newRowFromFromDBResult
596 *
597 * @deprecated use newRowFromDBResult instead
598 * @since 1.20
599 *
600 * @param stdClass $result
601 *
602 * @return IORMRow
603 */
604 public function newFromDBResult( stdClass $result ) {
605 return self::newRowFromDBResult( $result );
606 }
607
608 /**
609 * Get a new instance of the class from a database result.
610 *
611 * @since 1.20
612 *
613 * @param stdClass $result
614 *
615 * @return IORMRow
616 */
617 public function newRowFromDBResult( stdClass $result ) {
618 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
619 }
620
621 /**
622 * @see ORMTable::newRow
623 *
624 * @deprecated use newRow instead
625 * @since 1.20
626 *
627 * @param array $data
628 * @param boolean $loadDefaults
629 *
630 * @return IORMRow
631 */
632 public function newFromArray( array $data, $loadDefaults = false ) {
633 return static::newRow( $data, $loadDefaults );
634 }
635
636 /**
637 * Get a new instance of the class from an array.
638 *
639 * @since 1.20
640 *
641 * @param array $data
642 * @param boolean $loadDefaults
643 *
644 * @return IORMRow
645 */
646 public function newRow( array $data, $loadDefaults = false ) {
647 $class = $this->getRowClass();
648 return new $class( $this, $data, $loadDefaults );
649 }
650
651 /**
652 * Return the names of the fields.
653 *
654 * @since 1.20
655 *
656 * @return array
657 */
658 public function getFieldNames() {
659 return array_keys( $this->getFields() );
660 }
661
662 /**
663 * Gets if the object can take a certain field.
664 *
665 * @since 1.20
666 *
667 * @param string $name
668 *
669 * @return boolean
670 */
671 public function canHaveField( $name ) {
672 return array_key_exists( $name, $this->getFields() );
673 }
674
675 }