summaryrefslogtreecommitdiff
path: root/includes/db/ORMTable.php
blob: 5f6723b960f720de8bd683c08e05beb5ab252f5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
<?php
/**
 * Abstract base class for representing a single database table.
 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @since 1.20
 * Non-abstract since 1.21
 *
 * @file ORMTable.php
 * @ingroup ORM
 *
 * @license GNU GPL v2 or later
 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
 */

class ORMTable extends DBAccessBase implements IORMTable {

	/**
	 * Cache for instances, used by the singleton method.
	 *
	 * @since 1.20
	 * @deprecated since 1.21
	 *
	 * @var ORMTable[]
	 */
	protected static $instanceCache = array();

	/**
	 * @since 1.21
	 *
	 * @var string
	 */
	protected $tableName;

	/**
	 * @since 1.21
	 *
	 * @var string[]
	 */
	protected $fields = array();

	/**
	 * @since 1.21
	 *
	 * @var string
	 */
	protected $fieldPrefix = '';

	/**
	 * @since 1.21
	 *
	 * @var string
	 */
	protected $rowClass = 'ORMRow';

	/**
	 * @since 1.21
	 *
	 * @var array
	 */
	protected $defaults = array();

	/**
	 * ID of the database connection to use for read operations.
	 * Can be changed via @see setReadDb.
	 *
	 * @since 1.20
	 *
	 * @var integer DB_ enum
	 */
	protected $readDb = DB_SLAVE;

	/**
	 * Constructor.
	 *
	 * @since 1.21
	 *
	 * @param string $tableName
	 * @param string[] $fields
	 * @param array $defaults
	 * @param string|null $rowClass
	 * @param string $fieldPrefix
	 */
	public function __construct( $tableName = '', array $fields = array(), array $defaults = array(), $rowClass = null, $fieldPrefix = '' ) {
		$this->tableName = $tableName;
		$this->fields = $fields;
		$this->defaults = $defaults;

		if ( is_string( $rowClass ) ) {
			$this->rowClass = $rowClass;
		}

		$this->fieldPrefix = $fieldPrefix;
	}

	/**
	 * @see IORMTable::getName
	 *
	 * @since 1.21
	 *
	 * @return string
	 * @throws MWException
	 */
	public function getName() {
		if ( $this->tableName === '' ) {
			throw new MWException( 'The table name needs to be set' );
		}

		return $this->tableName;
	}

	/**
	 * Gets the db field prefix.
	 *
	 * @since 1.20
	 *
	 * @return string
	 */
	protected function getFieldPrefix() {
		return $this->fieldPrefix;
	}

	/**
	 * @see IORMTable::getRowClass
	 *
	 * @since 1.21
	 *
	 * @return string
	 */
	public function getRowClass() {
		return $this->rowClass;
	}

	/**
	 * @see ORMTable::getFields
	 *
	 * @since 1.21
	 *
	 * @return array
	 * @throws MWException
	 */
	public function getFields() {
		if ( $this->fields === array() ) {
			throw new MWException( 'The table needs to have one or more fields' );
		}

		return $this->fields;
	}

	/**
	 * Returns a list of default field values.
	 * field name => field value
	 *
	 * @since 1.20
	 *
	 * @return array
	 */
	public function getDefaults() {
		return $this->defaults;
	}

	/**
	 * Returns a list of the summary fields.
	 * These are fields that cache computed values, such as the amount of linked objects of $type.
	 * This is relevant as one might not want to do actions such as log changes when these get updated.
	 *
	 * @since 1.20
	 *
	 * @return array
	 */
	public function getSummaryFields() {
		return array();
	}

	/**
	 * Selects the the specified fields of the records matching the provided
	 * conditions and returns them as DBDataObject. Field names get prefixed.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $fields
	 * @param array $conditions
	 * @param array $options
	 * @param string|null $functionName
	 *
	 * @return ORMResult
	 */
	public function select( $fields = null, array $conditions = array(),
							array $options = array(), $functionName = null ) {
		$res = $this->rawSelect( $fields, $conditions, $options, $functionName );
		return new ORMResult( $this, $res );
	}

