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 $fields = array_diff( $fields, array_keys( $this->fields
) );
217 if ( count( $fields ) > 0 ) {
218 $results = $this->rawSelect(
219 $this->getPrefixedFields( $fields ),
220 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
221 array( 'LIMIT' => 1 )
224 foreach ( $results as $result ) {
225 $this->setFields( $this->getFieldsFromDBResult( $result ), $override );
236 * Gets the value of a field.
240 * @param string $name
241 * @param mixed $default
243 * @throws MWException
246 public function getField( $name, $default = null ) {
247 if ( $this->hasField( $name ) ) {
248 return $this->fields
[$name];
249 } elseif ( !is_null( $default ) ) {
252 throw new MWException( 'Attempted to get not-set field ' . $name );
257 * Gets the value of a field but first loads it if not done so already.
265 public function loadAndGetField( $name ) {
266 if ( !$this->hasField( $name ) ) {
267 $this->loadFields( array( $name ) );
270 return $this->getField( $name );
278 * @param string $name
280 public function removeField( $name ) {
281 unset( $this->fields
[$name] );
285 * Returns the objects database id.
289 * @return integer|null
291 public function getId() {
292 return $this->getField( 'id' );
296 * Sets the objects database id.
300 * @param integer|null $id
302 public function setId( $id ) {
303 return $this->setField( 'id', $id );
307 * Gets if a certain field is set.
311 * @param string $name
315 public function hasField( $name ) {
316 return array_key_exists( $name, $this->fields
);
320 * Gets if the id field is set.
326 public function hasIdField() {
327 return $this->hasField( 'id' )
328 && !is_null( $this->getField( 'id' ) );
332 * Sets multiple fields.
336 * @param array $fields The fields to set
337 * @param boolean $override Override already set fields with the provided values?
339 public function setFields( array $fields, $override = true ) {
340 foreach ( $fields as $name => $value ) {
341 if ( $override ||
!$this->hasField( $name ) ) {
342 $this->setField( $name, $value );
348 * Gets the fields => values to write to the table.
354 protected function getWriteValues() {
357 foreach ( $this->getFieldTypes() as $name => $type ) {
358 if ( array_key_exists( $name, $this->fields
) ) {
359 $value = $this->fields
[$name];
363 $value = (array)$value;
365 $value = serialize( $value );
368 $values[$this->getFieldPrefix() . $name] = $value;
376 * Serializes the object to an associative array which
377 * can then easily be converted into JSON or similar.
381 * @param null|array $fields
382 * @param boolean $incNullId
386 public function toArray( $fields = null, $incNullId = false ) {
388 $setFields = array();
390 if ( !is_array( $fields ) ) {
391 $setFields = $this->getSetFieldNames();
393 foreach ( $fields as $field ) {
394 if ( $this->hasField( $field ) ) {
395 $setFields[] = $field;
400 foreach ( $setFields as $field ) {
401 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
402 $data[$field] = $this->getField( $field );
410 * Load the default values, via getDefaults.
414 * @param boolean $override
416 public function loadDefaults( $override = true ) {
417 $this->setFields( $this->getDefaults(), $override );
421 * Writes the answer to the database, either updating it
422 * when it already exists, or inserting it when it doesn't.
426 * @return boolean Success indicator
428 public function save() {
429 if ( $this->hasIdField() ) {
430 return $this->saveExisting();
432 return $this->insert();
437 * Updates the object in the database.
441 * @return boolean Success indicator
443 protected function saveExisting() {
444 $dbw = wfGetDB( DB_MASTER
);
446 $success = $dbw->update(
448 $this->getWriteValues(),
449 array( $this->getFieldPrefix() . 'id' => $this->getId() ),
457 * Inserts the object into the database.
461 * @return boolean Success indicator
463 protected function insert() {
464 $dbw = wfGetDB( DB_MASTER
);
466 $result = $dbw->insert(
468 $this->getWriteValues(),
474 $this->setField( 'id', $dbw->insertId() );
481 * Removes the object from the database.
485 * @return boolean Success indicator
487 public function remove() {
488 $this->beforeRemove();
490 $success = static::delete( array( 'id' => $this->getId() ) );
500 * Gets called before an object is removed from the database.
504 protected function beforeRemove() {
505 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
509 * Before removal of an object happens, @see beforeRemove gets called.
510 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
511 * This allows for loading info needed after removal to get rid of linked data and the like.
517 protected function getBeforeRemoveFields() {
522 * Gets called after successfull removal.
523 * Can be overriden to get rid of linked data.
527 protected function onRemoved() {
528 $this->setField( 'id', null );
532 * Return the names and values of the fields.
538 public function getFields() {
539 return $this->fields
;
543 * Return the names of the fields.
549 public function getSetFieldNames() {
550 return array_keys( $this->fields
);
554 * Sets the value of a field.
555 * Strings can be provided for other types,
556 * so this method can be called from unserialization handlers.
560 * @param string $name
561 * @param mixed $value
563 * @throws MWException
565 public function setField( $name, $value ) {
566 $fields = $this->getFieldTypes();
568 if ( array_key_exists( $name, $fields ) ) {
569 switch ( $fields[$name] ) {
571 $value = (int)$value;
574 $value = (float)$value;
577 if ( is_string( $value ) ) {
578 $value = $value !== '0';
579 } elseif ( is_int( $value ) ) {
580 $value = $value !== 0;
584 if ( is_string( $value ) ) {
585 $value = unserialize( $value );
588 if ( !is_array( $value ) ) {
593 if ( is_string( $value ) ) {
594 $value = unserialize( $value );
598 if ( is_string( $value ) ) {
599 $value = (int)$value;
604 $this->fields
[$name] = $value;
606 throw new MWException( 'Attempted to set unknown field ' . $name );
611 * Get a new instance of the class from an array.
616 * @param boolean $loadDefaults
618 * @return DBDataObject
620 public static function newFromArray( array $data, $loadDefaults = false ) {
621 return new static( $data, $loadDefaults );
625 * Get the database type used for read operations.
628 * @return integer DB_ enum
630 public static function getReadDb() {
631 return self
::$readDb;
635 * Set the database type to use for read operations.
641 public static function setReadDb( $db ) {
646 * Gets if the object can take a certain field.
650 * @param string $name
654 public static function canHaveField( $name ) {
655 return array_key_exists( $name, static::getFieldTypes() );
659 * Takes in a field or array of fields and returns an
660 * array with their prefixed versions, ready for db usage.
664 * @param array|string $fields
668 public static function getPrefixedFields( array $fields ) {
669 foreach ( $fields as &$field ) {
670 $field = static::getPrefixedField( $field );
677 * Takes in a field and returns an it's prefixed version, ready for db usage.
678 * If the field needs to be prefixed for another table, provide an array in the form
679 * array( 'tablename', 'fieldname' )
680 * Where table name is registered in $wgDBDataObjects.
684 * @param string|array $field
687 * @throws MWException
689 public static function getPrefixedField( $field ) {
690 static $prefixes = false;
692 if ( $prefixes === false ) {
693 foreach ( $GLOBALS['wgDBDataObjects'] as $classInfo ) {
694 $prefixes[$classInfo['table']] = $classInfo['prefix'];
698 if ( is_array( $field ) && count( $field ) > 1 ) {
699 if ( array_key_exists( $field[0], $prefixes ) ) {
700 $prefix = $prefixes[$field[0]];
704 throw new MWException( 'Tried to prefix field with unknown table "' . $field[0] . '"' );
708 $prefix = static::getFieldPrefix();
711 return $prefix . $field;
715 * Takes in an associative array with field names as keys and
716 * their values as value. The field names are prefixed with the
719 * Field names can also be provided as an array with as first element a table name, such as
720 * $conditions = array(
721 * array( array( 'tablename', 'fieldname' ), $value ),
726 * @param array $values
730 public static function getPrefixedValues( array $values ) {
731 $prefixedValues = array();
733 foreach ( $values as $field => $value ) {
734 if ( is_integer( $field ) ) {
735 if ( is_array( $value ) ) {
740 $value = explode( ' ', $value, 2 );
741 $value[0] = static::getPrefixedField( $value[0] );
742 $prefixedValues[] = implode( ' ', $value );
747 $prefixedValues[static::getPrefixedField( $field )] = $value;
750 return $prefixedValues;
754 * Get an array with fields from a database result,
755 * that can be fed directly to the constructor or
760 * @param object $result
764 public static function getFieldsFromDBResult( $result ) {
765 $result = (array)$result;
766 return array_combine(
767 static::unprefixFieldNames( array_keys( $result ) ),
768 array_values( $result )
773 * Takes a field name with prefix and returns the unprefixed equivalent.
777 * @param string $fieldName
781 public static function unprefixFieldName( $fieldName ) {
782 return substr( $fieldName, strlen( static::getFieldPrefix() ) );
786 * Takes an array of field names with prefix and returns the unprefixed equivalent.
790 * @param array $fieldNames
794 public static function unprefixFieldNames( array $fieldNames ) {
795 return array_map( 'static::unprefixFieldName', $fieldNames );
799 * Get a new instance of the class from a database result.
803 * @param stdClass $result
805 * @return DBDataObject
807 public static function newFromDBResult( stdClass
$result ) {
808 return static::newFromArray( static::getFieldsFromDBResult( $result ) );
812 * Removes the object from the database.
816 * @param array $conditions
818 * @return boolean Success indicator
820 public static function delete( array $conditions ) {
821 return wfGetDB( DB_MASTER
)->delete(
822 static::getDBTable(),
823 static::getPrefixedValues( $conditions )
828 * Add an amount (can be negative) to the specified field (needs to be numeric).
832 * @param string $field
833 * @param integer $amount
835 * @return boolean Success indicator
837 public static function addToField( $field, $amount ) {
838 if ( $amount == 0 ) {
842 if ( !static::hasIdField() ) {
846 $absoluteAmount = abs( $amount );
847 $isNegative = $amount < 0;
849 $dbw = wfGetDB( DB_MASTER
);
851 $fullField = static::getPrefixedField( $field );
853 $success = $dbw->update(
854 static::getDBTable(),
855 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
856 array( static::getPrefixedField( 'id' ) => static::getId() ),
860 if ( $success && static::hasField( $field ) ) {
861 static::setField( $field, static::getField( $field ) +
$amount );
868 * Selects the the specified fields of the records matching the provided
869 * conditions and returns them as DBDataObject. Field names get prefixed.
873 * @param array|string|null $fields
874 * @param array $conditions
875 * @param array $options
876 * @param array $joinConds
878 * @return array of self
880 public static function select( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array() ) {
881 $result = static::selectFields( $fields, $conditions, $options, $joinConds, false );
885 foreach ( $result as $record ) {
886 $objects[] = static::newFromArray( $record );
893 * Selects the the specified fields of the records matching the provided
894 * conditions and returns them as associative arrays.
895 * Provided field names get prefixed.
896 * Returned field names will not have a prefix.
898 * When $collapse is true:
899 * If one field is selected, each item in the result array will be this field.
900 * If two fields are selected, each item in the result array will have as key
901 * the first field and as value the second field.
902 * If more then two fields are selected, each item will be an associative array.
906 * @param array|string|null $fields
907 * @param array $conditions
908 * @param array $options
909 * @param array $joinConds
910 * @param boolean $collapse Set to false to always return each result row as associative array.
912 * @return array of array
914 public static function selectFields( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array(), $collapse = true ) {
915 if ( is_null( $fields ) ) {
916 $fields = array_keys( static::getFieldTypes() );
919 $fields = (array)$fields;
922 $tables = array( static::getDBTable() );
923 $joinConds = static::getProcessedJoinConds( $joinConds, $tables );
925 $result = static::rawSelect(
926 static::getPrefixedFields( $fields ),
927 static::getPrefixedValues( $conditions ),
935 foreach ( $result as $record ) {
936 $objects[] = static::getFieldsFromDBResult( $record );
940 if ( count( $fields ) === 1 ) {
941 $objects = array_map( function( $object ) { return array_shift( $object ); } , $objects );
943 elseif ( count( $fields ) === 2 ) {
946 foreach ( $objects as $object ) {
947 $o[array_shift( $object )] = array_shift( $object );
958 * Process the join conditions. This includes prefixing table and field names,
959 * and adding of needed tables.
963 * @param array $joinConds Join conditions without prefixes and fields in array rather then string with equals sign.
964 * @param array $tables List of tables to which the extra needed ones get added.
966 * @return array Join conditions ready to be fed to MediaWikis native select function.
968 protected static function getProcessedJoinConds( array $joinConds, array &$tables ) {
971 foreach ( $joinConds as $table => $joinCond ) {
972 if ( !in_array( $table, $tables ) ) {
976 $cond = array( $joinCond[0], array() );
978 foreach ( $joinCond[1] as $joinCondPart ) {
980 static::getPrefixedField( $joinCondPart[0] ),
981 static::getPrefixedField( $joinCondPart[1] ),
984 if ( !in_array( $joinCondPart[0][0], $tables ) ) {
985 $tables[] = $joinCondPart[0][0];
988 if ( !in_array( $joinCondPart[1][0], $tables ) ) {
989 $tables[] = $joinCondPart[1][0];
992 $cond[1][] = implode( '=', $parts );
995 $conds[$table] = $cond;
1002 * Selects the the specified fields of the first matching record.
1003 * Field names get prefixed.
1007 * @param array|string|null $fields
1008 * @param array $conditions
1009 * @param array $options
1010 * @param array $joinConds
1012 * @return EPBObject|false
1014 public static function selectRow( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array() ) {
1015 $options['LIMIT'] = 1;
1017 $objects = static::select( $fields, $conditions, $options, $joinConds );
1019 return count( $objects ) > 0 ?
$objects[0] : false;
1023 * Selects the the specified fields of the first record matching the provided
1024 * conditions and returns it as an associative array, or false when nothing matches.
1025 * This method makes use of selectFields and expects the same parameters and
1026 * returns the same results (if there are any, if there are none, this method returns false).
1027 * @see DBDataObject::selectFields
1031 * @param array|string|null $fields
1032 * @param array $conditions
1033 * @param array $options
1034 * @param array $joinConds
1035 * @param boolean $collapse Set to false to always return each result row as associative array.
1037 * @return mixed|array|false
1039 public static function selectFieldsRow( $fields = null, array $conditions = array(), array $options = array(), array $joinConds = array(), $collapse = true ) {
1040 $options['LIMIT'] = 1;
1042 $objects = static::selectFields( $fields, $conditions, $options, $joinConds, $collapse );
1044 return count( $objects ) > 0 ?
$objects[0] : false;
1048 * Returns if there is at least one record matching the provided conditions.
1049 * Condition field names get prefixed.
1053 * @param array $conditions
1057 public static function has( array $conditions = array() ) {
1058 return static::selectRow( array( 'id' ), $conditions ) !== false;
1062 * Returns the amount of matching records.
1063 * Condition field names get prefixed.
1067 * @param array $conditions
1068 * @param array $options
1072 public static function count( array $conditions = array(), array $options = array() ) {
1073 $res = static::rawSelect(
1074 array( 'COUNT(*) AS rowcount' ),
1075 static::getPrefixedValues( $conditions ),
1079 return $res->rowcount
;
1083 * Selects the the specified fields of the records matching the provided
1084 * conditions. Field names do NOT get prefixed.
1088 * @param array $fields
1089 * @param array $conditions
1090 * @param array $options
1091 * @param array $joinConds
1092 * @param array $tables
1094 * @return ResultWrapper
1096 public static function rawSelect( array $fields, array $conditions = array(), array $options = array(), array $joinConds = array(), array $tables = null ) {
1097 if ( is_null( $tables ) ) {
1098 $tables = static::getDBTable();
1101 $dbr = wfGetDB( static::getReadDb() );
1103 return $dbr->select(
1106 count( $conditions ) == 0 ?
'' : $conditions,
1114 * Update the records matching the provided conditions by
1115 * setting the fields that are keys in the $values param to
1116 * their corresponding values.
1120 * @param array $values
1121 * @param array $conditions
1123 * @return boolean Success indicator
1125 public static function update( array $values, array $conditions = array() ) {
1126 $dbw = wfGetDB( DB_MASTER
);
1128 return $dbw->update(
1129 static::getDBTable(),
1130 static::getPrefixedValues( $values ),
1131 static::getPrefixedValues( $conditions ),
1137 * Return the names of the fields.
1143 public static function getFieldNames() {
1144 return array_keys( static::getFieldTypes() );
1148 * Returns an array with the fields and their descriptions.
1150 * field name => field description
1156 public static function getFieldDescriptions() {
1161 * Get API parameters for the fields supported by this object.
1165 * @param boolean $requireParams
1166 * @param boolean $setDefaults
1170 public static function getAPIParams( $requireParams = false, $setDefaults = false ) {
1176 'bool' => 'integer',
1177 'array' => 'string',
1182 $defaults = static::getDefaults();
1184 foreach ( static::getFieldTypes() as $field => $type ) {
1185 if ( $field == 'id' ) {
1189 $hasDefault = array_key_exists( $field, $defaults );
1191 $params[$field] = array(
1192 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
1193 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
1196 if ( $type == 'array' ) {
1197 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
1200 if ( $setDefaults && $hasDefault ) {
1201 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
1202 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
1210 * Computes and updates the values of the summary fields.
1214 * @param array|string|null $summaryFields
1216 public function loadSummaryFields( $summaryFields = null ) {
1221 * Computes the values of the summary fields of the objects matching the provided conditions.
1225 * @param array|string|null $summaryFields
1226 * @param array $conditions
1228 public static function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
1229 self
::setReadDb( DB_MASTER
);
1231 foreach ( self
::select( null, $conditions ) as /* DBDataObject */ $item ) {
1232 $item->loadSummaryFields( $summaryFields );
1233 $item->setSummaryMode( true );
1234 $item->saveExisting();
1237 self
::setReadDb( DB_SLAVE
);
1241 * Sets the value for the @see $updateSummaries field.
1245 * @param boolean $update
1247 public function setUpdateSummaries( $update ) {
1248 $this->updateSummaries
= $update;
1252 * Sets the value for the @see $inSummaryMode field.
1256 * @param boolean $update
1258 public function setSummaryMode( $summaryMode ) {
1259 $this->inSummaryMode
= $summaryMode;
1263 * Return if any fields got changed.
1267 * @param DBDataObject $object
1268 * @param boolean $excludeSummaryFields When set to true, summary field changes are ignored.
1272 protected function fieldsChanged( DBDataObject
$object, $excludeSummaryFields = false ) {
1273 foreach ( $this->fields
as $name => $value ) {
1274 $excluded = $excludeSummaryFields && in_array( $name, $this->getSummaryFields() );
1276 if ( !$excluded && $object->getField( $name ) !== $value ) {