Merge "ORM: pass some __METHOD__ to database functions"
[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 * @license GNU GPL v2 or later
27 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
28 */
29
30 abstract class ORMTable extends DBAccessBase 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 * ID of 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 $dbr = $this->getReadDbConnection();
149 $result = $dbr->select(
150 $this->getName(),
151 $this->getPrefixedFields( $fields ),
152 $this->getPrefixedValues( $conditions ),
153 is_null( $functionName ) ? __METHOD__ : $functionName,
154 $options
155 );
156
157 $this->releaseConnection( $dbr );
158 return $result;
159 }
160
161 /**
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.
166 *
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.
172 *
173 * @since 1.20
174 *
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
180 *
181 * @return array of array
182 */
183 public function selectFields( $fields = null, array $conditions = array(),
184 array $options = array(), $collapse = true, $functionName = null ) {
185 $objects = array();
186
187 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
188
189 foreach ( $result as $record ) {
190 $objects[] = $this->getFieldsFromDBResult( $record );
191 }
192
193 if ( $collapse ) {
194 if ( count( $fields ) === 1 ) {
195 $objects = array_map( 'array_shift', $objects );
196 }
197 elseif ( count( $fields ) === 2 ) {
198 $o = array();
199
200 foreach ( $objects as $object ) {
201 $o[array_shift( $object )] = array_shift( $object );
202 }
203
204 $objects = $o;
205 }
206 }
207
208 return $objects;
209 }
210
211 /**
212 * Selects the the specified fields of the first matching record.
213 * Field names get prefixed.
214 *
215 * @since 1.20
216 *
217 * @param array|string|null $fields
218 * @param array $conditions
219 * @param array $options
220 * @param string|null $functionName
221 *
222 * @return IORMRow|bool False on failure
223 */
224 public function selectRow( $fields = null, array $conditions = array(),
225 array $options = array(), $functionName = null ) {
226 $options['LIMIT'] = 1;
227
228 $objects = $this->select( $fields, $conditions, $options, $functionName );
229
230 return $objects->isEmpty() ? false : $objects->current();
231 }
232
233 /**
234 * Selects the the specified fields of the records matching the provided
235 * conditions. Field names do NOT get prefixed.
236 *
237 * @since 1.20
238 *
239 * @param array $fields
240 * @param array $conditions
241 * @param array $options
242 * @param string|null $functionName
243 *
244 * @return ResultWrapper
245 */
246 public function rawSelectRow( array $fields, array $conditions = array(),
247 array $options = array(), $functionName = null ) {
248 $dbr = $this->getReadDbConnection();
249
250 $result = $dbr->selectRow(
251 $this->getName(),
252 $fields,
253 $conditions,
254 is_null( $functionName ) ? __METHOD__ : $functionName,
255 $options
256 );
257
258 $this->releaseConnection( $dbr );
259 return $result;
260 }
261
262 /**
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
268 *
269 * @since 1.20
270 *
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
276 *
277 * @return mixed|array|bool False on failure
278 */
279 public function selectFieldsRow( $fields = null, array $conditions = array(),
280 array $options = array(), $collapse = true, $functionName = null ) {
281 $options['LIMIT'] = 1;
282
283 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
284
285 return empty( $objects ) ? false : $objects[0];
286 }
287
288 /**
289 * Returns if there is at least one record matching the provided conditions.
290 * Condition field names get prefixed.
291 *
292 * @since 1.20
293 *
294 * @param array $conditions
295 *
296 * @return boolean
297 */
298 public function has( array $conditions = array() ) {
299 return $this->selectRow( array( 'id' ), $conditions ) !== false;
300 }
301
302 /**
303 * Checks if the table exists
304 *
305 * @since 1.21
306 *
307 * @return boolean
308 */
309 public function exists() {
310 $dbr = $this->getReadDbConnection();
311 $exists = $dbr->tableExists( $this->getName() );
312 $this->releaseConnection( $dbr );
313
314 return $exists;
315 }
316
317 /**
318 * Returns the amount of matching records.
319 * Condition field names get prefixed.
320 *
321 * Note that this can be expensive on large tables.
322 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
323 *
324 * @since 1.20
325 *
326 * @param array $conditions
327 * @param array $options
328 *
329 * @return integer
330 */
331 public function count( array $conditions = array(), array $options = array() ) {
332 $res = $this->rawSelectRow(
333 array( 'rowcount' => 'COUNT(*)' ),
334 $this->getPrefixedValues( $conditions ),
335 $options,
336 __METHOD__
337 );
338
339 return $res->rowcount;
340 }
341
342 /**
343 * Removes the object from the database.
344 *
345 * @since 1.20
346 *
347 * @param array $conditions
348 * @param string|null $functionName
349 *
350 * @return boolean Success indicator
351 */
352 public function delete( array $conditions, $functionName = null ) {
353 $dbw = $this->getWriteDbConnection();
354
355 $result = $dbw->delete(
356 $this->getName(),
357 $conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
358 is_null( $functionName ) ? __METHOD__ : $functionName
359 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
360
361 $this->releaseConnection( $dbw );
362 return $result;
363 }
364
365 /**
366 * Get API parameters for the fields supported by this object.
367 *
368 * @since 1.20
369 *
370 * @param boolean $requireParams
371 * @param boolean $setDefaults
372 *
373 * @return array
374 */
375 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
376 $typeMap = array(
377 'id' => 'integer',
378 'int' => 'integer',
379 'float' => 'NULL',
380 'str' => 'string',
381 'bool' => 'integer',
382 'array' => 'string',
383 'blob' => 'string',
384 );
385
386 $params = array();
387 $defaults = $this->getDefaults();
388
389 foreach ( $this->getFields() as $field => $type ) {
390 if ( $field == 'id' ) {
391 continue;
392 }
393
394 $hasDefault = array_key_exists( $field, $defaults );
395
396 $params[$field] = array(
397 ApiBase::PARAM_TYPE => $typeMap[$type],
398 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
399 );
400
401 if ( $type == 'array' ) {
402 $params[$field][ApiBase::PARAM_ISMULTI] = true;
403 }
404
405 if ( $setDefaults && $hasDefault ) {
406 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
407 $params[$field][ApiBase::PARAM_DFLT] = $default;
408 }
409 }
410
411 return $params;
412 }
413
414 /**
415 * Returns an array with the fields and their descriptions.
416 *
417 * field name => field description
418 *
419 * @since 1.20
420 *
421 * @return array
422 */
423 public function getFieldDescriptions() {
424 return array();
425 }
426
427 /**
428 * Get the database ID used for read operations.
429 *
430 * @since 1.20
431 *
432 * @return integer DB_ enum
433 */
434 public function getReadDb() {
435 return $this->readDb;
436 }
437
438 /**
439 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
440 *
441 * @param integer $db
442 *
443 * @since 1.20
444 */
445 public function setReadDb( $db ) {
446 $this->readDb = $db;
447 }
448
449 /**
450 * Get the ID of the any foreign wiki to use as a target for database operations
451 *
452 * @since 1.20
453 *
454 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
455 */
456 public function getTargetWiki() {
457 return $this->wiki;
458 }
459
460 /**
461 * Set the ID of the any foreign wiki to use as a target for database operations
462 *
463 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
464 *
465 * @since 1.20
466 */
467 public function setTargetWiki( $wiki ) {
468 $this->wiki = $wiki;
469 }
470
471 /**
472 * Get the database type used for read operations.
473 * This is to be used instead of wfGetDB.
474 *
475 * @see LoadBalancer::getConnection
476 *
477 * @since 1.20
478 *
479 * @return DatabaseBase The database object
480 */
481 public function getReadDbConnection() {
482 return $this->getConnection( $this->getReadDb(), array() );
483 }
484
485 /**
486 * Get the database type used for read operations.
487 * This is to be used instead of wfGetDB.
488 *
489 * @see LoadBalancer::getConnection
490 *
491 * @since 1.20
492 *
493 * @return DatabaseBase The database object
494 */
495 public function getWriteDbConnection() {
496 return $this->getConnection( DB_MASTER, array() );
497 }
498
499 /**
500 * Releases the lease on the given database connection. This is useful mainly
501 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
502 *
503 * @see LoadBalancer::reuseConnection
504 *
505 * @param DatabaseBase $db the database
506 *
507 * @since 1.20
508 */
509 public function releaseConnection( DatabaseBase $db ) {
510 parent::releaseConnection( $db ); // just make it public
511 }
512
513 /**
514 * Update the records matching the provided conditions by
515 * setting the fields that are keys in the $values param to
516 * their corresponding values.
517 *
518 * @since 1.20
519 *
520 * @param array $values
521 * @param array $conditions
522 *
523 * @return boolean Success indicator
524 */
525 public function update( array $values, array $conditions = array() ) {
526 $dbw = $this->getWriteDbConnection();
527
528 $result = $dbw->update(
529 $this->getName(),
530 $this->getPrefixedValues( $values ),
531 $this->getPrefixedValues( $conditions ),
532 __METHOD__
533 ) !== false; // DatabaseBase::update does not always return true for success as documented...
534
535 $this->releaseConnection( $dbw );
536 return $result;
537 }
538
539 /**
540 * Computes the values of the summary fields of the objects matching the provided conditions.
541 *
542 * @since 1.20
543 *
544 * @param array|string|null $summaryFields
545 * @param array $conditions
546 */
547 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
548 $slave = $this->getReadDb();
549 $this->setReadDb( DB_MASTER );
550
551 /**
552 * @var IORMRow $item
553 */
554 foreach ( $this->select( null, $conditions ) as $item ) {
555 $item->loadSummaryFields( $summaryFields );
556 $item->setSummaryMode( true );
557 $item->save();
558 }
559
560 $this->setReadDb( $slave );
561 }
562
563 /**
564 * Takes in an associative array with field names as keys and
565 * their values as value. The field names are prefixed with the
566 * db field prefix.
567 *
568 * @since 1.20
569 *
570 * @param array $values
571 *
572 * @return array
573 */
574 public function getPrefixedValues( array $values ) {
575 $prefixedValues = array();
576
577 foreach ( $values as $field => $value ) {
578 if ( is_integer( $field ) ) {
579 if ( is_array( $value ) ) {
580 $field = $value[0];
581 $value = $value[1];
582 }
583 else {
584 $value = explode( ' ', $value, 2 );
585 $value[0] = $this->getPrefixedField( $value[0] );
586 $prefixedValues[] = implode( ' ', $value );
587 continue;
588 }
589 }
590
591 $prefixedValues[$this->getPrefixedField( $field )] = $value;
592 }
593
594 return $prefixedValues;
595 }
596
597 /**
598 * Takes in a field or array of fields and returns an
599 * array with their prefixed versions, ready for db usage.
600 *
601 * @since 1.20
602 *
603 * @param array|string $fields
604 *
605 * @return array
606 */
607 public function getPrefixedFields( array $fields ) {
608 foreach ( $fields as &$field ) {
609 $field = $this->getPrefixedField( $field );
610 }
611
612 return $fields;
613 }
614
615 /**
616 * Takes in a field and returns an it's prefixed version, ready for db usage.
617 *
618 * @since 1.20
619 *
620 * @param string|array $field
621 *
622 * @return string
623 */
624 public function getPrefixedField( $field ) {
625 return $this->getFieldPrefix() . $field;
626 }
627
628 /**
629 * Takes an array of field names with prefix and returns the unprefixed equivalent.
630 *
631 * @since 1.20
632 *
633 * @param array $fieldNames
634 *
635 * @return array
636 */
637 public function unprefixFieldNames( array $fieldNames ) {
638 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
639 }
640
641 /**
642 * Takes a field name with prefix and returns the unprefixed equivalent.
643 *
644 * @since 1.20
645 *
646 * @param string $fieldName
647 *
648 * @return string
649 */
650 public function unprefixFieldName( $fieldName ) {
651 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
652 }
653
654 /**
655 * Get an instance of this class.
656 *
657 * @since 1.20
658 *
659 * @return IORMTable
660 */
661 public static function singleton() {
662 $class = get_called_class();
663
664 if ( !array_key_exists( $class, self::$instanceCache ) ) {
665 self::$instanceCache[$class] = new $class;
666 }
667
668 return self::$instanceCache[$class];
669 }
670
671 /**
672 * Get an array with fields from a database result,
673 * that can be fed directly to the constructor or
674 * to setFields.
675 *
676 * @since 1.20
677 *
678 * @param stdClass $result
679 *
680 * @return array
681 */
682 public function getFieldsFromDBResult( stdClass $result ) {
683 $result = (array)$result;
684 return array_combine(
685 $this->unprefixFieldNames( array_keys( $result ) ),
686 array_values( $result )
687 );
688 }
689
690 /**
691 * @see ORMTable::newRowFromFromDBResult
692 *
693 * @deprecated use newRowFromDBResult instead
694 * @since 1.20
695 *
696 * @param stdClass $result
697 *
698 * @return IORMRow
699 */
700 public function newFromDBResult( stdClass $result ) {
701 return self::newRowFromDBResult( $result );
702 }
703
704 /**
705 * Get a new instance of the class from a database result.
706 *
707 * @since 1.20
708 *
709 * @param stdClass $result
710 *
711 * @return IORMRow
712 */
713 public function newRowFromDBResult( stdClass $result ) {
714 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
715 }
716
717 /**
718 * @see ORMTable::newRow
719 *
720 * @deprecated use newRow instead
721 * @since 1.20
722 *
723 * @param array $data
724 * @param boolean $loadDefaults
725 *
726 * @return IORMRow
727 */
728 public function newFromArray( array $data, $loadDefaults = false ) {
729 return static::newRow( $data, $loadDefaults );
730 }
731
732 /**
733 * Get a new instance of the class from an array.
734 *
735 * @since 1.20
736 *
737 * @param array $data
738 * @param boolean $loadDefaults
739 *
740 * @return IORMRow
741 */
742 public function newRow( array $data, $loadDefaults = false ) {
743 $class = $this->getRowClass();
744 return new $class( $this, $data, $loadDefaults );
745 }
746
747 /**
748 * Return the names of the fields.
749 *
750 * @since 1.20
751 *
752 * @return array
753 */
754 public function getFieldNames() {
755 return array_keys( $this->getFields() );
756 }
757
758 /**
759 * Gets if the object can take a certain field.
760 *
761 * @since 1.20
762 *
763 * @param string $name
764 *
765 * @return boolean
766 */
767 public function canHaveField( $name ) {
768 return array_key_exists( $name, $this->getFields() );
769 }
770
771 }