	/**
	 * Selects the the specified fields of the records matching the provided
	 * conditions and returns them as DBDataObject. Field names get prefixed.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $fields
	 * @param array $conditions
	 * @param array $options
	 * @param string|null $functionName
	 *
	 * @return array of row objects
	 * @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
	 */
	public function selectObjects( $fields = null, array $conditions = array(),
								   array $options = array(), $functionName = null ) {
		$result = $this->selectFields( $fields, $conditions, $options, false, $functionName );

		$objects = array();

		foreach ( $result as $record ) {
			$objects[] = $this->newRow( $record );
		}

		return $objects;
	}

	/**
	 * Do the actual select.
	 *
	 * @since 1.20
	 *
	 * @param null|string|array $fields
	 * @param array             $conditions
	 * @param array             $options
	 * @param null|string       $functionName
	 *
	 * @return ResultWrapper
	 * @throws DBQueryError if the quey failed (even if the database was in ignoreErrors mode).
	 */
	public function rawSelect( $fields = null, array $conditions = array(),
							   array $options = array(), $functionName = null ) {
		if ( is_null( $fields ) ) {
			$fields = array_keys( $this->getFields() );
		}
		else {
			$fields = (array)$fields;
		}

		$dbr = $this->getReadDbConnection();
		$result = $dbr->select(
			$this->getName(),
			$this->getPrefixedFields( $fields ),
			$this->getPrefixedValues( $conditions ),
			is_null( $functionName ) ? __METHOD__ : $functionName,
			$options
		);

		/* @var Exception $error */
		$error = null;

		if ( $result === false ) {
			// Database connection was in "ignoreErrors" mode. We don't like that.
			// So, we emulate the DBQueryError that should have been thrown.
			$error = new DBQueryError(
				$dbr,
				$dbr->lastError(),
				$dbr->lastErrno(),
				$dbr->lastQuery(),
				is_null( $functionName ) ? __METHOD__ : $functionName
			);
		}

		$this->releaseConnection( $dbr );

		if ( $error ) {
			// Note: construct the error before releasing the connection,
			// but throw it after.
			throw $error;
		}

		return $result;
	}

	/**
	 * Selects the the specified fields of the records matching the provided
	 * conditions and returns them as associative arrays.
	 * Provided field names get prefixed.
	 * Returned field names will not have a prefix.
	 *
	 * When $collapse is true:
	 * If one field is selected, each item in the result array will be this field.
	 * If two fields are selected, each item in the result array will have as key
	 * the first field and as value the second field.
	 * If more then two fields are selected, each item will be an associative array.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $fields
	 * @param array $conditions
	 * @param array $options
	 * @param boolean $collapse Set to false to always return each result row as associative array.
	 * @param string|null $functionName
	 *
	 * @return array of array
	 */
	public function selectFields( $fields = null, array $conditions = array(),
								  array $options = array(), $collapse = true, $functionName = null ) {
		$objects = array();

		$result = $this->rawSelect( $fields, $conditions, $options, $functionName );

		foreach ( $result as $record ) {
			$objects[] = $this->getFieldsFromDBResult( $record );
		}

		if ( $collapse ) {
			if ( count( $fields ) === 1 ) {
				$objects = array_map( 'array_shift', $objects );
			}
			elseif ( count( $fields ) === 2 ) {
				$o = array();

				foreach ( $objects as $object ) {
					$o[array_shift( $object )] = array_shift( $object );
				}

				$objects = $o;
			}
		}

		return $objects;
	}

	/**
	 * Selects the the specified fields of the first matching record.
	 * Field names get prefixed.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $fields
	 * @param array $conditions
	 * @param array $options
	 * @param string|null $functionName
	 *
	 * @return IORMRow|bool False on failure
	 */
	public function selectRow( $fields = null, array $conditions = array(),
							   array $options = array(), $functionName = null ) {
		$options['LIMIT'] = 1;

		$objects = $this->select( $fields, $conditions, $options, $functionName );

		return ( !$objects || $objects->isEmpty() ) ? false : $objects->current();
	}

	/**
	 * Selects the the specified fields of the records matching the provided
	 * conditions. Field names do NOT get prefixed.
	 *
	 * @since 1.20
	 *
	 * @param array $fields
	 * @param array $conditions
	 * @param array $options
	 * @param string|null $functionName
	 *
	 * @return ResultWrapper
	 */
	public function rawSelectRow( array $fields, array $conditions = array(),
								  array $options = array(), $functionName = null ) {
		$dbr = $this->getReadDbConnection();

		$result = $dbr->selectRow(
			$this->getName(),
			$fields,
			$conditions,
			is_null( $functionName ) ? __METHOD__ : $functionName,
			$options
		);

		$this->releaseConnection( $dbr );
		return $result;
	}

