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