Merge "(Bug 38439) Attempt on fixing the suicidal LangObjCache"
[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 );
337
338 return $res->rowcount;
339 }
340
341 /**
342 * Removes the object from the database.
343 *
344 * @since 1.20
345 *
346 * @param array $conditions
347 * @param string|null $functionName
348 *
349 * @return boolean Success indicator
350 */
351 public function delete( array $conditions, $functionName = null ) {
352 $dbw = $this->getWriteDbConnection();
353
354 $result = $dbw->delete(
355 $this->getName(),
356 $conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
357 $functionName
358 ) !== false; // DatabaseBase::delete does not always return true for success as documented...
359
360 $this->releaseConnection( $dbw );
361 return $result;
362 }
363
364 /**
365 * Get API parameters for the fields supported by this object.
366 *
367 * @since 1.20
368 *
369 * @param boolean $requireParams
370 * @param boolean $setDefaults
371 *
372 * @return array
373 */
374 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
375 $typeMap = array(
376 'id' => 'integer',
377 'int' => 'integer',
378 'float' => 'NULL',
379 'str' => 'string',
380 'bool' => 'integer',
381 'array' => 'string',
382 'blob' => 'string',
383 );
384
385 $params = array();
386 $defaults = $this->getDefaults();
387
388 foreach ( $this->getFields() as $field => $type ) {
389 if ( $field == 'id' ) {
390 continue;
391 }
392
393 $hasDefault = array_key_exists( $field, $defaults );
394
395 $params[$field] = array(
396 ApiBase::PARAM_TYPE => $typeMap[$type],
397 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
398 );
399
400 if ( $type == 'array' ) {
401 $params[$field][ApiBase::PARAM_ISMULTI] = true;
402 }
403
404 if ( $setDefaults && $hasDefault ) {
405 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
406 $params[$field][ApiBase::PARAM_DFLT] = $default;
407 }
408 }
409
410 return $params;
411 }
412
413 /**
414 * Returns an array with the fields and their descriptions.
415 *
416 * field name => field description
417 *
418 * @since 1.20
419 *
420 * @return array
421 */
422 public function getFieldDescriptions() {
423 return array();
424 }
425
426 /**
427 * Get the database ID used for read operations.
428 *
429 * @since 1.20
430 *
431 * @return integer DB_ enum
432 */
433 public function getReadDb() {
434 return $this->readDb;
435 }
436
437 /**
438 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
439 *
440 * @param integer $db
441 *
442 * @since 1.20
443 */
444 public function setReadDb( $db ) {
445 $this->readDb = $db;
446 }
447
448 /**
449 * Get the ID of the any foreign wiki to use as a target for database operations
450 *
451 * @since 1.20
452 *
453 * @return String|bool The target wiki, in a form that LBFactory understands (or false if the local wiki is used)
454 */
455 public function getTargetWiki() {
456 return $this->wiki;
457 }
458
459 /**
460 * Set the ID of the any foreign wiki to use as a target for database operations
461 *
462 * @param String|bool $wiki The target wiki, in a form that LBFactory understands (or false if the local wiki shall be used)
463 *
464 * @since 1.20
465 */
466 public function setTargetWiki( $wiki ) {
467 $this->wiki = $wiki;
468 }
469
470 /**
471 * Get the database type used for read operations.
472 * This is to be used instead of wfGetDB.
473 *
474 * @see LoadBalancer::getConnection
475 *
476 * @since 1.20
477 *
478 * @return DatabaseBase The database object
479 */
480 public function getReadDbConnection() {
481 return $this->getConnection( $this->getReadDb(), array() );
482 }
483
484 /**
485 * Get the database type used for read operations.
486 * This is to be used instead of wfGetDB.
487 *
488 * @see LoadBalancer::getConnection
489 *
490 * @since 1.20
491 *
492 * @return DatabaseBase The database object
493 */
494 public function getWriteDbConnection() {
495 return $this->getConnection( DB_MASTER, array() );
496 }
497
498 /**
499 * Releases the lease on the given database connection. This is useful mainly
500 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
501 *
502 * @see LoadBalancer::reuseConnection
503 *
504 * @param DatabaseBase $db the database
505 *
506 * @since 1.20
507 */
508 public function releaseConnection( DatabaseBase $db ) {
509 parent::releaseConnection( $db ); // just make it public
510 }
511
512 /**
513 * Update the records matching the provided conditions by
514 * setting the fields that are keys in the $values param to
515 * their corresponding values.
516 *
517 * @since 1.20
518 *
519 * @param array $values
520 * @param array $conditions
521 *
522 * @return boolean Success indicator
523 */
524 public function update( array $values, array $conditions = array() ) {
525 $dbw = $this->getWriteDbConnection();
526
527 $result = $dbw->update(
528 $this->getName(),
529 $this->getPrefixedValues( $values ),
530 $this->getPrefixedValues( $conditions ),
531 __METHOD__
532 ) !== false; // DatabaseBase::update does not always return true for success as documented...
533
534 $this->releaseConnection( $dbw );
535 return $result;
536 }
537
538 /**
539 * Computes the values of the summary fields of the objects matching the provided conditions.
540 *
541 * @since 1.20
542 *
543 * @param array|string|null $summaryFields
544 * @param array $conditions
545 */
546 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
547 $slave = $this->getReadDb();
548 $this->setReadDb( DB_MASTER );
549
550 /**
551 * @var IORMRow $item
552 */
553 foreach ( $this->select( null, $conditions ) as $item ) {
554 $item->loadSummaryFields( $summaryFields );
555 $item->setSummaryMode( true );
556 $item->save();
557 }
558
559 $this->setReadDb( $slave );
560 }
561
562 /**
563 * Takes in an associative array with field names as keys and
564 * their values as value. The field names are prefixed with the
565 * db field prefix.
566 *
567 * @since 1.20
568 *
569 * @param array $values
570 *
571 * @return array
572 */
573 public function getPrefixedValues( array $values ) {
574 $prefixedValues = array();
575
576 foreach ( $values as $field => $value ) {
577 if ( is_integer( $field ) ) {
578 if ( is_array( $value ) ) {
579 $field = $value[0];
580 $value = $value[1];
581 }
582 else {
583 $value = explode( ' ', $value, 2 );
584 $value[0] = $this->getPrefixedField( $value[0] );
585 $prefixedValues[] = implode( ' ', $value );
586 continue;
587 }
588 }
589
590 $prefixedValues[$this->getPrefixedField( $field )] = $value;
591 }
592
593 return $prefixedValues;
594 }
595
596 /**
597 * Takes in a field or array of fields and returns an
598 * array with their prefixed versions, ready for db usage.
599 *
600 * @since 1.20
601 *
602 * @param array|string $fields
603 *
604 * @return array
605 */
606 public function getPrefixedFields( array $fields ) {
607 foreach ( $fields as &$field ) {
608 $field = $this->getPrefixedField( $field );
609 }
610
611 return $fields;
612 }
613
614 /**
615 * Takes in a field and returns an it's prefixed version, ready for db usage.
616 *
617 * @since 1.20
618 *
619 * @param string|array $field
620 *
621 * @return string
622 */
623 public function getPrefixedField( $field ) {
624 return $this->getFieldPrefix() . $field;
625 }
626
627 /**
628 * Takes an array of field names with prefix and returns the unprefixed equivalent.
629 *
630 * @since 1.20
631 *
632 * @param array $fieldNames
633 *
634 * @return array
635 */
636 public function unprefixFieldNames( array $fieldNames ) {
637 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
638 }
639
640 /**
641 * Takes a field name with prefix and returns the unprefixed equivalent.
642 *
643 * @since 1.20
644 *
645 * @param string $fieldName
646 *
647 * @return string
648 */
649 public function unprefixFieldName( $fieldName ) {
650 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
651 }
652
653 /**
654 * Get an instance of this class.
655 *
656 * @since 1.20
657 *
658 * @return IORMTable
659 */
660 public static function singleton() {
661 $class = get_called_class();
662
663 if ( !array_key_exists( $class, self::$instanceCache ) ) {
664 self::$instanceCache[$class] = new $class;
665 }
666
667 return self::$instanceCache[$class];
668 }
669
670 /**
671 * Get an array with fields from a database result,
672 * that can be fed directly to the constructor or
673 * to setFields.
674 *
675 * @since 1.20
676 *
677 * @param stdClass $result
678 *
679 * @return array
680 */
681 public function getFieldsFromDBResult( stdClass $result ) {
682 $result = (array)$result;
683 return array_combine(
684 $this->unprefixFieldNames( array_keys( $result ) ),
685 array_values( $result )
686 );
687 }
688
689 /**
690 * @see ORMTable::newRowFromFromDBResult
691 *
692 * @deprecated use newRowFromDBResult instead
693 * @since 1.20
694 *
695 * @param stdClass $result
696 *
697 * @return IORMRow
698 */
699 public function newFromDBResult( stdClass $result ) {
700 return self::newRowFromDBResult( $result );
701 }
702
703 /**
704 * Get a new instance of the class from a database result.
705 *
706 * @since 1.20
707 *
708 * @param stdClass $result
709 *
710 * @return IORMRow
711 */
712 public function newRowFromDBResult( stdClass $result ) {
713 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
714 }
715
716 /**
717 * @see ORMTable::newRow
718 *
719 * @deprecated use newRow instead
720 * @since 1.20
721 *
722 * @param array $data
723 * @param boolean $loadDefaults
724 *
725 * @return IORMRow
726 */
727 public function newFromArray( array $data, $loadDefaults = false ) {
728 return static::newRow( $data, $loadDefaults );
729 }
730
731 /**
732 * Get a new instance of the class from an array.
733 *
734 * @since 1.20
735 *
736 * @param array $data
737 * @param boolean $loadDefaults
738 *
739 * @return IORMRow
740 */
741 public function newRow( array $data, $loadDefaults = false ) {
742 $class = $this->getRowClass();
743 return new $class( $this, $data, $loadDefaults );
744 }
745
746 /**
747 * Return the names of the fields.
748 *
749 * @since 1.20
750 *
751 * @return array
752 */
753 public function getFieldNames() {
754 return array_keys( $this->getFields() );
755 }
756
757 /**
758 * Gets if the object can take a certain field.
759 *
760 * @since 1.20
761 *
762 * @param string $name
763 *
764 * @return boolean
765 */
766 public function canHaveField( $name ) {
767 return array_key_exists( $name, $this->getFields() );
768 }
769
770 }