651eadd5c3579097dc801a39a5ffc0aa78aed3b6
[lhc/web/wiklou.git] / includes / db / ORMTable.php
1 <?php
2
3 /**
4 * Abstract base class for representing a single database table.
5 *
6 * @since 1.20
7 *
8 * @file ORMTable.php
9 *
10 * @licence GNU GPL v2 or later
11 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
12 */
13 abstract class ORMTable {
14
15 /**
16 * Returns the name of the database table objects of this type are stored in.
17 *
18 * @since 1.20
19 *
20 * @return string
21 */
22 public abstract function getName();
23
24 /**
25 * Returns the name of a ORMRow deriving class that
26 * represents single rows in this table.
27 *
28 * @since 1.20
29 *
30 * @return string
31 */
32 public abstract function getRowClass();
33
34 /**
35 * Gets the db field prefix.
36 *
37 * @since 1.20
38 *
39 * @return string
40 */
41 protected abstract function getFieldPrefix();
42
43 /**
44 * Returns an array with the fields and their types this object contains.
45 * This corresponds directly to the fields in the database, without prefix.
46 *
47 * field name => type
48 *
49 * Allowed types:
50 * * id
51 * * str
52 * * int
53 * * float
54 * * bool
55 * * array
56 *
57 * @since 1.20
58 *
59 * @return array
60 */
61 public abstract function getFields();
62
63 /**
64 * Cache for instances, used by the singleton method.
65 *
66 * @since 1.20
67 * @var array of DBTable
68 */
69 protected static $instanceCache = array();
70
71 /**
72 * The database connection to use for read operations.
73 * Can be changed via @see setReadDb.
74 *
75 * @since 1.20
76 * @var integer DB_ enum
77 */
78 protected $readDb = DB_SLAVE;
79
80 /**
81 * Returns a list of default field values.
82 * field name => field value
83 *
84 * @since 1.20
85 *
86 * @return array
87 */
88 public function getDefaults() {
89 return array();
90 }
91
92 /**
93 * Returns a list of the summary fields.
94 * These are fields that cache computed values, such as the amount of linked objects of $type.
95 * This is relevant as one might not want to do actions such as log changes when these get updated.
96 *
97 * @since 1.20
98 *
99 * @return array
100 */
101 public function getSummaryFields() {
102 return array();
103 }
104
105 /**
106 * Selects the the specified fields of the records matching the provided
107 * conditions and returns them as DBDataObject. Field names get prefixed.
108 *
109 * @since 1.20
110 *
111 * @param array|string|null $fields
112 * @param array $conditions
113 * @param array $options
114 * @param string|null $functionName
115 *
116 * @return ORMResult
117 */
118 public function select( $fields = null, array $conditions = array(),
119 array $options = array(), $functionName = null ) {
120 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
121 }
122
123 /**
124 * Selects the the specified fields of the records matching the provided
125 * conditions and returns them as DBDataObject. Field names get prefixed.
126 *
127 * @since 1.20
128 *
129 * @param array|string|null $fields
130 * @param array $conditions
131 * @param array $options
132 * @param string|null $functionName
133 *
134 * @return array of self
135 */
136 public function selectObjects( $fields = null, array $conditions = array(),
137 array $options = array(), $functionName = null ) {
138 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
139
140 $objects = array();
141
142 foreach ( $result as $record ) {
143 $objects[] = $this->newFromArray( $record );
144 }
145
146 return $objects;
147 }
148
149 /**
150 * Do the actual select.
151 *
152 * @since 1.20
153 *
154 * @param null|string|array $fields
155 * @param array $conditions
156 * @param array $options
157 * @param null|string $functionName
158 *
159 * @return ResultWrapper
160 */
161 public function rawSelect( $fields = null, array $conditions = array(),
162 array $options = array(), $functionName = null ) {
163 if ( is_null( $fields ) ) {
164 $fields = array_keys( $this->getFields() );
165 }
166 else {
167 $fields = (array)$fields;
168 }
169
170 return wfGetDB( $this->getReadDb() )->select(
171 $this->getName(),
172 $this->getPrefixedFields( $fields ),
173 $this->getPrefixedValues( $conditions ),
174 is_null( $functionName ) ? __METHOD__ : $functionName,
175 $options
176 );
177 }
178
179 /**
180 * Selects the the specified fields of the records matching the provided
181 * conditions and returns them as associative arrays.
182 * Provided field names get prefixed.
183 * Returned field names will not have a prefix.
184 *
185 * When $collapse is true:
186 * If one field is selected, each item in the result array will be this field.
187 * If two fields are selected, each item in the result array will have as key
188 * the first field and as value the second field.
189 * If more then two fields are selected, each item will be an associative array.
190 *
191 * @since 1.20
192 *
193 * @param array|string|null $fields
194 * @param array $conditions
195 * @param array $options
196 * @param boolean $collapse Set to false to always return each result row as associative array.
197 * @param string|null $functionName
198 *
199 * @return array of array
200 */
201 public function selectFields( $fields = null, array $conditions = array(),
202 array $options = array(), $collapse = true, $functionName = null ) {
203 $objects = array();
204
205 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
206
207 foreach ( $result as $record ) {
208 $objects[] = $this->getFieldsFromDBResult( $record );
209 }
210
211 if ( $collapse ) {
212 if ( count( $fields ) === 1 ) {
213 $objects = array_map( 'array_shift', $objects );
214 }
215 elseif ( count( $fields ) === 2 ) {
216 $o = array();
217
218 foreach ( $objects as $object ) {
219 $o[array_shift( $object )] = array_shift( $object );
220 }
221
222 $objects = $o;
223 }
224 }
225
226 return $objects;
227 }
228
229 /**
230 * Selects the the specified fields of the first matching record.
231 * Field names get prefixed.
232 *
233 * @since 1.20
234 *
235 * @param array|string|null $fields
236 * @param array $conditions
237 * @param array $options
238 * @param string|null $functionName
239 *
240 * @return DBObject|bool False on failure
241 */
242 public function selectRow( $fields = null, array $conditions = array(),
243 array $options = array(), $functionName = null ) {
244 $options['LIMIT'] = 1;
245
246 $objects = $this->select( $fields, $conditions, $options, $functionName );
247
248 return $objects->isEmpty() ? false : $objects->current();
249 }
250
251 /**
252 * Selects the the specified fields of the records matching the provided
253 * conditions. Field names do NOT get prefixed.
254 *
255 * @since 1.20
256 *
257 * @param array $fields
258 * @param array $conditions
259 * @param array $options
260 * @param string|null $functionName
261 *
262 * @return ResultWrapper
263 */
264 public function rawSelectRow( array $fields, array $conditions = array(),
265 array $options = array(), $functionName = null ) {
266 $dbr = wfGetDB( $this->getReadDb() );
267
268 return $dbr->selectRow(
269 $this->getName(),
270 $fields,
271 $conditions,
272 is_null( $functionName ) ? __METHOD__ : $functionName,
273 $options
274 );
275 }
276
277 /**
278 * Selects the the specified fields of the first record matching the provided
279 * conditions and returns it as an associative array, or false when nothing matches.
280 * This method makes use of selectFields and expects the same parameters and
281 * returns the same results (if there are any, if there are none, this method returns false).
282 * @see ORMTable::selectFields
283 *
284 * @since 1.20
285 *
286 * @param array|string|null $fields
287 * @param array $conditions
288 * @param array $options
289 * @param boolean $collapse Set to false to always return each result row as associative array.
290 * @param string|null $functionName
291 *
292 * @return mixed|array|bool False on failure
293 */
294 public function selectFieldsRow( $fields = null, array $conditions = array(),
295 array $options = array(), $collapse = true, $functionName = null ) {
296 $options['LIMIT'] = 1;
297
298 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
299
300 return empty( $objects ) ? false : $objects[0];
301 }
302
303 /**
304 * Returns if there is at least one record matching the provided conditions.
305 * Condition field names get prefixed.
306 *
307 * @since 1.20
308 *
309 * @param array $conditions
310 *
311 * @return boolean
312 */
313 public function has( array $conditions = array() ) {
314 return $this->selectRow( array( 'id' ), $conditions ) !== false;
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( 'COUNT(*) AS rowcount' ),
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 return wfGetDB( DB_MASTER )->delete(
353 $this->getName(),
354 $this->getPrefixedValues( $conditions ),
355 $functionName
356 );
357 }
358
359 /**
360 * Get API parameters for the fields supported by this object.
361 *
362 * @since 1.20
363 *
364 * @param boolean $requireParams
365 * @param boolean $setDefaults
366 *
367 * @return array
368 */
369 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
370 $typeMap = array(
371 'id' => 'integer',
372 'int' => 'integer',
373 'float' => 'NULL',
374 'str' => 'string',
375 'bool' => 'integer',
376 'array' => 'string',
377 'blob' => 'string',
378 );
379
380 $params = array();
381 $defaults = $this->getDefaults();
382
383 foreach ( $this->getFields() as $field => $type ) {
384 if ( $field == 'id' ) {
385 continue;
386 }
387
388 $hasDefault = array_key_exists( $field, $defaults );
389
390 $params[$field] = array(
391 ApiBase::PARAM_TYPE => $typeMap[$type],
392 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
393 );
394
395 if ( $type == 'array' ) {
396 $params[$field][ApiBase::PARAM_ISMULTI] = true;
397 }
398
399 if ( $setDefaults && $hasDefault ) {
400 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
401 $params[$field][ApiBase::PARAM_DFLT] = $default;
402 }
403 }
404
405 return $params;
406 }
407
408 /**
409 * Returns an array with the fields and their descriptions.
410 *
411 * field name => field description
412 *
413 * @since 1.20
414 *
415 * @return array
416 */
417 public function getFieldDescriptions() {
418 return array();
419 }
420
421 /**
422 * Get the database type used for read operations.
423 *
424 * @since 1.20
425 *
426 * @return integer DB_ enum
427 */
428 public function getReadDb() {
429 return $this->readDb;
430 }
431
432 /**
433 * Set the database type to use for read operations.
434 *
435 * @param integer $db
436 *
437 * @since 1.20
438 */
439 public function setReadDb( $db ) {
440 $this->readDb = $db;
441 }
442
443 /**
444 * Update the records matching the provided conditions by
445 * setting the fields that are keys in the $values param to
446 * their corresponding values.
447 *
448 * @since 1.20
449 *
450 * @param array $values
451 * @param array $conditions
452 *
453 * @return boolean Success indicator
454 */
455 public function update( array $values, array $conditions = array() ) {
456 $dbw = wfGetDB( DB_MASTER );
457
458 return $dbw->update(
459 $this->getName(),
460 $this->getPrefixedValues( $values ),
461 $this->getPrefixedValues( $conditions ),
462 __METHOD__
463 );
464 }
465
466 /**
467 * Computes the values of the summary fields of the objects matching the provided conditions.
468 *
469 * @since 1.20
470 *
471 * @param array|string|null $summaryFields
472 * @param array $conditions
473 */
474 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
475 $this->setReadDb( DB_MASTER );
476
477 foreach ( $this->select( null, $conditions ) as /* ORMRow */ $item ) {
478 $item->loadSummaryFields( $summaryFields );
479 $item->setSummaryMode( true );
480 $item->save();
481 }
482
483 $this->setReadDb( DB_SLAVE );
484 }
485
486 /**
487 * Takes in an associative array with field names as keys and
488 * their values as value. The field names are prefixed with the
489 * db field prefix.
490 *
491 * Field names can also be provided as an array with as first element a table name, such as
492 * $conditions = array(
493 * array( array( 'tablename', 'fieldname' ), $value ),
494 * );
495 *
496 * @since 1.20
497 *
498 * @param array $values
499 *
500 * @return array
501 */
502 public function getPrefixedValues( array $values ) {
503 $prefixedValues = array();
504
505 foreach ( $values as $field => $value ) {
506 if ( is_integer( $field ) ) {
507 if ( is_array( $value ) ) {
508 $field = $value[0];
509 $value = $value[1];
510 }
511 else {
512 $value = explode( ' ', $value, 2 );
513 $value[0] = $this->getPrefixedField( $value[0] );
514 $prefixedValues[] = implode( ' ', $value );
515 continue;
516 }
517 }
518
519 $prefixedValues[$this->getPrefixedField( $field )] = $value;
520 }
521
522 return $prefixedValues;
523 }
524
525 /**
526 * Takes in a field or array of fields and returns an
527 * array with their prefixed versions, ready for db usage.
528 *
529 * @since 1.20
530 *
531 * @param array|string $fields
532 *
533 * @return array
534 */
535 public function getPrefixedFields( array $fields ) {
536 foreach ( $fields as &$field ) {
537 $field = $this->getPrefixedField( $field );
538 }
539
540 return $fields;
541 }
542
543 /**
544 * Takes in a field and returns an it's prefixed version, ready for db usage.
545 *
546 * @since 1.20
547 *
548 * @param string|array $field
549 *
550 * @return string
551 */
552 public function getPrefixedField( $field ) {
553 return $this->getFieldPrefix() . $field;
554 }
555
556 /**
557 * Takes an array of field names with prefix and returns the unprefixed equivalent.
558 *
559 * @since 1.20
560 *
561 * @param array $fieldNames
562 *
563 * @return array
564 */
565 public function unprefixFieldNames( array $fieldNames ) {
566 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
567 }
568
569 /**
570 * Takes a field name with prefix and returns the unprefixed equivalent.
571 *
572 * @since 1.20
573 *
574 * @param string $fieldName
575 *
576 * @return string
577 */
578 public function unprefixFieldName( $fieldName ) {
579 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
580 }
581
582 /**
583 * Get an instance of this class.
584 *
585 * @since 1.20
586 *
587 * @return ORMTable
588 */
589 public static function singleton() {
590 $class = function_exists( 'get_called_class' ) ? get_called_class() : self::get_called_class();
591
592 if ( !array_key_exists( $class, self::$instanceCache ) ) {
593 self::$instanceCache[$class] = new $class;
594 }
595
596 return self::$instanceCache[$class];
597 }
598
599 /**
600 * Compatibility fallback function so the singleton method works on PHP < 5.3.
601 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
602 *
603 * @since 1.20
604 *
605 * @return string
606 */
607 protected static function get_called_class() {
608 $bt = debug_backtrace();
609 $l = count($bt) - 1;
610 $matches = array();
611 while(empty($matches) && $l > -1){
612 $lines = file($bt[$l]['file']);
613 $callerLine = $lines[$bt[$l]['line']-1];
614 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
615 $callerLine,
616 $matches);
617 }
618 if (!isset($matches[1])) $matches[1]=NULL; //for notices
619 if ($matches[1] == 'self') {
620 $line = $bt[$l]['line']-1;
621 while ($line > 0 && strpos($lines[$line], 'class') === false) {
622 $line--;
623 }
624 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
625 }
626 return $matches[1];
627 }
628
629 /**
630 * Get an array with fields from a database result,
631 * that can be fed directly to the constructor or
632 * to setFields.
633 *
634 * @since 1.20
635 *
636 * @param stdClass $result
637 *
638 * @return array
639 */
640 public function getFieldsFromDBResult( stdClass $result ) {
641 $result = (array)$result;
642 return array_combine(
643 $this->unprefixFieldNames( array_keys( $result ) ),
644 array_values( $result )
645 );
646 }
647
648 /**
649 * Get a new instance of the class from a database result.
650 *
651 * @since 1.20
652 *
653 * @param stdClass $result
654 *
655 * @return ORMRow
656 */
657 public function newFromDBResult( stdClass $result ) {
658 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
659 }
660
661 /**
662 * Get a new instance of the class from an array.
663 *
664 * @since 1.20
665 *
666 * @param array $data
667 * @param boolean $loadDefaults
668 *
669 * @return ORMRow
670 */
671 public function newFromArray( array $data, $loadDefaults = false ) {
672 $class = $this->getRowClass();
673 return new $class( $this, $data, $loadDefaults );
674 }
675
676 /**
677 * Return the names of the fields.
678 *
679 * @since 1.20
680 *
681 * @return array
682 */
683 public function getFieldNames() {
684 return array_keys( $this->getFields() );
685 }
686
687 /**
688 * Gets if the object can take a certain field.
689 *
690 * @since 1.20
691 *
692 * @param string $name
693 *
694 * @return boolean
695 */
696 public function canHaveField( $name ) {
697 return array_key_exists( $name, $this->getFields() );
698 }
699
700 }