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