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