4 * Abstract base class for representing objects that are stored in some DB table.
5 * This is basically an ORM-like wrapper around rows in database tables that
6 * aims to be both simple and very flexible. It is centered around an associative
7 * array of fields and various methods to do common interaction with the database.
9 * These methods must be implemented in deriving classes:
12 * These methods are likely candidates for overriding:
20 * Deriving classes must register their table and field prefix in $wgDBDataObjects.
21 * Syntax: $wgDBDataObjects['DrivingClassName'] = array( 'table' => 'table_name', 'prefix' => 'fieldprefix_' );
22 * Example: $wgDBDataObjects['EPOrg'] = array( 'table' => 'ep_orgs', 'prefix' => 'org_' );
24 * Main instance methods:
30 * Main static methods:
42 * @file DBDataObject.php
44 * @licence GNU GPL v3 or later
45 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
47 abstract class DBDataObject
{
50 * The fields of the object.
51 * field name (w/o prefix) => value
56 protected $fields = array( 'id' => null );
59 * If the object should update summaries of linked items when changed.
60 * For example, update the course_count field in universities when a course in courses is deleted.
61 * Settings this to false can prevent needless updating work in situations
62 * such as deleting a university, which will then delete all it's courses.
67 protected $updateSummaries = true;
70 * Indicates if the object is in summary mode.
71 * This mode indicates that only summary fields got updated,
72 * which allows for optimizations.
77 protected $inSummaryMode = false;
81 * The database connection to use for read operations.
82 * Can be changed via @see setReadDb.
85 * @var integer DB_ enum
87 protected static $readDb = DB_SLAVE
;
90 * Returns the name of the database table objects of this type are stored in.
97 public static function getDBTable() {
98 global $wgDBDataObjects;
99 if ( array_key_exists( get_called_class(), $wgDBDataObjects ) ) {
100 return $wgDBDataObjects[get_called_class()]['table'];
103 throw new MWException( 'Class "' . get_called_class() . '" not found in $wgDBDataObjects' );
108 * Gets the db field prefix.
112 * @throws MWException
115 protected static function getFieldPrefix() {
116 global $wgDBDataObjects;
117 if ( array_key_exists( get_called_class(), $wgDBDataObjects ) ) {
118 return $wgDBDataObjects[get_called_class()]['prefix'];
121 throw new MWException( 'Class "' . get_called_class() . '" not found in $wgDBDataObjects' );
126 * Returns an array with the fields and their types this object contains.
127 * This corresponds directly to the fields in the database, without prefix.
141 * @throws MWException
144 protected static function getFieldTypes() {
145 throw new MWException( 'Class did not implement getFieldTypes' );
149 * Returns a list of default field values.
150 * field name => field value
156 public static function getDefaults() {
161 * Returns a list of the summary fields.
162 * These are fields that cache computed values, such as the amount of linked objects of $type.
163 * This is relevant as one might not want to do actions such as log changes when these get updated.
169 public static function getSummaryFields() {
178 * @param array|null $fields
179 * @param boolean $loadDefaults
181 public function __construct( $fields = null, $loadDefaults = false ) {
182 if ( !is_array( $fields ) ) {
186 if ( $loadDefaults ) {
187 $fields = array_merge( $this->getDefaults(), $fields );
190 $this->setFields( $fields );
194 * Load the specified fields from the database.
198 * @param array|null $fields
199 * @param boolean $override
200 * @param boolean $skipLoaded
202 * @return Success indicator
204 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
205 if ( is_null( $this->getId() ) ) {
209 if ( is_null( $fields ) ) {
210 $fields = array_keys( $this->getFieldTypes() );
214 $loadedFields = array_keys( $this->fields
);
215 $fields = array_filter( $fields, function( $field ) use ( $loadedFields ) {
216 return !in_array( $field, $loadedFields );
220 if ( count( $fields ) > 0 ) {
221 $results = $this->rawSelect(
222 $this->getPrefixedFields( $fields ),
223 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
224 array( 'LIMIT' => 1 )
227 foreach ( $results as $result ) {
228 $this->setFields( $this->getFieldsFromDBResult( $result ), $override );
239 * Gets the value of a field.
243 * @param string $name
244 * @param mixed $default
246 * @throws MWException
249 public function getField( $name, $default = null ) {
250 if ( $this->hasField( $name ) ) {
251 return $this->fields
[$name];
252 } elseif ( !is_null( $default ) ) {
255 throw new MWException( 'Attempted to get not-set field ' . $name );
260 * Gets the value of a field but first loads it if not done so already.
268 public function loadAndGetField( $name ) {
269 if ( !$this->hasField( $name ) ) {
270 $this->loadFields( array( $name ) );
273 return $this->getField( $name );
281 * @param string $name
283 public function removeField( $name ) {
284 unset( $this->fields
[$name] );
288 * Returns the objects database id.
292 * @return integer|null
294 public function getId() {
295 return $this->getField( 'id' );
299 * Sets the objects database id.
303 * @param integer|null $id
305 public function setId( $id ) {
306 return $this->setField( 'id', $id );
310 * Gets if a certain field is set.
314 * @param string $name
318 public function hasField( $name ) {
319 return array_key_exists( $name, $this->fields
);
323 * Gets if the id field is set.
329 public function hasIdField() {
330 return $this->hasField( 'id' )
331 && !is_null( $this->getField( 'id' ) );
335 * Sets multiple fields.
339 * @param array $fields The fields to set
340 * @param boolean $override Override already set fields with the provided values?
342 public function setFields( array $fields, $override = true ) {
343 foreach ( $fields as $name => $value ) {
344 if ( $override ||
!$this->hasField( $name ) ) {
345 $this->setField( $name, $value );
351 * Gets the fields => values to write to the table.
357 protected function getWriteValues() {
360 foreach ( $this->getFieldTypes() as $name => $type ) {
361 if ( array_key_exists( $name, $this->fields
) ) {
362 $value = $this->fields
[$name];
366 $value = (array)$value;
368 $value = serialize( $value );
371 $values[$this->getFieldPrefix() . $name] = $value;
379 * Serializes the object to an associative array which
380 * can then easily be converted into JSON or similar.
384 * @param null|array $fields
385 * @param boolean $incNullId
389 public function toArray( $fields = null, $incNullId = false ) {
391 $setFields = array();
393 if ( !is_array( $fields ) ) {
394 $setFields = $this->getSetFieldNames();
396 foreach ( $fields as $field ) {
397 if ( $this->hasField( $field ) ) {
398 $setFields[] = $field;
403 foreach ( $setFields as $field ) {
404 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
405 $data[$field] = $this->getField( $field );
413 * Load the default values, via getDefaults.
417 * @param boolean $override
419 public function loadDefaults( $override = true ) {
420 $this->setFields( $this->getDefaults(), $override );
424 * Writes the answer to the database, either updating it
425 * when it already exists, or inserting it when it doesn't.
429 * @return boolean Success indicator
431 public function save() {
432 if ( $this->hasIdField() ) {
433 return $this->saveExisting();
435 return $this->insert();
440 * Updates the object in the database.
444 * @return boolean Success indicator
446 protected function saveExisting() {
447 $dbw = wfGetDB( DB_MASTER
);
449 $success = $dbw->update(
451 $this->getWriteValues(),
452 array( $this->getFieldPrefix() . 'id' => $this->getId() ),
460 * Inserts the object into the database.
464 * @return boolean Success indicator
466 protected function insert() {
467 $dbw = wfGetDB( DB_MASTER
);
469 $result = $dbw->insert(
471 $this->getWriteValues(),
477 $this->setField( 'id', $dbw->insertId() );
484 * Removes the object from the database.
488 * @return boolean Success indicator
490 public function remove() {
491 $this->beforeRemove();
493 $success = static::delete( array( 'id' => $this->getId() ) );
503 * Gets called before an object is removed from the database.
507 protected function beforeRemove() {
508 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
512 * Before removal of an object happens, @see beforeRemove gets called.
513 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
514 * This allows for loading info needed after removal to get rid of linked data and the like.
520 protected function getBeforeRemoveFields() {
525 * Gets called after successfull removal.
526 * Can be overriden to get rid of linked data.
530 protected function onRemoved() {
531 $this->setField( 'id', null );
535 * Return the names and values of the fields.
541 public function getFields() {
542 return $this->fields
;
546 * Return the names of the fields.
552 public function getSetFieldNames() {
553 return array_keys( $this->fields
);
557 * Sets the value of a field.
558 * Strings can be provided for other types,
559 * so this method can be called from unserialization handlers.
563 * @param string $name
564 * @param mixed $value
566 * @throws MWException
568 public function setField( $name, $value ) {
569 $fields = $this->getFieldTypes();
571 if ( array_key_exists( $name, $fields ) ) {
572 switch ( $fields[$name] ) {
574 $value = (int)$value;
577 $value = (float)$value;
580 if ( is_string( $value ) ) {
581 $value = $value !== '0';
582 } elseif ( is_int( $value ) ) {
583 $value = $value !== 0;
587 if ( is_string( $value ) ) {
588 $value = unserialize( $value );
591 if ( !is_array( $value ) ) {
596 if ( is_string( $value ) ) {
597 $value = unserialize( $value );
601 if ( is_string( $value ) ) {
602 $value = (int)$value;
607 $this->fields
[$name] = $value;
609 throw new MWException( 'Attempted to set unknown field ' . $name );
614 * Get a new instance of the class from an array.
619 * @param boolean $loadDefaults
621 * @return DBDataObject
623 public static function newFromArray( array $data, $loadDefaults = false ) {
624 return new static( $data, $loadDefaults );
628 * Get the database type used for read operations.
631 * @return integer DB_ enum
633 public static function getReadDb() {
634 return self
::$readDb;
638 * Set the database type to use for read operations.
644 public static function setReadDb( $db ) {
649 * Gets if the object can take a certain field.
653 * @param string $name
657 public static function canHasField( $name ) {
658 return array_key_exists( $name, static::getFieldTypes() );
662 * Takes in a field or array of fields and returns an
663 * array with their prefixed versions, ready for db usage.
667 * @param array|string $fields
671 public static function getPrefixedFields( array $fields ) {
672 foreach ( $fields as &$field ) {
673 $field = static::getPrefixedField( $field );
680 * Takes in a field and returns an it's prefixed version, ready for db usage.
681 * If the field needs to be prefixed for another table, provide an array in the form
682 * array( 'tablename', 'fieldname' )
683 * Where table name is registered in $wgDBDataObjects.
687 * @param string|array $field
690 * @throws MWException
692 public static function getPrefixedField( $field ) {
693 static $prefixes = false;
695 if ( $prefixes === false ) {
696 foreach ( $GLOBALS['wgDBDataObjects'] as $classInfo ) {
697 $prefixes[$classInfo['table']] = $classInfo['prefix'];
701 if ( is_array( $field ) && count( $field ) > 1 ) {
702 if ( array_key_exists( $field[0], $prefixes ) ) {
703 $prefix = $prefixes[$field[0]];
707 throw new MWException( 'Tried to prefix field with unknown table "' . $field[0] . '"' );
711 $prefix = static::getFieldPrefix();
714 return $prefix . $field;
718 * Takes in an associative array with field names as keys and
719 * their values as value. The field names are prefixed with the
722 * Field names can also be provided as an array with as first element a table name, such as
723 * $conditions = array(
724 * array( array( 'tablename', 'fieldname' ), $value ),
729 * @param array $values
733 public static function getPrefixedValues( array $values ) {
734 $prefixedValues = array();
736 foreach ( $values as $field => $value ) {
737 if ( is_integer( $field ) ) {
738 if ( is_array( $value ) ) {
743 $value = explode( ' ', $value, 2 );
744 $value[0] = static::getPrefixedField( $value[0] );
745 $prefixedValues[] = implode( ' ', $value );
750 $prefixedValues[static::getPrefixedField( $field )] = $value;
753 return $prefixedValues;
757 * Get an array with fields from a database result,
758 * that can be fed directly to the constructor or
763 * @param object $result
767 public static function getFieldsFromDBResult( $result ) {
768 $result = (array)$result;
769 return array_combine(
770 static::unprefixFieldNames( array_keys( $result ) ),
771 array_values( $result )
776 * Takes a field name with prefix and returns the unprefixed equivalent.
780 * @param string $fieldName
784 public static function unprefixFieldName( $fieldName ) {
785 return substr( $fieldName, strlen( static::getFieldPrefix() ) );
789 * Takes an array of field names with prefix and returns the unprefixed equivalent.
793 * @param array $fieldNames
797 public static function unprefixFieldNames( array $fieldNames ) {
798 return array_map( 'static::unprefixFieldName', $fieldNames );
802 * Get a new instance of the class from a database result.
806 * @param stdClass $result
808 * @return DBDataObject
810 public static function newFromDBResult( stdClass
$result ) {
811 return static::newFromArray( static::getFieldsFromDBResult( $result ) );
815 * Removes the object from the database.
819 * @param array $conditions
821 * @return boolean Success indicator
823 public static function delete( array $conditions ) {
824 return wfGetDB( DB_MASTER
)->delete(
825 static::getDBTable(),
826 static::getPrefixedValues( $conditions )
831 * Add an amount (can be negative) to the specified field (needs to be numeric).
835 * @param string $field
836 * @param integer $amount
838 * @return boolean Success indicator
840 public static function addToField( $field, $amount ) {
841 if ( $amount == 0 ) {
845 if ( !static::hasIdField() ) {
849 $absoluteAmount = abs( $amount );
850 $isNegative = $amount < 0;
852 $dbw = wfGetDB( DB_MASTER
);
854 $fullField = static::getPrefixedField( $field );
856 $success = $dbw->update(
857 static::getDBTable(),
858 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
859 array( static::getPrefixedField( 'id' ) => static::getId() ),
863 if ( $success && static::hasField( $field ) ) {
864 static::setField( $field, static::getField( $field ) +
$amount );
871 * Selects the the specified fields of the records matching the provided
872 * conditions and returns them as DBDataObject. Field names get prefixed.
876 * @param array|string|null $fields
877 * @param array $conditions
878 * @param array $options
879 * @param array $joinConds
881 * @return array of self
883 public static function select( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array() ) {
884 $result = static::selectFields( $fields, $conditions, $options, $joinConds, false );
888 foreach ( $result as $record ) {
889 $objects[] = static::newFromArray( $record );
896 * Selects the the specified fields of the records matching the provided
897 * conditions and returns them as associative arrays.
898 * Provided field names get prefixed.
899 * Returned field names will not have a prefix.
901 * When $collapse is true:
902 * If one field is selected, each item in the result array will be this field.
903 * If two fields are selected, each item in the result array will have as key
904 * the first field and as value the second field.
905 * If more then two fields are selected, each item will be an associative array.
909 * @param array|string|null $fields
910 * @param array $conditions
911 * @param array $options
912 * @param array $joinConds
913 * @param boolean $collapse Set to false to always return each result row as associative array.
915 * @return array of array
917 public static function selectFields( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array(), $collapse = true ) {
918 if ( is_null( $fields ) ) {
919 $fields = array_keys( static::getFieldTypes() );
922 $fields = (array)$fields;
925 $tables = array( static::getDBTable() );
926 $joinConds = static::getProcessedJoinConds( $joinConds, $tables );
928 $result = static::rawSelect(
929 static::getPrefixedFields( $fields ),
930 static::getPrefixedValues( $conditions ),
938 foreach ( $result as $record ) {
939 $objects[] = static::getFieldsFromDBResult( $record );
943 if ( count( $fields ) === 1 ) {
944 $objects = array_map( function( $object ) { return array_shift( $object ); } , $objects );
946 elseif ( count( $fields ) === 2 ) {
949 foreach ( $objects as $object ) {
950 $o[array_shift( $object )] = array_shift( $object );
961 * Process the join conditions. This includes prefixing table and field names,
962 * and adding of needed tables.
966 * @param array $joinConds Join conditions without prefixes and fields in array rather then string with equals sign.
967 * @param array $tables List of tables to which the extra needed ones get added.
969 * @return array Join conditions ready to be fed to MediaWikis native select function.
971 protected static function getProcessedJoinConds( array $joinConds, array &$tables ) {
974 foreach ( $joinConds as $table => $joinCond ) {
975 if ( !in_array( $table, $tables ) ) {
979 $cond = array( $joinCond[0], array() );
981 foreach ( $joinCond[1] as $joinCondPart ) {
983 static::getPrefixedField( $joinCondPart[0] ),
984 static::getPrefixedField( $joinCondPart[1] ),
987 if ( !in_array( $joinCondPart[0][0], $tables ) ) {
988 $tables[] = $joinCondPart[0][0];
991 if ( !in_array( $joinCondPart[1][0], $tables ) ) {
992 $tables[] = $joinCondPart[1][0];
995 $cond[1][] = implode( '=', $parts );
998 $conds[$table] = $cond;
1005 * Selects the the specified fields of the first matching record.
1006 * Field names get prefixed.
1010 * @param array|string|null $fields
1011 * @param array $conditions
1012 * @param array $options
1013 * @param array $joinConds
1015 * @return EPBObject|false
1017 public static function selectRow( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array() ) {
1018 $options['LIMIT'] = 1;
1020 $objects = static::select( $fields, $conditions, $options, $joinConds );
1022 return count( $objects ) > 0 ?
$objects[0] : false;
1026 * Selects the the specified fields of the first record matching the provided
1027 * conditions and returns it as an associative array, or false when nothing matches.
1028 * This method makes use of selectFields and expects the same parameters and
1029 * returns the same results (if there are any, if there are none, this method returns false).
1030 * @see DBDataObject::selectFields
1034 * @param array|string|null $fields
1035 * @param array $conditions
1036 * @param array $options
1037 * @param array $joinConds
1038 * @param boolean $collapse Set to false to always return each result row as associative array.
1040 * @return mixed|array|false
1042 public static function selectFieldsRow( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array(), $collapse = true ) {
1043 $options['LIMIT'] = 1;
1045 $objects = static::selectFields( $fields, $conditions, $options, $joinConds, $collapse );
1047 return count( $objects ) > 0 ?
$objects[0] : false;
1051 * Returns if there is at least one record matching the provided conditions.
1052 * Condition field names get prefixed.
1056 * @param array $conditions
1060 public static function has( array $conditions = array() ) {
1061 return static::selectRow( array( 'id' ), $conditions ) !== false;
1065 * Returns the amount of matching records.
1066 * Condition field names get prefixed.
1070 * @param array $conditions
1071 * @param array $options
1075 public static function count( array $conditions = array(), array $options = array() ) {
1076 $res = static::rawSelect(
1077 array( 'COUNT(*) AS rowcount' ),
1078 static::getPrefixedValues( $conditions ),
1082 return $res->rowcount
;
1086 * Selects the the specified fields of the records matching the provided
1087 * conditions. Field names do NOT get prefixed.
1091 * @param array $fields
1092 * @param array $conditions
1093 * @param array $options
1094 * @param array $joinConds
1095 * @param array $tables
1097 * @return ResultWrapper
1099 public static function rawSelect( array $fields, array $conditions = array(), array $options = array(), array $joinConds = array(), array $tables = null ) {
1100 if ( is_null( $tables ) ) {
1101 $tables = static::getDBTable();
1104 $dbr = wfGetDB( static::getReadDb() );
1106 return $dbr->select(
1109 count( $conditions ) == 0 ?
'' : $conditions,
1117 * Update the records matching the provided conditions by
1118 * setting the fields that are keys in the $values param to
1119 * their corresponding values.
1123 * @param array $values
1124 * @param array $conditions
1126 * @return boolean Success indicator
1128 public static function update( array $values, array $conditions = array() ) {
1129 $dbw = wfGetDB( DB_MASTER
);
1131 return $dbw->update(
1132 static::getDBTable(),
1133 static::getPrefixedValues( $values ),
1134 static::getPrefixedValues( $conditions ),
1140 * Return the names of the fields.
1146 public static function getFieldNames() {
1147 return array_keys( static::getFieldTypes() );
1151 * Returns an array with the fields and their descriptions.
1153 * field name => field description
1159 public static function getFieldDescriptions() {
1164 * Get API parameters for the fields supported by this object.
1168 * @param boolean $requireParams
1169 * @param boolean $setDefaults
1173 public static function getAPIParams( $requireParams = false, $setDefaults = false ) {
1179 'bool' => 'integer',
1180 'array' => 'string',
1185 $defaults = static::getDefaults();
1187 foreach ( static::getFieldTypes() as $field => $type ) {
1188 if ( $field == 'id' ) {
1192 $hasDefault = array_key_exists( $field, $defaults );
1194 $params[$field] = array(
1195 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
1196 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
1199 if ( $type == 'array' ) {
1200 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
1203 if ( $setDefaults && $hasDefault ) {
1204 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
1205 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
1213 * Computes and updates the values of the summary fields.
1217 * @param array|string|null $summaryFields
1219 public function loadSummaryFields( $summaryFields = null ) {
1224 * Computes the values of the summary fields of the objects matching the provided conditions.
1228 * @param array|string|null $summaryFields
1229 * @param array $conditions
1231 public static function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
1232 self
::setReadDb( DB_MASTER
);
1234 foreach ( self
::select( null, $conditions ) as /* DBDataObject */ $item ) {
1235 $item->loadSummaryFields( $summaryFields );
1236 $item->setSummaryMode( true );
1237 $item->saveExisting();
1240 self
::setReadDb( DB_SLAVE
);
1244 * Sets the value for the @see $updateSummaries field.
1248 * @param boolean $update
1250 public function setUpdateSummaries( $update ) {
1251 $this->updateSummaries
= $update;
1255 * Sets the value for the @see $inSummaryMode field.
1259 * @param boolean $update
1261 public function setSummaryMode( $summaryMode ) {
1262 $this->inSummaryMode
= $summaryMode;
1266 * Return if any fields got changed.
1270 * @param DBDataObject $object
1271 * @param boolean $excludeSummaryFields When set to true, summary field changes are ignored.
1275 protected function fieldsChanged( DBDataObject
$object, $excludeSummaryFields = false ) {
1276 foreach ( $this->fields
as $name => $value ) {
1277 $excluded = $excludeSummaryFields && in_array( $name, $this->getSummaryFields() );
1279 if ( !$excluded && $object->getField( $name ) !== $value ) {