(bug 41796) follow-up for Ic9e728f8, release db connection in ORMRow
[lhc/web/wiklou.git] / includes / db / ORMRow.php
1 <?php
2 /**
3 * Abstract base class for representing objects that are stored in some DB table.
4 * This is basically an ORM-like wrapper around rows in database tables that
5 * aims to be both simple and very flexible. It is centered around an associative
6 * array of fields and various methods to do common interaction with the database.
7 *
8 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @since 1.20
26 *
27 * @file ORMRow.php
28 * @ingroup ORM
29 *
30 * @license GNU GPL v2 or later
31 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
32 */
33
34 abstract class ORMRow implements IORMRow {
35
36 /**
37 * The fields of the object.
38 * field name (w/o prefix) => value
39 *
40 * @since 1.20
41 * @var array
42 */
43 protected $fields = array( 'id' => null );
44
45 /**
46 * @since 1.20
47 * @var ORMTable
48 */
49 protected $table;
50
51 /**
52 * If the object should update summaries of linked items when changed.
53 * For example, update the course_count field in universities when a course in courses is deleted.
54 * Settings this to false can prevent needless updating work in situations
55 * such as deleting a university, which will then delete all it's courses.
56 *
57 * @since 1.20
58 * @var bool
59 */
60 protected $updateSummaries = true;
61
62 /**
63 * Indicates if the object is in summary mode.
64 * This mode indicates that only summary fields got updated,
65 * which allows for optimizations.
66 *
67 * @since 1.20
68 * @var bool
69 */
70 protected $inSummaryMode = false;
71
72 /**
73 * Constructor.
74 *
75 * @since 1.20
76 *
77 * @param IORMTable $table
78 * @param array|null $fields
79 * @param boolean $loadDefaults
80 */
81 public function __construct( IORMTable $table, $fields = null, $loadDefaults = false ) {
82 $this->table = $table;
83
84 if ( !is_array( $fields ) ) {
85 $fields = array();
86 }
87
88 if ( $loadDefaults ) {
89 $fields = array_merge( $this->table->getDefaults(), $fields );
90 }
91
92 $this->setFields( $fields );
93 }
94
95 /**
96 * Load the specified fields from the database.
97 *
98 * @since 1.20
99 *
100 * @param array|null $fields
101 * @param boolean $override
102 * @param boolean $skipLoaded
103 *
104 * @return bool Success indicator
105 */
106 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
107 if ( is_null( $this->getId() ) ) {
108 return false;
109 }
110
111 if ( is_null( $fields ) ) {
112 $fields = array_keys( $this->table->getFields() );
113 }
114
115 if ( $skipLoaded ) {
116 $fields = array_diff( $fields, array_keys( $this->fields ) );
117 }
118
119 if ( !empty( $fields ) ) {
120 $result = $this->table->rawSelectRow(
121 $this->table->getPrefixedFields( $fields ),
122 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
123 array( 'LIMIT' => 1 )
124 );
125
126 if ( $result !== false ) {
127 $this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
128 return true;
129 }
130 return false;
131 }
132
133 return true;
134 }
135
136 /**
137 * Gets the value of a field.
138 *
139 * @since 1.20
140 *
141 * @param $name string: Field name
142 * @param $default mixed: Default value to return when none is found
143 * (default: null)
144 *
145 * @throws MWException
146 * @return mixed
147 */
148 public function getField( $name, $default = null ) {
149 if ( $this->hasField( $name ) ) {
150 return $this->fields[$name];
151 } elseif ( !is_null( $default ) ) {
152 return $default;
153 } else {
154 throw new MWException( 'Attempted to get not-set field ' . $name );
155 }
156 }
157
158 /**
159 * Gets the value of a field but first loads it if not done so already.
160 *
161 * @since 1.20
162 *
163 * @param $name string
164 *
165 * @return mixed
166 */
167 public function loadAndGetField( $name ) {
168 if ( !$this->hasField( $name ) ) {
169 $this->loadFields( array( $name ) );
170 }
171
172 return $this->getField( $name );
173 }
174
175 /**
176 * Remove a field.
177 *
178 * @since 1.20
179 *
180 * @param string $name
181 */
182 public function removeField( $name ) {
183 unset( $this->fields[$name] );
184 }
185
186 /**
187 * Returns the objects database id.
188 *
189 * @since 1.20
190 *
191 * @return integer|null
192 */
193 public function getId() {
194 return $this->getField( 'id' );
195 }
196
197 /**
198 * Sets the objects database id.
199 *
200 * @since 1.20
201 *
202 * @param integer|null $id
203 */
204 public function setId( $id ) {
205 $this->setField( 'id', $id );
206 }
207
208 /**
209 * Gets if a certain field is set.
210 *
211 * @since 1.20
212 *
213 * @param string $name
214 *
215 * @return boolean
216 */
217 public function hasField( $name ) {
218 return array_key_exists( $name, $this->fields );
219 }
220
221 /**
222 * Gets if the id field is set.
223 *
224 * @since 1.20
225 *
226 * @return boolean
227 */
228 public function hasIdField() {
229 return $this->hasField( 'id' )
230 && !is_null( $this->getField( 'id' ) );
231 }
232
233 /**
234 * Sets multiple fields.
235 *
236 * @since 1.20
237 *
238 * @param array $fields The fields to set
239 * @param boolean $override Override already set fields with the provided values?
240 */
241 public function setFields( array $fields, $override = true ) {
242 foreach ( $fields as $name => $value ) {
243 if ( $override || !$this->hasField( $name ) ) {
244 $this->setField( $name, $value );
245 }
246 }
247 }
248
249 /**
250 * Gets the fields => values to write to the table.
251 *
252 * @since 1.20
253 *
254 * @return array
255 */
256 protected function getWriteValues() {
257 $values = array();
258
259 foreach ( $this->table->getFields() as $name => $type ) {
260 if ( array_key_exists( $name, $this->fields ) ) {
261 $value = $this->fields[$name];
262
263 switch ( $type ) {
264 case 'array':
265 $value = (array)$value;
266 case 'blob':
267 $value = serialize( $value );
268 }
269
270 $values[$this->table->getPrefixedField( $name )] = $value;
271 }
272 }
273
274 return $values;
275 }
276
277 /**
278 * Serializes the object to an associative array which
279 * can then easily be converted into JSON or similar.
280 *
281 * @since 1.20
282 *
283 * @param null|array $fields
284 * @param boolean $incNullId
285 *
286 * @return array
287 */
288 public function toArray( $fields = null, $incNullId = false ) {
289 $data = array();
290 $setFields = array();
291
292 if ( !is_array( $fields ) ) {
293 $setFields = $this->getSetFieldNames();
294 } else {
295 foreach ( $fields as $field ) {
296 if ( $this->hasField( $field ) ) {
297 $setFields[] = $field;
298 }
299 }
300 }
301
302 foreach ( $setFields as $field ) {
303 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
304 $data[$field] = $this->getField( $field );
305 }
306 }
307
308 return $data;
309 }
310
311 /**
312 * Load the default values, via getDefaults.
313 *
314 * @since 1.20
315 *
316 * @param boolean $override
317 */
318 public function loadDefaults( $override = true ) {
319 $this->setFields( $this->table->getDefaults(), $override );
320 }
321
322 /**
323 * Writes the answer to the database, either updating it
324 * when it already exists, or inserting it when it doesn't.
325 *
326 * @since 1.20
327 *
328 * @param string|null $functionName
329 *
330 * @return boolean Success indicator
331 */
332 public function save( $functionName = null ) {
333 if ( $this->hasIdField() ) {
334 return $this->saveExisting( $functionName );
335 } else {
336 return $this->insert( $functionName );
337 }
338 }
339
340 /**
341 * Updates the object in the database.
342 *
343 * @since 1.20
344 *
345 * @param string|null $functionName
346 *
347 * @return boolean Success indicator
348 */
349 protected function saveExisting( $functionName = null ) {
350 $dbw = $this->table->getWriteDbConnection();
351
352 $success = $dbw->update(
353 $this->table->getName(),
354 $this->getWriteValues(),
355 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
356 is_null( $functionName ) ? __METHOD__ : $functionName
357 );
358
359 $this->table->releaseConnection( $dbw );
360
361 // DatabaseBase::update does not always return true for success as documented...
362 return $success !== false;
363 }
364
365 /**
366 * Returns the WHERE considtions needed to identify this object so
367 * it can be updated.
368 *
369 * @since 1.20
370 *
371 * @return array
372 */
373 protected function getUpdateConditions() {
374 return array( 'id' => $this->getId() );
375 }
376
377 /**
378 * Inserts the object into the database.
379 *
380 * @since 1.20
381 *
382 * @param string|null $functionName
383 * @param array|null $options
384 *
385 * @return boolean Success indicator
386 */
387 protected function insert( $functionName = null, array $options = null ) {
388 $dbw = $this->table->getWriteDbConnection();
389
390 $success = $dbw->insert(
391 $this->table->getName(),
392 $this->getWriteValues(),
393 is_null( $functionName ) ? __METHOD__ : $functionName,
394 is_null( $options ) ? array( 'IGNORE' ) : $options
395 );
396
397 // DatabaseBase::insert does not always return true for success as documented...
398 $success = $success !== false;
399
400 if ( $success ) {
401 $this->setField( 'id', $dbw->insertId() );
402 }
403
404 $this->table->releaseConnection( $dbw );
405
406 return $success;
407 }
408
409 /**
410 * Removes the object from the database.
411 *
412 * @since 1.20
413 *
414 * @return boolean Success indicator
415 */
416 public function remove() {
417 $this->beforeRemove();
418
419 $success = $this->table->delete( array( 'id' => $this->getId() ) );
420
421 // DatabaseBase::delete does not always return true for success as documented...
422 $success = $success !== false;
423
424 if ( $success ) {
425 $this->onRemoved();
426 }
427
428 return $success;
429 }
430
431 /**
432 * Gets called before an object is removed from the database.
433 *
434 * @since 1.20
435 */
436 protected function beforeRemove() {
437 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
438 }
439
440 /**
441 * Before removal of an object happens, @see beforeRemove gets called.
442 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
443 * This allows for loading info needed after removal to get rid of linked data and the like.
444 *
445 * @since 1.20
446 *
447 * @return array|null
448 */
449 protected function getBeforeRemoveFields() {
450 return array();
451 }
452
453 /**
454 * Gets called after successfull removal.
455 * Can be overriden to get rid of linked data.
456 *
457 * @since 1.20
458 */
459 protected function onRemoved() {
460 $this->setField( 'id', null );
461 }
462
463 /**
464 * Return the names and values of the fields.
465 *
466 * @since 1.20
467 *
468 * @return array
469 */
470 public function getFields() {
471 return $this->fields;
472 }
473
474 /**
475 * Return the names of the fields.
476 *
477 * @since 1.20
478 *
479 * @return array
480 */
481 public function getSetFieldNames() {
482 return array_keys( $this->fields );
483 }
484
485 /**
486 * Sets the value of a field.
487 * Strings can be provided for other types,
488 * so this method can be called from unserialization handlers.
489 *
490 * @since 1.20
491 *
492 * @param string $name
493 * @param mixed $value
494 *
495 * @throws MWException
496 */
497 public function setField( $name, $value ) {
498 $fields = $this->table->getFields();
499
500 if ( array_key_exists( $name, $fields ) ) {
501 switch ( $fields[$name] ) {
502 case 'int':
503 $value = (int)$value;
504 break;
505 case 'float':
506 $value = (float)$value;
507 break;
508 case 'bool':
509 if ( is_string( $value ) ) {
510 $value = $value !== '0';
511 } elseif ( is_int( $value ) ) {
512 $value = $value !== 0;
513 }
514 break;
515 case 'array':
516 if ( is_string( $value ) ) {
517 $value = unserialize( $value );
518 }
519
520 if ( !is_array( $value ) ) {
521 $value = array();
522 }
523 break;
524 case 'blob':
525 if ( is_string( $value ) ) {
526 $value = unserialize( $value );
527 }
528 break;
529 case 'id':
530 if ( is_string( $value ) ) {
531 $value = (int)$value;
532 }
533 break;
534 }
535
536 $this->fields[$name] = $value;
537 } else {
538 throw new MWException( 'Attempted to set unknown field ' . $name );
539 }
540 }
541
542 /**
543 * Add an amount (can be negative) to the specified field (needs to be numeric).
544 * TODO: most off this stuff makes more sense in the table class
545 *
546 * @since 1.20
547 *
548 * @param string $field
549 * @param integer $amount
550 *
551 * @return boolean Success indicator
552 */
553 public function addToField( $field, $amount ) {
554 if ( $amount == 0 ) {
555 return true;
556 }
557
558 if ( !$this->hasIdField() ) {
559 return false;
560 }
561
562 $absoluteAmount = abs( $amount );
563 $isNegative = $amount < 0;
564
565 $dbw = $this->table->getWriteDbConnection();
566
567 $fullField = $this->table->getPrefixedField( $field );
568
569 $success = $dbw->update(
570 $this->table->getName(),
571 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
572 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
573 __METHOD__
574 );
575
576 if ( $success && $this->hasField( $field ) ) {
577 $this->setField( $field, $this->getField( $field ) + $amount );
578 }
579
580 $this->table->releaseConnection( $dbw );
581
582 return $success;
583 }
584
585 /**
586 * Return the names of the fields.
587 *
588 * @since 1.20
589 *
590 * @return array
591 */
592 public function getFieldNames() {
593 return array_keys( $this->table->getFields() );
594 }
595
596 /**
597 * Computes and updates the values of the summary fields.
598 *
599 * @since 1.20
600 *
601 * @param array|string|null $summaryFields
602 */
603 public function loadSummaryFields( $summaryFields = null ) {
604
605 }
606
607 /**
608 * Sets the value for the @see $updateSummaries field.
609 *
610 * @since 1.20
611 *
612 * @param boolean $update
613 */
614 public function setUpdateSummaries( $update ) {
615 $this->updateSummaries = $update;
616 }
617
618 /**
619 * Sets the value for the @see $inSummaryMode field.
620 *
621 * @since 1.20
622 *
623 * @param boolean $summaryMode
624 */
625 public function setSummaryMode( $summaryMode ) {
626 $this->inSummaryMode = $summaryMode;
627 }
628
629 /**
630 * Return if any fields got changed.
631 *
632 * @since 1.20
633 *
634 * @param IORMRow $object
635 * @param boolean|array $excludeSummaryFields
636 * When set to true, summary field changes are ignored.
637 * Can also be an array of fields to ignore.
638 *
639 * @return boolean
640 */
641 protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
642 $exclusionFields = array();
643
644 if ( $excludeSummaryFields !== false ) {
645 $exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
646 }
647
648 foreach ( $this->fields as $name => $value ) {
649 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
650
651 if ( !$excluded && $object->getField( $name ) !== $value ) {
652 return true;
653 }
654 }
655
656 return false;
657 }
658
659 /**
660 * Returns the table this IORMRow is a row in.
661 *
662 * @since 1.20
663 *
664 * @return IORMTable
665 */
666 public function getTable() {
667 return $this->table;
668 }
669
670 }