move method and added warning on count function
[lhc/web/wiklou.git] / includes / DBTable.php
1 <?php
2
3 /**
4 * Abstract base class for representing a single database table.
5 *
6 * @since 1.20
7 *
8 * @file DBTable.php
9 *
10 * @licence GNU GPL v2 or later
11 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
12 */
13 abstract class DBTable {
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 getDBTable();
23
24 /**
25 * Returns the name of a DBDataObject deriving class that
26 * represents single rows in this table.
27 *
28 * @since 1.20
29 *
30 * @return string
31 */
32 public abstract function getDataObjectClass();
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 getFieldTypes();
62
63 /**
64 * The database connection to use for read operations.
65 * Can be changed via @see setReadDb.
66 *
67 * @since 1.20
68 * @var integer DB_ enum
69 */
70 protected $readDb = DB_SLAVE;
71
72 /**
73 * Returns a list of default field values.
74 * field name => field value
75 *
76 * @since 1.20
77 *
78 * @return array
79 */
80 public function getDefaults() {
81 return array();
82 }
83
84 /**
85 * Returns a list of the summary fields.
86 * These are fields that cache computed values, such as the amount of linked objects of $type.
87 * This is relevant as one might not want to do actions such as log changes when these get updated.
88 *
89 * @since 1.20
90 *
91 * @return array
92 */
93 public function getSummaryFields() {
94 return array();
95 }
96
97 /**
98 * Selects the the specified fields of the records matching the provided
99 * conditions and returns them as DBDataObject. Field names get prefixed.
100 *
101 * @since 1.20
102 *
103 * @param array|string|null $fields
104 * @param array $conditions
105 * @param array $options
106 *
107 * @return array of self
108 */
109 public function select( $fields = null, array $conditions = array(), array $options = array() ) {
110 $result = $this->selectFields( $fields, $conditions, $options, false );
111
112 $objects = array();
113
114 foreach ( $result as $record ) {
115 $objects[] = $this->newFromArray( $record );
116 }
117
118 return $objects;
119 }
120
121 /**
122 * Selects the the specified fields of the records matching the provided
123 * conditions and returns them as associative arrays.
124 * Provided field names get prefixed.
125 * Returned field names will not have a prefix.
126 *
127 * When $collapse is true:
128 * If one field is selected, each item in the result array will be this field.
129 * If two fields are selected, each item in the result array will have as key
130 * the first field and as value the second field.
131 * If more then two fields are selected, each item will be an associative array.
132 *
133 * @since 1.20
134 *
135 * @param array|string|null $fields
136 * @param array $conditions
137 * @param array $options
138 * @param boolean $collapse Set to false to always return each result row as associative array.
139 *
140 * @return array of array
141 */
142 public function selectFields( $fields = null, array $conditions = array(), array $options = array(), $collapse = true ) {
143 if ( is_null( $fields ) ) {
144 $fields = array_keys( $this->getFieldTypes() );
145 }
146 else {
147 $fields = (array)$fields;
148 }
149
150 $dbr = wfGetDB( $this->getReadDb() );
151 $result = $dbr->select(
152 $this->getDBTable(),
153 $this->getPrefixedFields( $fields ),
154 $this->getPrefixedValues( $conditions ),
155 __METHOD__,
156 $options
157 );
158
159 $objects = array();
160
161 foreach ( $result as $record ) {
162 $objects[] = $this->getFieldsFromDBResult( $record );
163 }
164
165 if ( $collapse ) {
166 if ( count( $fields ) === 1 ) {
167 $objects = array_map( 'array_shift', $objects );
168 }
169 elseif ( count( $fields ) === 2 ) {
170 $o = array();
171
172 foreach ( $objects as $object ) {
173 $o[array_shift( $object )] = array_shift( $object );
174 }
175
176 $objects = $o;
177 }
178 }
179
180 return $objects;
181 }
182
183 /**
184 * Selects the the specified fields of the first matching record.
185 * Field names get prefixed.
186 *
187 * @since 1.20
188 *
189 * @param array|string|null $fields
190 * @param array $conditions
191 * @param array $options
192 *
193 * @return DBObject|bool False on failure
194 */
195 public function selectRow( $fields = null, array $conditions = array(), array $options = array() ) {
196 $options['LIMIT'] = 1;
197
198 $objects = $this->select( $fields, $conditions, $options );
199
200 return count( $objects ) > 0 ? $objects[0] : false;
201 }
202
203 /**
204 * Selects the the specified fields of the records matching the provided
205 * conditions. Field names do NOT get prefixed.
206 *
207 * @since 1.20
208 *
209 * @param array $fields
210 * @param array $conditions
211 * @param array $options
212 *
213 * @return ResultWrapper
214 */
215 public function rawSelectRow( array $fields, array $conditions = array(), array $options = array() ) {
216 $dbr = wfGetDB( $this->getReadDb() );
217
218 return $dbr->selectRow(
219 $this->getDBTable(),
220 $fields,
221 $conditions,
222 __METHOD__,
223 $options
224 );
225 }
226
227 /**
228 * Selects the the specified fields of the first record matching the provided
229 * conditions and returns it as an associative array, or false when nothing matches.
230 * This method makes use of selectFields and expects the same parameters and
231 * returns the same results (if there are any, if there are none, this method returns false).
232 * @see DBDataObject::selectFields
233 *
234 * @since 1.20
235 *
236 * @param array|string|null $fields
237 * @param array $conditions
238 * @param array $options
239 * @param boolean $collapse Set to false to always return each result row as associative array.
240 *
241 * @return mixed|array|bool False on failure
242 */
243 public function selectFieldsRow( $fields = null, array $conditions = array(), array $options = array(), $collapse = true ) {
244 $options['LIMIT'] = 1;
245
246 $objects = $this->selectFields( $fields, $conditions, $options, $collapse );
247
248 return count( $objects ) > 0 ? $objects[0] : false;
249 }
250
251 /**
252 * Returns if there is at least one record matching the provided conditions.
253 * Condition field names get prefixed.
254 *
255 * @since 1.20
256 *
257 * @param array $conditions
258 *
259 * @return boolean
260 */
261 public function has( array $conditions = array() ) {
262 return $this->selectRow( array( 'id' ), $conditions ) !== false;
263 }
264
265 /**
266 * Returns the amount of matching records.
267 * Condition field names get prefixed.
268 *
269 * Note that this can be expensive on large tables.
270 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
271 *
272 * @since 1.20
273 *
274 * @param array $conditions
275 * @param array $options
276 *
277 * @return integer
278 */
279 public function count( array $conditions = array(), array $options = array() ) {
280 $res = $this->rawSelectRow(
281 array( 'COUNT(*) AS rowcount' ),
282 $this->getPrefixedValues( $conditions ),
283 $options
284 );
285
286 return $res->rowcount;
287 }
288
289 /**
290 * Removes the object from the database.
291 *
292 * @since 1.20
293 *
294 * @param array $conditions
295 *
296 * @return boolean Success indicator
297 */
298 public function delete( array $conditions ) {
299 return wfGetDB( DB_MASTER )->delete(
300 $this->getDBTable(),
301 $this->getPrefixedValues( $conditions )
302 );
303 }
304
305 /**
306 * Get API parameters for the fields supported by this object.
307 *
308 * @since 1.20
309 *
310 * @param boolean $requireParams
311 * @param boolean $setDefaults
312 *
313 * @return array
314 */
315 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
316 $typeMap = array(
317 'id' => 'integer',
318 'int' => 'integer',
319 'float' => 'NULL',
320 'str' => 'string',
321 'bool' => 'integer',
322 'array' => 'string',
323 'blob' => 'string',
324 );
325
326 $params = array();
327 $defaults = $this->getDefaults();
328
329 foreach ( $this->getFieldTypes() as $field => $type ) {
330 if ( $field == 'id' ) {
331 continue;
332 }
333
334 $hasDefault = array_key_exists( $field, $defaults );
335
336 $params[$field] = array(
337 ApiBase::PARAM_TYPE => $typeMap[$type],
338 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
339 );
340
341 if ( $type == 'array' ) {
342 $params[$field][ApiBase::PARAM_ISMULTI] = true;
343 }
344
345 if ( $setDefaults && $hasDefault ) {
346 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
347 $params[$field][ApiBase::PARAM_DFLT] = $default;
348 }
349 }
350
351 return $params;
352 }
353
354 /**
355 * Returns an array with the fields and their descriptions.
356 *
357 * field name => field description
358 *
359 * @since 1.20
360 *
361 * @return array
362 */
363 public function getFieldDescriptions() {
364 return array();
365 }
366
367 /**
368 * Get the database type used for read operations.
369 *
370 * @since 1.20
371 *
372 * @return integer DB_ enum
373 */
374 public function getReadDb() {
375 return $this->readDb;
376 }
377
378 /**
379 * Set the database type to use for read operations.
380 *
381 * @param integer $db
382 *
383 * @since 1.20
384 */
385 public function setReadDb( $db ) {
386 $this->readDb = $db;
387 }
388
389 /**
390 * Update the records matching the provided conditions by
391 * setting the fields that are keys in the $values param to
392 * their corresponding values.
393 *
394 * @since 1.20
395 *
396 * @param array $values
397 * @param array $conditions
398 *
399 * @return boolean Success indicator
400 */
401 public function update( array $values, array $conditions = array() ) {
402 $dbw = wfGetDB( DB_MASTER );
403
404 return $dbw->update(
405 $this->getDBTable(),
406 $this->getPrefixedValues( $values ),
407 $this->getPrefixedValues( $conditions ),
408 __METHOD__
409 );
410 }
411
412 /**
413 * Computes the values of the summary fields of the objects matching the provided conditions.
414 *
415 * @since 1.20
416 *
417 * @param array|string|null $summaryFields
418 * @param array $conditions
419 */
420 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
421 $this->setReadDb( DB_MASTER );
422
423 foreach ( $this->select( null, $conditions ) as /* DBDataObject */ $item ) {
424 $item->loadSummaryFields( $summaryFields );
425 $item->setSummaryMode( true );
426 $item->saveExisting();
427 }
428
429 $this->setReadDb( DB_SLAVE );
430 }
431
432 /**
433 * Takes in an associative array with field names as keys and
434 * their values as value. The field names are prefixed with the
435 * db field prefix.
436 *
437 * Field names can also be provided as an array with as first element a table name, such as
438 * $conditions = array(
439 * array( array( 'tablename', 'fieldname' ), $value ),
440 * );
441 *
442 * @since 1.20
443 *
444 * @param array $values
445 *
446 * @return array
447 */
448 public function getPrefixedValues( array $values ) {
449 $prefixedValues = array();
450
451 foreach ( $values as $field => $value ) {
452 if ( is_integer( $field ) ) {
453 if ( is_array( $value ) ) {
454 $field = $value[0];
455 $value = $value[1];
456 }
457 else {
458 $value = explode( ' ', $value, 2 );
459 $value[0] = $this->getPrefixedField( $value[0] );
460 $prefixedValues[] = implode( ' ', $value );
461 continue;
462 }
463 }
464
465 $prefixedValues[$this->getPrefixedField( $field )] = $value;
466 }
467
468 return $prefixedValues;
469 }
470
471 /**
472 * Takes in a field or array of fields and returns an
473 * array with their prefixed versions, ready for db usage.
474 *
475 * @since 1.20
476 *
477 * @param array|string $fields
478 *
479 * @return array
480 */
481 public function getPrefixedFields( array $fields ) {
482 foreach ( $fields as &$field ) {
483 $field = $this->getPrefixedField( $field );
484 }
485
486 return $fields;
487 }
488
489 /**
490 * Takes in a field and returns an it's prefixed version, ready for db usage.
491 *
492 * @since 1.20
493 *
494 * @param string|array $field
495 *
496 * @return string
497 */
498 public function getPrefixedField( $field ) {
499 return $this->getFieldPrefix() . $field;
500 }
501
502 /**
503 * Takes an array of field names with prefix and returns the unprefixed equivalent.
504 *
505 * @since 1.20
506 *
507 * @param array $fieldNames
508 *
509 * @return array
510 */
511 public function unprefixFieldNames( array $fieldNames ) {
512 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
513 }
514
515 /**
516 * Takes a field name with prefix and returns the unprefixed equivalent.
517 *
518 * @since 1.20
519 *
520 * @param string $fieldName
521 *
522 * @return string
523 */
524 public function unprefixFieldName( $fieldName ) {
525 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
526 }
527
528 public function __construct() {
529
530 }
531
532 /**
533 * Get an instance of this class.
534 *
535 * @since 1.20
536 *
537 * @return DBtable
538 */
539 public static function &singleton() {
540 static $instance;
541
542 if ( !isset( $instance ) ) {
543 $instance = new static;
544 }
545
546 return $instance;
547 }
548
549 /**
550 * Get an array with fields from a database result,
551 * that can be fed directly to the constructor or
552 * to setFields.
553 *
554 * @since 1.20
555 *
556 * @param stdClass $result
557 *
558 * @return array
559 */
560 public function getFieldsFromDBResult( stdClass $result ) {
561 $result = (array)$result;
562 return array_combine(
563 $this->unprefixFieldNames( array_keys( $result ) ),
564 array_values( $result )
565 );
566 }
567
568 /**
569 * Get a new instance of the class from a database result.
570 *
571 * @since 1.20
572 *
573 * @param stdClass $result
574 *
575 * @return DBDataObject
576 */
577 public function newFromDBResult( stdClass $result ) {
578 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
579 }
580
581 /**
582 * Get a new instance of the class from an array.
583 *
584 * @since 1.20
585 *
586 * @param array $data
587 * @param boolean $loadDefaults
588 *
589 * @return DBDataObject
590 */
591 public function newFromArray( array $data, $loadDefaults = false ) {
592 $class = $this->getDataObjectClass();
593 return new $class( $this, $data, $loadDefaults );
594 }
595
596 /**
597 * Return the names of the fields.
598 *
599 * @since 1.20
600 *
601 * @return array
602 */
603 public function getFieldNames() {
604 return array_keys( $this->getFieldTypes() );
605 }
606
607 /**
608 * Gets if the object can take a certain field.
609 *
610 * @since 1.20
611 *
612 * @param string $name
613 *
614 * @return boolean
615 */
616 public function canHaveField( $name ) {
617 return array_key_exists( $name, $this->getFieldTypes() );
618 }
619
620 }