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