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