	/**
	 * Selects the the specified fields of the first record matching the provided
	 * conditions and returns it as an associative array, or false when nothing matches.
	 * This method makes use of selectFields and expects the same parameters and
	 * returns the same results (if there are any, if there are none, this method returns false).
	 * @see ORMTable::selectFields
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $fields
	 * @param array $conditions
	 * @param array $options
	 * @param boolean $collapse Set to false to always return each result row as associative array.
	 * @param string|null $functionName
	 *
	 * @return mixed|array|bool False on failure
	 */
	public function selectFieldsRow( $fields = null, array $conditions = array(),
									 array $options = array(), $collapse = true, $functionName = null ) {
		$options['LIMIT'] = 1;

		$objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );

		return empty( $objects ) ? false : $objects[0];
	}

	/**
	 * Returns if there is at least one record matching the provided conditions.
	 * Condition field names get prefixed.
	 *
	 * @since 1.20
	 *
	 * @param array $conditions
	 *
	 * @return boolean
	 */
	public function has( array $conditions = array() ) {
		return $this->selectRow( array( 'id' ), $conditions ) !== false;
	}

	/**
	 * Checks if the table exists
	 *
	 * @since 1.21
	 *
	 * @return boolean
	 */
	public function exists() {
		$dbr = $this->getReadDbConnection();
		$exists = $dbr->tableExists( $this->getName() );
		$this->releaseConnection( $dbr );

		return $exists;
	}

	/**
	 * Returns the amount of matching records.
	 * Condition field names get prefixed.
	 *
	 * Note that this can be expensive on large tables.
	 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
	 *
	 * @since 1.20
	 *
	 * @param array $conditions
	 * @param array $options
	 *
	 * @return integer
	 */
	public function count( array $conditions = array(), array $options = array() ) {
		$res = $this->rawSelectRow(
			array( 'rowcount' => 'COUNT(*)' ),
			$this->getPrefixedValues( $conditions ),
			$options,
			__METHOD__
		);

		return $res->rowcount;
	}

	/**
	 * Removes the object from the database.
	 *
	 * @since 1.20
	 *
	 * @param array $conditions
	 * @param string|null $functionName
	 *
	 * @return boolean Success indicator
	 */
	public function delete( array $conditions, $functionName = null ) {
		$dbw = $this->getWriteDbConnection();

		$result = $dbw->delete(
			$this->getName(),
			$conditions === array() ? '*' : $this->getPrefixedValues( $conditions ),
			is_null( $functionName ) ? __METHOD__ : $functionName
		) !== false; // DatabaseBase::delete does not always return true for success as documented...

		$this->releaseConnection( $dbw );
		return $result;
	}

	/**
	 * Get API parameters for the fields supported by this object.
	 *
	 * @since 1.20
	 *
	 * @param boolean $requireParams
	 * @param boolean $setDefaults
	 *
	 * @return array
	 */
	public function getAPIParams( $requireParams = false, $setDefaults = false ) {
		$typeMap = array(
			'id' => 'integer',
			'int' => 'integer',
			'float' => 'NULL',
			'str' => 'string',
			'bool' => 'integer',
			'array' => 'string',
			'blob' => 'string',
		);

		$params = array();
		$defaults = $this->getDefaults();

		foreach ( $this->getFields() as $field => $type ) {
			if ( $field == 'id' ) {
				continue;
			}

			$hasDefault = array_key_exists( $field, $defaults );

			$params[$field] = array(
				ApiBase::PARAM_TYPE => $typeMap[$type],
				ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
			);

			if ( $type == 'array' ) {
				$params[$field][ApiBase::PARAM_ISMULTI] = true;
			}

			if ( $setDefaults && $hasDefault ) {
				$default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
				$params[$field][ApiBase::PARAM_DFLT] = $default;
			}
		}

		return $params;
	}

	/**
	 * Returns an array with the fields and their descriptions.
	 *
	 * field name => field description
	 *
	 * @since 1.20
	 *
	 * @return array
	 */
	public function getFieldDescriptions() {
		return array();
	}

	/**
	 * Get the database ID used for read operations.
	 *
	 * @since 1.20
	 *
	 * @return integer DB_ enum
	 */
	public function getReadDb() {
		return $this->readDb;
	}

	/**
	 * Set the database ID to use for read operations, use DB_XXX constants or an index to the load balancer setup.
	 *
	 * @param integer $db
	 *
	 * @since 1.20
	 */
	public function setReadDb( $db ) {
		$this->readDb = $db;
	}

	/**
	 * Get the ID of the any foreign wiki to use as a target for database operations
	 *
	 * @since 1.20
	 *
	 * @return String|bool The target wiki, in a form that  LBFactory understands (or false if the local wiki is used)
	 */
	public function getTargetWiki() {
		return $this->wiki;
	}

	/**
	 * Set the ID of the any foreign wiki to use as a target for database operations
	 *
	 * @param string|bool $wiki The target wiki, in a form that  LBFactory understands (or false if the local wiki shall be used)
	 *
	 * @since 1.20
	 */
	public function setTargetWiki( $wiki ) {
		$this->wiki = $wiki;
	}

	/**
	 * Get the database type used for read operations.
	 * This is to be used instead of wfGetDB.
	 *
	 * @see LoadBalancer::getConnection
	 *
	 * @since 1.20
	 *
	 * @return DatabaseBase The database object
	 */
	public function getReadDbConnection() {
		return $this->getConnection( $this->getReadDb(), array() );
	}

	/**
	 * Get the database type used for read operations.
	 * This is to be used instead of wfGetDB.
	 *
	 * @see LoadBalancer::getConnection
	 *
	 * @since 1.20
	 *
	 * @return DatabaseBase The database object
	 */
	public function getWriteDbConnection() {
		return $this->getConnection( DB_MASTER, array() );
	}

	/**
	 * Releases the lease on the given database connection. This is useful mainly
	 * for connections to a foreign wiki. It does nothing for connections to the local wiki.
	 *
	 * @see LoadBalancer::reuseConnection
	 *
	 * @param DatabaseBase $db the database
	 *
	 * @since 1.20
	 */
	public function releaseConnection( DatabaseBase $db ) {
		parent::releaseConnection( $db ); // just make it public
	}

	/**
	 * Update the records matching the provided conditions by
	 * setting the fields that are keys in the $values param to
	 * their corresponding values.
	 *
	 * @since 1.20
	 *
	 * @param array $values
	 * @param array $conditions
	 *
	 * @return boolean Success indicator
	 */
	public function update( array $values, array $conditions = array() ) {
		$dbw = $this->getWriteDbConnection();

		$result = $dbw->update(
			$this->getName(),
			$this->getPrefixedValues( $values ),
			$this->getPrefixedValues( $conditions ),
			__METHOD__
		) !== false; // DatabaseBase::update does not always return true for success as documented...

		$this->releaseConnection( $dbw );
		return $result;
	}

	/**
	 * Computes the values of the summary fields of the objects matching the provided conditions.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $summaryFields
	 * @param array $conditions
	 */
	public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
		$slave = $this->getReadDb();
		$this->setReadDb( DB_MASTER );

		/**
		 * @var IORMRow $item
		 */
		foreach ( $this->select( null, $conditions ) as $item ) {
			$item->loadSummaryFields( $summaryFields );
			$item->setSummaryMode( true );
			$item->save();
		}

		$this->setReadDb( $slave );
	}

	/**
	 * Takes in an associative array with field names as keys and
	 * their values as value. The field names are prefixed with the
	 * db field prefix.
	 *
	 * @since 1.20
	 *
	 * @param array $values
	 *
	 * @return array
	 */
	public function getPrefixedValues( array $values ) {
		$prefixedValues = array();

		foreach ( $values as $field => $value ) {
			if ( is_integer( $field ) ) {
				if ( is_array( $value ) ) {
					$field = $value[0];
					$value = $value[1];
				}
				else {
					$value = explode( ' ', $value, 2 );
					$value[0] = $this->getPrefixedField( $value[0] );
					$prefixedValues[] = implode( ' ', $value );
					continue;
				}
			}

			$prefixedValues[$this->getPrefixedField( $field )] = $value;
		}

		return $prefixedValues;
	}

	/**
	 * Takes in a field or array of fields and returns an
	 * array with their prefixed versions, ready for db usage.
	 *
	 * @since 1.20
	 *
	 * @param array|string $fields
	 *
	 * @return array
	 */
	public function getPrefixedFields( array $fields ) {
		foreach ( $fields as &$field ) {
			$field = $this->getPrefixedField( $field );
		}

		return $fields;
	}

	/**
	 * Takes in a field and returns an it's prefixed version, ready for db usage.
	 *
	 * @since 1.20
	 *
	 * @param string|array $field
	 *
	 * @return string
	 */
	public function getPrefixedField( $field ) {
		return $this->getFieldPrefix() . $field;
	}

	/**
	 * Takes an array of field names with prefix and returns the unprefixed equivalent.
	 *
	 * @since 1.20
	 *
	 * @param array $fieldNames
	 *
	 * @return array
	 */
	public function unprefixFieldNames( array $fieldNames ) {
		return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
	}

	/**
	 * Takes a field name with prefix and returns the unprefixed equivalent.
	 *
	 * @since 1.20
	 *
	 * @param string $fieldName
	 *
	 * @return string
	 */
	public function unprefixFieldName( $fieldName ) {
		return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
	}

	/**
	 * Get an instance of this class.
	 *
	 * @since 1.20
	 * @deprecated since 1.21
	 *
	 * @return IORMTable
	 */
	public static function singleton() {
		$class = get_called_class();

		if ( !array_key_exists( $class, self::$instanceCache ) ) {
			self::$instanceCache[$class] = new $class;
		}

		return self::$instanceCache[$class];
	}

	/**
	 * Get an array with fields from a database result,
	 * that can be fed directly to the constructor or
	 * to setFields.
	 *
	 * @since 1.20
	 *
	 * @param stdClass $result
	 *
	 * @return array
	 */
	public function getFieldsFromDBResult( stdClass $result ) {
		$result = (array)$result;

		$rawFields = array_combine(
			$this->unprefixFieldNames( array_keys( $result ) ),
			array_values( $result )
		);

		$fieldDefinitions = $this->getFields();
		$fields = array();

		foreach ( $rawFields as $name => $value ) {
			if ( array_key_exists( $name, $fieldDefinitions ) ) {
				switch ( $fieldDefinitions[$name] ) {
					case 'int':
						$value = (int)$value;
						break;
					case 'float':
						$value = (float)$value;
						break;
					case 'bool':
						if ( is_string( $value ) ) {
							$value = $value !== '0';
						} elseif ( is_int( $value ) ) {
							$value = $value !== 0;
						}
						break;
					case 'array':
						if ( is_string( $value ) ) {
							$value = unserialize( $value );
						}

						if ( !is_array( $value ) ) {
							$value = array();
						}
						break;
					case 'blob':
						if ( is_string( $value ) ) {
							$value = unserialize( $value );
						}
						break;
					case 'id':
						if ( is_string( $value ) ) {
							$value = (int)$value;
						}
						break;
				}

				$fields[$name] = $value;
			} else {
				throw new MWException( 'Attempted to set unknown field ' . $name );
			}
		}

		return $fields;
	}

	/**
	 * @see ORMTable::newRowFromFromDBResult
	 *
	 * @deprecated use newRowFromDBResult instead
	 * @since 1.20
	 *
	 * @param stdClass $result
	 *
	 * @return IORMRow
	 */
	public function newFromDBResult( stdClass $result ) {
		return self::newRowFromDBResult( $result );
	}

	/**
	 * Get a new instance of the class from a database result.
	 *
	 * @since 1.20
	 *
	 * @param stdClass $result
	 *
	 * @return IORMRow
	 */
	public function newRowFromDBResult( stdClass $result ) {
		return $this->newRow( $this->getFieldsFromDBResult( $result ) );
	}

	/**
	 * @see ORMTable::newRow
	 *
	 * @deprecated use newRow instead
	 * @since 1.20
	 *
	 * @param array $data
	 * @param boolean $loadDefaults
	 *
	 * @return IORMRow
	 */
	public function newFromArray( array $data, $loadDefaults = false ) {
		return static::newRow( $data, $loadDefaults );
	}

	/**
	 * Get a new instance of the class from an array.
	 *
	 * @since 1.20
	 *
	 * @param array $fields
	 * @param boolean $loadDefaults
	 *
	 * @return IORMRow
	 */
	public function newRow( array $fields, $loadDefaults = false ) {
		$class = $this->getRowClass();

		return new $class( $this, $fields, $loadDefaults );
	}

	/**
	 * Return the names of the fields.
	 *
	 * @since 1.20
	 *
	 * @return array
	 */
	public function getFieldNames() {
		return array_keys( $this->getFields() );
	}

	/**
	 * Gets if the object can take a certain field.
	 *
	 * @since 1.20
	 *
	 * @param string $name
	 *
	 * @return boolean
	 */
	public function canHaveField( $name ) {
		return array_key_exists( $name, $this->getFields() );
	}

	/**
	 * Updates the provided row in the database.
	 *
	 * @since 1.22
	 *
	 * @param IORMRow $row The row to save
	 * @param string|null $functionName
	 *
	 * @return boolean Success indicator
	 */
	public function updateRow( IORMRow $row, $functionName = null ) {
		$dbw = $this->getWriteDbConnection();

		$success = $dbw->update(
			$this->getName(),
			$this->getWriteValues( $row ),
			$this->getPrefixedValues( array( 'id' => $row->getId() ) ),
			is_null( $functionName ) ? __METHOD__ : $functionName
		);

		$this->releaseConnection( $dbw );

		// DatabaseBase::update does not always return true for success as documented...
		return $success !== false;
	}

	/**
	 * Inserts the provided row into the database.
	 *
	 * @since 1.22
	 *
	 * @param IORMRow $row
	 * @param string|null $functionName
	 * @param array|null $options
	 *
	 * @return boolean Success indicator
	 */
	public function insertRow( IORMRow $row, $functionName = null, array $options = null ) {
		$dbw = $this->getWriteDbConnection();

		$success = $dbw->insert(
			$this->getName(),
			$this->getWriteValues( $row ),
			is_null( $functionName ) ? __METHOD__ : $functionName,
			$options
		);

		// DatabaseBase::insert does not always return true for success as documented...
		$success = $success !== false;

		if ( $success ) {
			$row->setField( 'id', $dbw->insertId() );
		}

		$this->releaseConnection( $dbw );

		return $success;
	}

	/**
	 * Gets the fields => values to write to the table.
	 *
	 * @since 1.22
	 *
	 * @param IORMRow $row
	 *
	 * @return array
	 */
	protected function getWriteValues( IORMRow $row ) {
		$values = array();

		$rowFields = $row->getFields();

		foreach ( $this->getFields() as $name => $type ) {
			if ( array_key_exists( $name, $rowFields ) ) {
				$value = $rowFields[$name];

				switch ( $type ) {
					case 'array':
						$value = (array)$value;
					// fall-through!
					case 'blob':
						$value = serialize( $value );
					// fall-through!
				}

				$values[$this->getPrefixedField( $name )] = $value;
			}
		}

		return $values;
	}

	/**
	 * Removes the provided row from the database.
	 *
	 * @since 1.22
	 *
	 * @param IORMRow $row
	 * @param string|null $functionName
	 *
	 * @return boolean Success indicator
	 */
	public function removeRow( IORMRow $row, $functionName = null ) {
		$success = $this->delete(
			array( 'id' => $row->getId() ),
			is_null( $functionName ) ? __METHOD__ : $functionName
		);

		// DatabaseBase::delete does not always return true for success as documented...
		return $success !== false;
	}

	/**
	 * Add an amount (can be negative) to the specified field (needs to be numeric).
	 *
	 * @since 1.22
	 *
	 * @param array $conditions
	 * @param string $field
	 * @param integer $amount
	 *
	 * @return boolean Success indicator
	 * @throws MWException
	 */
	public function addToField( array $conditions, $field, $amount ) {
		if ( !array_key_exists( $field, $this->fields ) ) {
			throw new MWException( 'Unknown field "' . $field . '" provided' );
		}

		if ( $amount == 0 ) {
			return true;
		}

		$absoluteAmount = abs( $amount );
		$isNegative = $amount < 0;

		$fullField = $this->getPrefixedField( $field );

		$dbw = $this->getWriteDbConnection();

		$success = $dbw->update(
			$this->getName(),
			array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
			$this->getPrefixedValues( $conditions ),
			__METHOD__
		) !== false; // DatabaseBase::update does not always return true for success as documented...

		$this->releaseConnection( $dbw );

		return $success;
	}

}