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.
8 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
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.
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.
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
30 * @license GNU GPL v2 or later
31 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
34 class ORMRow
implements IORMRow
{
37 * The fields of the object.
38 * field name (w/o prefix) => value
43 protected $fields = array( 'id' => null );
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.
60 protected $updateSummaries = true;
63 * Indicates if the object is in summary mode.
64 * This mode indicates that only summary fields got updated,
65 * which allows for optimizations.
70 protected $inSummaryMode = false;
77 * @param IORMTable $table
78 * @param array|null $fields
79 * @param boolean $loadDefaults
81 public function __construct( IORMTable
$table, $fields = null, $loadDefaults = false ) {
82 $this->table
= $table;
84 if ( !is_array( $fields ) ) {
88 if ( $loadDefaults ) {
89 $fields = array_merge( $this->table
->getDefaults(), $fields );
92 $this->setFields( $fields );
96 * Load the specified fields from the database.
100 * @param array|null $fields
101 * @param boolean $override
102 * @param boolean $skipLoaded
104 * @return bool Success indicator
106 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
107 if ( is_null( $this->getId() ) ) {
111 if ( is_null( $fields ) ) {
112 $fields = array_keys( $this->table
->getFields() );
116 $fields = array_diff( $fields, array_keys( $this->fields
) );
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 ),
127 if ( $result !== false ) {
128 $this->setFields( $this->table
->getFieldsFromDBResult( $result ), $override );
138 * Gets the value of a field.
142 * @param $name string: Field name
143 * @param $default mixed: Default value to return when none is found
146 * @throws MWException
149 public function getField( $name, $default = null ) {
150 if ( $this->hasField( $name ) ) {
151 return $this->fields
[$name];
152 } elseif ( !is_null( $default ) ) {
155 throw new MWException( 'Attempted to get not-set field ' . $name );
160 * Gets the value of a field but first loads it if not done so already.
164 * @param $name string
168 public function loadAndGetField( $name ) {
169 if ( !$this->hasField( $name ) ) {
170 $this->loadFields( array( $name ) );
173 return $this->getField( $name );
181 * @param string $name
183 public function removeField( $name ) {
184 unset( $this->fields
[$name] );
188 * Returns the objects database id.
192 * @return integer|null
194 public function getId() {
195 return $this->getField( 'id' );
199 * Sets the objects database id.
203 * @param integer|null $id
205 public function setId( $id ) {
206 $this->setField( 'id', $id );
210 * Gets if a certain field is set.
214 * @param string $name
218 public function hasField( $name ) {
219 return array_key_exists( $name, $this->fields
);
223 * Gets if the id field is set.
229 public function hasIdField() {
230 return $this->hasField( 'id' )
231 && !is_null( $this->getField( 'id' ) );
235 * Sets multiple fields.
239 * @param array $fields The fields to set
240 * @param boolean $override Override already set fields with the provided values?
242 public function setFields( array $fields, $override = true ) {
243 foreach ( $fields as $name => $value ) {
244 if ( $override ||
!$this->hasField( $name ) ) {
245 $this->setField( $name, $value );
251 * Gets the fields => values to write to the table.
257 protected function getWriteValues() {
260 foreach ( $this->table
->getFields() as $name => $type ) {
261 if ( array_key_exists( $name, $this->fields
) ) {
262 $value = $this->fields
[$name];
266 $value = (array)$value;
269 $value = serialize( $value );
273 $values[$this->table
->getPrefixedField( $name )] = $value;
281 * Serializes the object to an associative array which
282 * can then easily be converted into JSON or similar.
286 * @param null|array $fields
287 * @param boolean $incNullId
291 public function toArray( $fields = null, $incNullId = false ) {
293 $setFields = array();
295 if ( !is_array( $fields ) ) {
296 $setFields = $this->getSetFieldNames();
298 foreach ( $fields as $field ) {
299 if ( $this->hasField( $field ) ) {
300 $setFields[] = $field;
305 foreach ( $setFields as $field ) {
306 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
307 $data[$field] = $this->getField( $field );
315 * Load the default values, via getDefaults.
319 * @param boolean $override
321 public function loadDefaults( $override = true ) {
322 $this->setFields( $this->table
->getDefaults(), $override );
326 * Writes the answer to the database, either updating it
327 * when it already exists, or inserting it when it doesn't.
331 * @param string|null $functionName
333 * @return boolean Success indicator
335 public function save( $functionName = null ) {
336 if ( $this->hasIdField() ) {
337 return $this->saveExisting( $functionName );
339 return $this->insert( $functionName );
344 * Updates the object in the database.
348 * @param string|null $functionName
350 * @return boolean Success indicator
352 protected function saveExisting( $functionName = null ) {
353 $dbw = $this->table
->getWriteDbConnection();
355 $success = $dbw->update(
356 $this->table
->getName(),
357 $this->getWriteValues(),
358 $this->table
->getPrefixedValues( $this->getUpdateConditions() ),
359 is_null( $functionName ) ? __METHOD__
: $functionName
362 $this->table
->releaseConnection( $dbw );
364 // DatabaseBase::update does not always return true for success as documented...
365 return $success !== false;
369 * Returns the WHERE considtions needed to identify this object so
376 protected function getUpdateConditions() {
377 return array( 'id' => $this->getId() );
381 * Inserts the object into the database.
385 * @param string|null $functionName
386 * @param array|null $options
388 * @return boolean Success indicator
390 protected function insert( $functionName = null, array $options = null ) {
391 $dbw = $this->table
->getWriteDbConnection();
393 $success = $dbw->insert(
394 $this->table
->getName(),
395 $this->getWriteValues(),
396 is_null( $functionName ) ? __METHOD__
: $functionName,
400 // DatabaseBase::insert does not always return true for success as documented...
401 $success = $success !== false;
404 $this->setField( 'id', $dbw->insertId() );
407 $this->table
->releaseConnection( $dbw );
413 * Removes the object from the database.
417 * @return boolean Success indicator
419 public function remove() {
420 $this->beforeRemove();
422 $success = $this->table
->delete( array( 'id' => $this->getId() ), __METHOD__
);
424 // DatabaseBase::delete does not always return true for success as documented...
425 $success = $success !== false;
435 * Gets called before an object is removed from the database.
439 protected function beforeRemove() {
440 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
444 * Before removal of an object happens, @see beforeRemove gets called.
445 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
446 * This allows for loading info needed after removal to get rid of linked data and the like.
452 protected function getBeforeRemoveFields() {
457 * Gets called after successful removal.
458 * Can be overridden to get rid of linked data.
462 protected function onRemoved() {
463 $this->setField( 'id', null );
467 * Return the names and values of the fields.
473 public function getFields() {
474 return $this->fields
;
478 * Return the names of the fields.
484 public function getSetFieldNames() {
485 return array_keys( $this->fields
);
489 * Sets the value of a field.
490 * Strings can be provided for other types,
491 * so this method can be called from unserialization handlers.
495 * @param string $name
496 * @param mixed $value
498 * @throws MWException
500 public function setField( $name, $value ) {
501 $fields = $this->table
->getFields();
503 if ( array_key_exists( $name, $fields ) ) {
504 switch ( $fields[$name] ) {
506 $value = (int)$value;
509 $value = (float)$value;
512 if ( is_string( $value ) ) {
513 $value = $value !== '0';
514 } elseif ( is_int( $value ) ) {
515 $value = $value !== 0;
519 if ( is_string( $value ) ) {
520 $value = unserialize( $value );
523 if ( !is_array( $value ) ) {
528 if ( is_string( $value ) ) {
529 $value = unserialize( $value );
533 if ( is_string( $value ) ) {
534 $value = (int)$value;
539 $this->fields
[$name] = $value;
541 throw new MWException( 'Attempted to set unknown field ' . $name );
546 * Add an amount (can be negative) to the specified field (needs to be numeric).
547 * TODO: most off this stuff makes more sense in the table class
551 * @param string $field
552 * @param integer $amount
554 * @return boolean Success indicator
556 public function addToField( $field, $amount ) {
557 if ( $amount == 0 ) {
561 if ( !$this->hasIdField() ) {
565 $absoluteAmount = abs( $amount );
566 $isNegative = $amount < 0;
568 $dbw = $this->table
->getWriteDbConnection();
570 $fullField = $this->table
->getPrefixedField( $field );
572 $success = $dbw->update(
573 $this->table
->getName(),
574 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
575 array( $this->table
->getPrefixedField( 'id' ) => $this->getId() ),
579 if ( $success && $this->hasField( $field ) ) {
580 $this->setField( $field, $this->getField( $field ) +
$amount );
583 $this->table
->releaseConnection( $dbw );
589 * Return the names of the fields.
595 public function getFieldNames() {
596 return array_keys( $this->table
->getFields() );
600 * Computes and updates the values of the summary fields.
604 * @param array|string|null $summaryFields
606 public function loadSummaryFields( $summaryFields = null ) {
611 * Sets the value for the @see $updateSummaries field.
615 * @param boolean $update
617 public function setUpdateSummaries( $update ) {
618 $this->updateSummaries
= $update;
622 * Sets the value for the @see $inSummaryMode field.
626 * @param boolean $summaryMode
628 public function setSummaryMode( $summaryMode ) {
629 $this->inSummaryMode
= $summaryMode;
633 * Return if any fields got changed.
637 * @param IORMRow $object
638 * @param boolean|array $excludeSummaryFields
639 * When set to true, summary field changes are ignored.
640 * Can also be an array of fields to ignore.
644 protected function fieldsChanged( IORMRow
$object, $excludeSummaryFields = false ) {
645 $exclusionFields = array();
647 if ( $excludeSummaryFields !== false ) {
648 $exclusionFields = is_array( $excludeSummaryFields ) ?
$excludeSummaryFields : $this->table
->getSummaryFields();
651 foreach ( $this->fields
as $name => $value ) {
652 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
654 if ( !$excluded && $object->getField( $name ) !== $value ) {
663 * Returns the table this IORMRow is a row in.
669 public function getTable() {