3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * Wrapper for Memcached_DataObject which knows its own schema definition.
22 * Builds its own damn settings from a schema definition.
24 * @author Brion Vibber <brion@status.net>
26 abstract class Managed_DataObject extends Memcached_DataObject
29 * The One True Thingy that must be defined and declared.
31 public static function schemaDef()
33 throw new MethodNotImplementedException(__METHOD__);
37 * Get an instance by key
39 * @param string $k Key to use to lookup (usually 'id' for this class)
40 * @param mixed $v Value to lookup
42 * @return get_called_class() object if found, or null for no hits
45 static function getKV($k,$v=NULL)
47 return parent::getClassKV(get_called_class(), $k, $v);
51 * Get an instance by compound key
53 * This is a utility method to get a single instance with a given set of
54 * key-value pairs. Usually used for the primary key for a compound key; thus
57 * @param array $kv array of key-value mappings
59 * @return get_called_class() object if found, or null for no hits
62 static function pkeyGet(array $kv)
64 return parent::pkeyGetClass(get_called_class(), $kv);
68 * Get multiple items from the database by key
70 * @param string $keyCol name of column for key
71 * @param array $keyVals key values to fetch
72 * @param boolean $skipNulls return only non-null results?
74 * @return array Array of objects, in order
76 static function multiGet($keyCol, array $keyVals, $skipNulls=true)
78 return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
82 * Get multiple items from the database by key
84 * @param string $keyCol name of column for key
85 * @param array $keyVals key values to fetch
86 * @param array $otherCols Other columns to hold fixed
88 * @return array Array mapping $keyVals to objects, or null if not found
90 static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
92 return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
96 * Get a multi-instance object
98 * This is a utility method to get multiple instances with a given set of
99 * values for a specific column.
101 * @param string $keyCol key column name
102 * @param array $keyVals array of key values
104 * @return get_called_class() object with multiple instances if found,
105 * Exception is thrown when no entries are found.
108 static function listFind($keyCol, array $keyVals)
110 return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
114 * Get a multi-instance object separated into an array
116 * This is a utility method to get multiple instances with a given set of
117 * values for a specific key column. Usually used for the primary key when
118 * multiple values are desired. Result is an array.
120 * @param string $keyCol key column name
121 * @param array $keyVals array of key values
123 * @return array with an get_called_class() object for each $keyVals entry
126 static function listGet($keyCol, array $keyVals)
128 return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
132 * get/set an associative array of table columns
135 * @return array (associative)
137 public function table()
139 $table = static::schemaDef();
140 return array_map(array($this, 'columnBitmap'), $table['fields']);
144 * get/set an array of table primary keys
146 * Key info is pulled from the table definition array.
153 return array_keys($this->keyTypes());
159 * Returns the first serial column defined in the table, if any.
162 * @return array (column,use_native,sequence_name)
165 function sequenceKey()
167 $table = static::schemaDef();
168 foreach ($table['fields'] as $name => $column) {
169 if ($column['type'] == 'serial') {
170 // We have a serial/autoincrement column.
171 // Declare it to be a native sequence!
172 return array($name, true, false);
176 // No sequence key on this table.
177 return array(false, false, false);
181 * Return key definitions for DB_DataObject and Memcache_DataObject.
183 * DB_DataObject needs to know about keys that the table has; this function
186 * @return array key definitions
191 $table = static::schemaDef();
194 if (!empty($table['unique keys'])) {
195 foreach ($table['unique keys'] as $idx => $fields) {
196 foreach ($fields as $name) {
202 if (!empty($table['primary key'])) {
203 foreach ($table['primary key'] as $name) {
211 * Build the appropriate DB_DataObject bitfield map for this field.
213 * @param array $column
216 function columnBitmap($column)
218 $type = $column['type'];
220 // For quoting style...
221 $intTypes = array('int',
226 if (in_array($type, $intTypes)) {
227 $style = DB_DATAOBJECT_INT;
229 $style = DB_DATAOBJECT_STR;
232 // Data type formatting style...
233 $formatStyles = array('blob' => DB_DATAOBJECT_BLOB,
234 'text' => DB_DATAOBJECT_TXT,
235 'date' => DB_DATAOBJECT_DATE,
236 'time' => DB_DATAOBJECT_TIME,
237 'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
238 'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP);
240 if (isset($formatStyles[$type])) {
241 $style |= $formatStyles[$type];
245 if (!empty($column['not null'])) {
246 $style |= DB_DATAOBJECT_NOTNULL;
256 $table = static::schemaDef();
258 foreach ($table['foreign keys'] as $keyname => $keydef) {
259 if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
260 if (isset($keydef[1][0])) {
261 $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
269 * Return a list of all primary/unique keys / vals that will be used for
270 * caching. This will understand compound unique keys, which
271 * Memcached_DataObject doesn't have enough info to handle properly.
273 * @return array of strings
275 function _allCacheKeys()
277 $table = static::schemaDef();
280 if (!empty($table['unique keys'])) {
281 $keyNames = $table['unique keys'];
282 foreach ($keyNames as $idx => $fields) {
284 foreach ($fields as $name) {
285 $val[$name] = self::valueString($this->$name);
287 $ckeys[] = self::multicacheKey($this->tableName(), $val);
291 if (!empty($table['primary key'])) {
292 $fields = $table['primary key'];
294 foreach ($fields as $name) {
295 $val[$name] = self::valueString($this->$name);
297 $ckeys[] = self::multicacheKey($this->tableName(), $val);
302 public function escapedTableName()
304 return common_database_tablename($this->tableName());
308 * Returns an ID, checked that it is set and reasonably valid
310 * If this dataobject uses a special id field (not 'id'), just
311 * implement your ID getting method in the child class.
313 * @return int ID of dataobject
314 * @throws Exception (when ID is not available or not set yet)
316 public function getID()
318 // FIXME: Make these exceptions more specific (their own classes)
319 if (!isset($this->id)) {
320 throw new Exception('No ID set.');
321 } elseif (empty($this->id)) {
322 throw new Exception('Empty ID for object! (not inserted yet?).');
325 // FIXME: How about forcing to return an int? Or will that overflow eventually?
329 // 'update' won't write key columns, so we have to do it ourselves.
330 // This also automatically calls "update" _before_ it sets the keys.
331 // FIXME: This only works with single-column primary keys so far! Beware!
333 * @param DB_DataObject &$orig Must be "instanceof" $this
334 * @param string $pid Primary ID column (no escaping is done on column name!)
336 public function updateWithKeys(&$orig, $pid='id')
338 if (!$orig instanceof $this) {
339 throw new ServerException('Tried updating a DataObject with a different class than itself.');
342 // do it in a transaction
343 $this->query('BEGIN');
346 foreach ($this->keys() as $k) {
347 if (strcmp($this->$k, $orig->$k) != 0) {
348 $parts[] = $k . ' = ' . $this->_quote($this->$k);
351 if (count($parts) == 0) {
352 // No changes to keys, it's safe to run ->update(...)
353 if ($this->update($orig) === false) {
354 common_log_db_error($this, 'UPDATE', __FILE__);
355 // rollback as something bad occurred
356 $this->query('ROLLBACK');
357 throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
362 // commit our db transaction since we won't reach the COMMIT below
363 $this->query('COMMIT');
364 // @FIXME return true only if something changed (otherwise 0)
368 $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s = %4$s',
369 common_database_tablename($this->tableName()),
370 implode(', ', $parts),
372 $this->_quote($this->$pid));
374 $result = $this->query($qry);
375 if ($result === false) {
376 common_log_db_error($this, 'UPDATE', __FILE__);
377 // rollback as something bad occurred
378 $this->query('ROLLBACK');
379 throw new ServerException("Could not UPDATE key fields for {$this->__table}");
382 // Update non-keys too, if the previous endeavour worked.
383 // The ->update call uses "$this" values for keys, that's why we can't do this until
384 // the keys are updated (because they might differ from $orig and update the wrong entries).
385 if ($this->update($orig) === false) {
386 common_log_db_error($this, 'UPDATE', __FILE__);
387 // rollback as something bad occurred
388 $this->query('ROLLBACK');
389 throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
394 // commit our db transaction
395 $this->query('COMMIT');
396 // @FIXME return true only if something changed (otherwise 0)
400 static public function beforeSchemaUpdate()