summaryrefslogtreecommitdiff
path: root/includes/db/ORMRow.php
blob: 6c1f27ffdf22e6f5b56bb553b5b3dd4d50da888e (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
<?php
/**
 * Abstract base class for representing objects that are stored in some DB table.
 * This is basically an ORM-like wrapper around rows in database tables that
 * aims to be both simple and very flexible. It is centered around an associative
 * array of fields and various methods to do common interaction with the database.
 *
 * 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
 *
 * @file ORMRow.php
 * @ingroup ORM
 *
 * @license GNU GPL v2 or later
 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
 */

class ORMRow implements IORMRow {

	/**
	 * The fields of the object.
	 * field name (w/o prefix) => value
	 *
	 * @since 1.20
	 * @var array
	 */
	protected $fields = array( 'id' => null );

	/**
	 * @since 1.20
	 * @var ORMTable
	 */
	protected $table;

	/**
	 * If the object should update summaries of linked items when changed.
	 * For example, update the course_count field in universities when a course in courses is deleted.
	 * Settings this to false can prevent needless updating work in situations
	 * such as deleting a university, which will then delete all it's courses.
	 *
	 * @since 1.20
	 * @var bool
	 */
	protected $updateSummaries = true;

	/**
	 * Indicates if the object is in summary mode.
	 * This mode indicates that only summary fields got updated,
	 * which allows for optimizations.
	 *
	 * @since 1.20
	 * @var bool
	 */
	protected $inSummaryMode = false;

	/**
	 * Constructor.
	 *
	 * @since 1.20
	 *
	 * @param IORMTable $table
	 * @param array|null $fields
	 * @param boolean $loadDefaults
	 */
	public function __construct( IORMTable $table, $fields = null, $loadDefaults = false ) {
		$this->table = $table;

		if ( !is_array( $fields ) ) {
			$fields = array();
		}

		if ( $loadDefaults ) {
			$fields = array_merge( $this->table->getDefaults(), $fields );
		}

		$this->setFields( $fields );
	}

	/**
	 * Load the specified fields from the database.
	 *
	 * @since 1.20
	 *
	 * @param array|null $fields
	 * @param boolean $override
	 * @param boolean $skipLoaded
	 *
	 * @return bool Success indicator
	 */
	public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
		if ( is_null( $this->getId() ) ) {
			return false;
		}

		if ( is_null( $fields ) ) {
			$fields = array_keys( $this->table->getFields() );
		}

		if ( $skipLoaded ) {
			$fields = array_diff( $fields, array_keys( $this->fields ) );
		}

		if ( !empty( $fields ) ) {
			$result = $this->table->rawSelectRow(
				$this->table->getPrefixedFields( $fields ),
				array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
				array( 'LIMIT' => 1 ),
				__METHOD__
			);

			if ( $result !== false ) {
				$this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
				return true;
			}
			return false;
		}

		return true;
	}

	/**
	 * Gets the value of a field.
	 *
	 * @since 1.20
	 *
	 * @param string $name Field name
	 * @param $default mixed: Default value to return when none is found
	 * (default: null)
	 *
	 * @throws MWException
	 * @return mixed
	 */
	public function getField( $name, $default = null ) {
		if ( $this->hasField( $name ) ) {
			return $this->fields[$name];
		} elseif ( !is_null( $default ) ) {
			return $default;
		} else {
			throw new MWException( 'Attempted to get not-set field ' . $name );
		}
	}

	/**
	 * Gets the value of a field but first loads it if not done so already.
	 *
	 * @since 1.20
	 *
	 * @param $name string
	 *
	 * @return mixed
	 */
	public function loadAndGetField( $name ) {
		if ( !$this->hasField( $name ) ) {
			$this->loadFields( array( $name ) );
		}

		return $this->getField( $name );
	}

	/**
	 * Remove a field.
	 *
	 * @since 1.20
	 *
	 * @param string $name
	 */
	public function removeField( $name ) {
		unset( $this->fields[$name] );
	}

	/**
	 * Returns the objects database id.
	 *
	 * @since 1.20
	 *
	 * @return integer|null
	 */
	public function getId() {
		return $this->getField( 'id' );
	}

	/**
	 * Sets the objects database id.
	 *
	 * @since 1.20
	 *
	 * @param integer|null $id
	 */
	public function setId( $id ) {
		$this->setField( 'id', $id );
	}

	/**
	 * Gets if a certain field is set.
	 *
	 * @since 1.20
	 *
	 * @param string $name
	 *
	 * @return boolean
	 */
	public function hasField( $name ) {
		return array_key_exists( $name, $this->fields );
	}

	/**
	 * Gets if the id field is set.
	 *
	 * @since 1.20
	 *
	 * @return boolean
	 */
	public function hasIdField() {
		return $this->hasField( 'id' )
			&& !is_null( $this->getField( 'id' ) );
	}

	/**
	 * Sets multiple fields.
	 *
	 * @since 1.20
	 *
	 * @param array $fields The fields to set
	 * @param boolean $override Override already set fields with the provided values?
	 */
	public function setFields( array $fields, $override = true ) {
		foreach ( $fields as $name => $value ) {
			if ( $override || !$this->hasField( $name ) ) {
				$this->setField( $name, $value );
			}
		}
	}

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

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

				// Skip null id fields so that the DBMS can set the default.
				if ( $name === 'id' && is_null ( $value ) ) {
					continue;
				}

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

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

		return $values;
	}

	/**
	 * Serializes the object to an associative array which
	 * can then easily be converted into JSON or similar.
	 *
	 * @since 1.20
	 *
	 * @param null|array $fields
	 * @param boolean $incNullId
	 *
	 * @return array
	 */
	public function toArray( $fields = null, $incNullId = false ) {
		$data = array();
		$setFields = array();

		if ( !is_array( $fields ) ) {
			$setFields = $this->getSetFieldNames();
		} else {
			foreach ( $fields as $field ) {
				if ( $this->hasField( $field ) ) {
					$setFields[] = $field;
				}
			}
		}

		foreach ( $setFields as $field ) {
			if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
				$data[$field] = $this->getField( $field );
			}
		}

		return $data;
	}

	/**
	 * Load the default values, via getDefaults.
	 *
	 * @since 1.20
	 *
	 * @param boolean $override
	 */
	public function loadDefaults( $override = true ) {
		$this->setFields( $this->table->getDefaults(), $override );
	}

	/**
	 * Writes the answer to the database, either updating it
	 * when it already exists, or inserting it when it doesn't.
	 *
	 * @since 1.20
	 *
	 * @param string|null $functionName
	 *
	 * @return boolean Success indicator
	 */
	public function save( $functionName = null ) {
		if ( $this->hasIdField() ) {
			return $this->saveExisting( $functionName );
		} else {
			return $this->insert( $functionName );
		}
	}

	/**
	 * Updates the object in the database.
	 *
	 * @since 1.20
	 *
	 * @param string|null $functionName
	 *
	 * @return boolean Success indicator
	 */
	protected function saveExisting( $functionName = null ) {
		$dbw = $this->table->getWriteDbConnection();

		$success = $dbw->update(
			$this->table->getName(),
			$this->getWriteValues(),
			$this->table->getPrefixedValues( $this->getUpdateConditions() ),
			is_null( $functionName ) ? __METHOD__ : $functionName
		);

		$this->table->releaseConnection( $dbw );

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

	/**
	 * Returns the WHERE considtions needed to identify this object so
	 * it can be updated.
	 *
	 * @since 1.20
	 *
	 * @return array
	 */
	protected function getUpdateConditions() {
		return array( 'id' => $this->getId() );
	}

	/**
	 * Inserts the object into the database.
	 *
	 * @since 1.20
	 *
	 * @param string|null $functionName
	 * @param array|null $options
	 *
	 * @return boolean Success indicator
	 */
	protected function insert( $functionName = null, array $options = null ) {
		$dbw = $this->table->getWriteDbConnection();

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

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

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

		$this->table->releaseConnection( $dbw );

		return $success;
	}

	/**
	 * Removes the object from the database.
	 *
	 * @since 1.20
	 *
	 * @return boolean Success indicator
	 */
	public function remove() {
		$this->beforeRemove();

		$success = $this->table->delete( array( 'id' => $this->getId() ), __METHOD__ );

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

		if ( $success ) {
			$this->onRemoved();
		}

		return $success;
	}

	/**
	 * Gets called before an object is removed from the database.
	 *
	 * @since 1.20
	 */
	protected function beforeRemove() {
		$this->loadFields( $this->getBeforeRemoveFields(), false, true );
	}

	/**
	 * Before removal of an object happens, @see beforeRemove gets called.
	 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
	 * This allows for loading info needed after removal to get rid of linked data and the like.
	 *
	 * @since 1.20
	 *
	 * @return array|null
	 */
	protected function getBeforeRemoveFields() {
		return array();
	}

	/**
	 * Gets called after successful removal.
	 * Can be overridden to get rid of linked data.
	 *
	 * @since 1.20
	 */
	protected function onRemoved() {
		$this->setField( 'id', null );
	}

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

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

	/**
	 * Sets the value of a field.
	 * Strings can be provided for other types,
	 * so this method can be called from unserialization handlers.
	 *
	 * @since 1.20
	 *
	 * @param string $name
	 * @param mixed $value
	 *
	 * @throws MWException
	 */
	public function setField( $name, $value ) {
		$fields = $this->table->getFields();

		if ( array_key_exists( $name, $fields ) ) {
			switch ( $fields[$name] ) {
				case 'int':
					$value = (int)$value;
					break;
				case 'float':
					$value = (float)$value;
					break;
				case 'bool':
					$value = (bool)$value;
					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;
			}

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

	/**
	 * Add an amount (can be negative) to the specified field (needs to be numeric).
	 * TODO: most off this stuff makes more sense in the table class
	 *
	 * @since 1.20
	 *
	 * @param string $field
	 * @param integer $amount
	 *
	 * @return boolean Success indicator
	 */
	public function addToField( $field, $amount ) {
		if ( $amount == 0 ) {
			return true;
		}

		if ( !$this->hasIdField() ) {
			return false;
		}

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

		$dbw = $this->table->getWriteDbConnection();

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

		$success = $dbw->update(
			$this->table->getName(),
			array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
			array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
			__METHOD__
		);

		if ( $success && $this->hasField( $field ) ) {
			$this->setField( $field, $this->getField( $field ) + $amount );
		}

		$this->table->releaseConnection( $dbw );

		return $success;
	}

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

	/**
	 * Computes and updates the values of the summary fields.
	 *
	 * @since 1.20
	 *
	 * @param array|string|null $summaryFields
	 */
	public function loadSummaryFields( $summaryFields = null ) {

	}

	/**
	 * Sets the value for the @see $updateSummaries field.
	 *
	 * @since 1.20
	 *
	 * @param boolean $update
	 */
	public function setUpdateSummaries( $update ) {
		$this->updateSummaries = $update;
	}

	/**
	 * Sets the value for the @see $inSummaryMode field.
	 *
	 * @since 1.20
	 *
	 * @param boolean $summaryMode
	 */
	public function setSummaryMode( $summaryMode ) {
		$this->inSummaryMode = $summaryMode;
	}

	/**
	 * Return if any fields got changed.
	 *
	 * @since 1.20
	 *
	 * @param IORMRow $object
	 * @param boolean|array $excludeSummaryFields
	 *  When set to true, summary field changes are ignored.
	 *  Can also be an array of fields to ignore.
	 *
	 * @return boolean
	 */
	protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
		$exclusionFields = array();

		if ( $excludeSummaryFields !== false ) {
			$exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
		}

		foreach ( $this->fields as $name => $value ) {
			$excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );

			if ( !$excluded && $object->getField( $name ) !== $value ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Returns the table this IORMRow is a row in.
	 *
	 * @since 1.20
	 *
	 * @return IORMTable
	 */
	public function getTable() {
		return $this->table;
	}

}