Move up devunt's name to Developers
[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 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 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 Exception
252 * @throws MWException
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 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 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 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 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 * @deprecated since 1.25, will be removed
782 *
783 * @param string[] $fieldNames
784 *
785 * @return string[]
786 */
787 public function unprefixFieldNames( array $fieldNames ) {
788 wfDeprecated( __METHOD__, '1.25' );
789
790 return $this->stripFieldPrefix( $fieldNames );
791 }
792
793 /**
794 * Takes an array of field names with prefix and returns the unprefixed equivalent.
795 *
796 * @param string[] $fieldNames
797 *
798 * @return string[]
799 */
800 private function stripFieldPrefix( array $fieldNames ) {
801 $start = strlen( $this->fieldPrefix );
802
803 return array_map( function ( $fieldName ) use ( $start ) {
804 return substr( $fieldName, $start );
805 }, $fieldNames );
806 }
807
808 /**
809 * Takes a field name with prefix and returns the unprefixed equivalent.
810 *
811 * @since 1.20
812 * @deprecated since 1.25, will be removed
813 *
814 * @param string $fieldName
815 *
816 * @return string
817 */
818 public function unprefixFieldName( $fieldName ) {
819 wfDeprecated( __METHOD__, '1.25' );
820
821 return substr( $fieldName, strlen( $this->fieldPrefix ) );
822 }
823
824 /**
825 * Get an instance of this class.
826 *
827 * @since 1.20
828 * @deprecated since 1.21
829 *
830 * @return IORMTable
831 */
832 public static function singleton() {
833 $class = get_called_class();
834
835 if ( !array_key_exists( $class, self::$instanceCache ) ) {
836 self::$instanceCache[$class] = new $class;
837 }
838
839 return self::$instanceCache[$class];
840 }
841
842 /**
843 * Get an array with fields from a database result,
844 * that can be fed directly to the constructor or
845 * to setFields.
846 *
847 * @since 1.20
848 *
849 * @param stdClass $result
850 * @throws MWException
851 * @return array
852 */
853 public function getFieldsFromDBResult( stdClass $result ) {
854 $result = (array)$result;
855
856 $rawFields = array_combine(
857 $this->stripFieldPrefix( array_keys( $result ) ),
858 array_values( $result )
859 );
860
861 $fieldDefinitions = $this->getFields();
862 $fields = array();
863
864 foreach ( $rawFields as $name => $value ) {
865 if ( array_key_exists( $name, $fieldDefinitions ) ) {
866 switch ( $fieldDefinitions[$name] ) {
867 case 'int':
868 $value = (int)$value;
869 break;
870 case 'float':
871 $value = (float)$value;
872 break;
873 case 'bool':
874 if ( is_string( $value ) ) {
875 $value = $value !== '0';
876 } elseif ( is_int( $value ) ) {
877 $value = $value !== 0;
878 }
879 break;
880 case 'array':
881 if ( is_string( $value ) ) {
882 $value = unserialize( $value );
883 }
884
885 if ( !is_array( $value ) ) {
886 $value = array();
887 }
888 break;
889 case 'blob':
890 if ( is_string( $value ) ) {
891 $value = unserialize( $value );
892 }
893 break;
894 case 'id':
895 if ( is_string( $value ) ) {
896 $value = (int)$value;
897 }
898 break;
899 }
900
901 $fields[$name] = $value;
902 } else {
903 throw new MWException( 'Attempted to set unknown field ' . $name );
904 }
905 }
906
907 return $fields;
908 }
909
910 /**
911 * @see ORMTable::newRowFromFromDBResult
912 *
913 * @deprecated since 1.20 use newRowFromDBResult instead
914 * @since 1.20
915 *
916 * @param stdClass $result
917 *
918 * @return IORMRow
919 */
920 public function newFromDBResult( stdClass $result ) {
921 return self::newRowFromDBResult( $result );
922 }
923
924 /**
925 * Get a new instance of the class from a database result.
926 *
927 * @since 1.20
928 *
929 * @param stdClass $result
930 *
931 * @return IORMRow
932 */
933 public function newRowFromDBResult( stdClass $result ) {
934 return $this->newRow( $this->getFieldsFromDBResult( $result ) );
935 }
936
937 /**
938 * @see ORMTable::newRow
939 *
940 * @deprecated since 1.20 use newRow instead
941 * @since 1.20
942 *
943 * @param array $data
944 * @param bool $loadDefaults
945 *
946 * @return IORMRow
947 */
948 public function newFromArray( array $data, $loadDefaults = false ) {
949 return static::newRow( $data, $loadDefaults );
950 }
951
952 /**
953 * Get a new instance of the class from an array.
954 *
955 * @since 1.20
956 *
957 * @param array $fields
958 * @param bool $loadDefaults
959 *
960 * @return IORMRow
961 */
962 public function newRow( array $fields, $loadDefaults = false ) {
963 $class = $this->getRowClass();
964
965 return new $class( $this, $fields, $loadDefaults );
966 }
967
968 /**
969 * Return the names of the fields.
970 *
971 * @since 1.20
972 *
973 * @return array
974 */
975 public function getFieldNames() {
976 return array_keys( $this->getFields() );
977 }
978
979 /**
980 * Gets if the object can take a certain field.
981 *
982 * @since 1.20
983 *
984 * @param string $name
985 *
986 * @return bool
987 */
988 public function canHaveField( $name ) {
989 return array_key_exists( $name, $this->getFields() );
990 }
991
992 /**
993 * Updates the provided row in the database.
994 *
995 * @since 1.22
996 *
997 * @param IORMRow $row The row to save
998 * @param string|null $functionName
999 *
1000 * @return bool Success indicator
1001 */
1002 public function updateRow( IORMRow $row, $functionName = null ) {
1003 $dbw = $this->getWriteDbConnection();
1004
1005 $success = $dbw->update(
1006 $this->getName(),
1007 $this->getWriteValues( $row ),
1008 $this->getPrefixedValues( array( 'id' => $row->getId() ) ),
1009 is_null( $functionName ) ? __METHOD__ : $functionName
1010 );
1011
1012 $this->releaseConnection( $dbw );
1013
1014 // DatabaseBase::update does not always return true for success as documented...
1015 return $success !== false;
1016 }
1017
1018 /**
1019 * Inserts the provided row into the database.
1020 *
1021 * @since 1.22
1022 *
1023 * @param IORMRow $row
1024 * @param string|null $functionName
1025 * @param array|null $options
1026 *
1027 * @return bool Success indicator
1028 */
1029 public function insertRow( IORMRow $row, $functionName = null, array $options = null ) {
1030 $dbw = $this->getWriteDbConnection();
1031
1032 $success = $dbw->insert(
1033 $this->getName(),
1034 $this->getWriteValues( $row ),
1035 is_null( $functionName ) ? __METHOD__ : $functionName,
1036 $options
1037 );
1038
1039 // DatabaseBase::insert does not always return true for success as documented...
1040 $success = $success !== false;
1041
1042 if ( $success ) {
1043 $row->setField( 'id', $dbw->insertId() );
1044 }
1045
1046 $this->releaseConnection( $dbw );
1047
1048 return $success;
1049 }
1050
1051 /**
1052 * Gets the fields => values to write to the table.
1053 *
1054 * @since 1.22
1055 *
1056 * @param IORMRow $row
1057 *
1058 * @return array
1059 */
1060 protected function getWriteValues( IORMRow $row ) {
1061 $values = array();
1062
1063 $rowFields = $row->getFields();
1064
1065 foreach ( $this->getFields() as $name => $type ) {
1066 if ( array_key_exists( $name, $rowFields ) ) {
1067 $value = $rowFields[$name];
1068
1069 switch ( $type ) {
1070 case 'array':
1071 $value = (array)$value;
1072 // fall-through!
1073 case 'blob':
1074 $value = serialize( $value );
1075 // fall-through!
1076 }
1077
1078 $values[$this->getPrefixedField( $name )] = $value;
1079 }
1080 }
1081
1082 return $values;
1083 }
1084
1085 /**
1086 * Removes the provided row from the database.
1087 *
1088 * @since 1.22
1089 *
1090 * @param IORMRow $row
1091 * @param string|null $functionName
1092 *
1093 * @return bool Success indicator
1094 */
1095 public function removeRow( IORMRow $row, $functionName = null ) {
1096 $success = $this->delete(
1097 array( 'id' => $row->getId() ),
1098 is_null( $functionName ) ? __METHOD__ : $functionName
1099 );
1100
1101 // DatabaseBase::delete does not always return true for success as documented...
1102 return $success !== false;
1103 }
1104
1105 /**
1106 * Add an amount (can be negative) to the specified field (needs to be numeric).
1107 *
1108 * @since 1.22
1109 *
1110 * @param array $conditions
1111 * @param string $field
1112 * @param int $amount
1113 *
1114 * @return bool Success indicator
1115 * @throws MWException
1116 */
1117 public function addToField( array $conditions, $field, $amount ) {
1118 if ( !array_key_exists( $field, $this->fields ) ) {
1119 throw new MWException( 'Unknown field "' . $field . '" provided' );
1120 }
1121
1122 if ( $amount == 0 ) {
1123 return true;
1124 }
1125
1126 $absoluteAmount = abs( $amount );
1127 $isNegative = $amount < 0;
1128
1129 $fullField = $this->getPrefixedField( $field );
1130
1131 $dbw = $this->getWriteDbConnection();
1132
1133 $success = $dbw->update(
1134 $this->getName(),
1135 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
1136 $this->getPrefixedValues( $conditions ),
1137 __METHOD__
1138 ) !== false; // DatabaseBase::update does not always return true for success as documented...
1139
1140 $this->releaseConnection( $dbw );
1141
1142 return $success;
1143 }
1144 }