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