Merge "AJAXify watchlist editor"
[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( 'COUNT(*) AS rowcount' ),
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 $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 foreach ( $this->select( null, $conditions ) as /* IORMRow */ $item ) {
456 $item->loadSummaryFields( $summaryFields );
457 $item->setSummaryMode( true );
458 $item->save();
459 }
460
461 $this->setReadDb( DB_SLAVE );
462 }
463
464 /**
465 * Takes in an associative array with field names as keys and
466 * their values as value. The field names are prefixed with the
467 * db field prefix.
468 *
469 * @since 1.20
470 *
471 * @param array $values
472 *
473 * @return array
474 */
475 public function getPrefixedValues( array $values ) {
476 $prefixedValues = array();
477
478 foreach ( $values as $field => $value ) {
479 if ( is_integer( $field ) ) {
480 if ( is_array( $value ) ) {
481 $field = $value[0];
482 $value = $value[1];
483 }
484 else {
485 $value = explode( ' ', $value, 2 );
486 $value[0] = $this->getPrefixedField( $value[0] );
487 $prefixedValues[] = implode( ' ', $value );
488 continue;
489 }
490 }
491
492 $prefixedValues[$this->getPrefixedField( $field )] = $value;
493 }
494
495 return $prefixedValues;
496 }
497
498 /**
499 * Takes in a field or array of fields and returns an
500 * array with their prefixed versions, ready for db usage.
501 *
502 * @since 1.20
503 *
504 * @param array|string $fields
505 *
506 * @return array
507 */
508 public function getPrefixedFields( array $fields ) {
509 foreach ( $fields as &$field ) {
510 $field = $this->getPrefixedField( $field );
511 }
512
513 return $fields;
514 }
515
516 /**
517 * Takes in a field and returns an it's prefixed version, ready for db usage.
518 *
519 * @since 1.20
520 *
521 * @param string|array $field
522 *
523 * @return string
524 */
525 public function getPrefixedField( $field ) {
526 return $this->getFieldPrefix() . $field;
527 }
528
529 /**
530 * Takes an array of field names with prefix and returns the unprefixed equivalent.
531 *
532 * @since 1.20
533 *
534 * @param array $fieldNames
535 *
536 * @return array
537 */
538 public function unprefixFieldNames( array $fieldNames ) {
539 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
540 }
541
542 /**
543 * Takes a field name with prefix and returns the unprefixed equivalent.
544 *
545 * @since 1.20
546 *
547 * @param string $fieldName
548 *
549 * @return string
550 */
551 public function unprefixFieldName( $fieldName ) {
552 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
553 }
554
555 /**
556 * Get an instance of this class.
557 *
558 * @since 1.20
559 *
560 * @return IORMTable
561 */
562 public static function singleton() {
563 $class = get_called_class();
564
565 if ( !array_key_exists( $class, self::$instanceCache ) ) {
566 self::$instanceCache[$class] = new $class;
567 }
568
569 return self::$instanceCache[$class];
570 }
571
572 /**
573 * Get an array with fields from a database result,
574 * that can be fed directly to the constructor or
575 * to setFields.
576 *
577 * @since 1.20
578 *
579 * @param stdClass $result
580 *
581 * @return array
582 */
583 public function getFieldsFromDBResult( stdClass $result ) {
584 $result = (array)$result;
585 return array_combine(
586 $this->unprefixFieldNames( array_keys( $result ) ),
587 array_values( $result )
588 );
589 }
590
591 /**
592 * @see ORMTable::newRowFromFromDBResult
593 *
594 * @deprecated use newRowFromDBResult instead
595 * @since 1.20
596 *
597 * @param stdClass $result
598 *
599 * @return IORMRow
600 */
601 public function newFromDBResult( stdClass $result ) {
602 return self::newRowFromDBResult( $result );
603 }
604
605 /**
606 * Get a new instance of the class from a database result.
607 *
608 * @since 1.20
609 *
610 * @param stdClass $result
611 *
612 * @return IORMRow
613 */
614 public function newRowFromDBResult( stdClass $result ) {
615 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
616 }
617
618 /**
619 * @see ORMTable::newRow
620 *
621 * @deprecated use newRow instead
622 * @since 1.20
623 *
624 * @param array $data
625 * @param boolean $loadDefaults
626 *
627 * @return IORMRow
628 */
629 public function newFromArray( array $data, $loadDefaults = false ) {
630 return static::newRow( $data, $loadDefaults );
631 }
632
633 /**
634 * Get a new instance of the class from an array.
635 *
636 * @since 1.20
637 *
638 * @param array $data
639 * @param boolean $loadDefaults
640 *
641 * @return IORMRow
642 */
643 public function newRow( array $data, $loadDefaults = false ) {
644 $class = $this->getRowClass();
645 return new $class( $this, $data, $loadDefaults );
646 }
647
648 /**
649 * Return the names of the fields.
650 *
651 * @since 1.20
652 *
653 * @return array
654 */
655 public function getFieldNames() {
656 return array_keys( $this->getFields() );
657 }
658
659 /**
660 * Gets if the object can take a certain field.
661 *
662 * @since 1.20
663 *
664 * @param string $name
665 *
666 * @return boolean
667 */
668 public function canHaveField( $name ) {
669 return array_key_exists( $name, $this->getFields() );
670 }
671
672 }