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);
67 static function pkeyCols()
69 return parent::pkeyColsClass(get_called_class());
73 * Get multiple items from the database by key
75 * @param string $keyCol name of column for key
76 * @param array $keyVals key values to fetch
77 * @param boolean $skipNulls return only non-null results?
79 * @return array Array of objects, in order
81 static function multiGet($keyCol, array $keyVals, $skipNulls=true)
83 return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
87 * Get multiple items from the database by key
89 * @param string $keyCol name of column for key
90 * @param array $keyVals key values to fetch
91 * @param array $otherCols Other columns to hold fixed
93 * @return array Array mapping $keyVals to objects, or null if not found
95 static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
97 return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
101 * Get a multi-instance object
103 * This is a utility method to get multiple instances with a given set of
104 * values for a specific column.
106 * @param string $keyCol key column name
107 * @param array $keyVals array of key values
109 * @return get_called_class() object with multiple instances if found,
110 * Exception is thrown when no entries are found.
113 static function listFind($keyCol, array $keyVals)
115 return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
119 * Get a multi-instance object separated into an array
121 * This is a utility method to get multiple instances with a given set of
122 * values for a specific key column. Usually used for the primary key when
123 * multiple values are desired. Result is an array.
125 * @param string $keyCol key column name
126 * @param array $keyVals array of key values
128 * @return array with an get_called_class() object for each $keyVals entry
131 static function listGet($keyCol, array $keyVals)
133 return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
137 * get/set an associative array of table columns
140 * @return array (associative)
142 public function table()
144 $table = static::schemaDef();
145 return array_map(array($this, 'columnBitmap'), $table['fields']);
149 * get/set an array of table primary keys
151 * Key info is pulled from the table definition array.
158 return array_keys($this->keyTypes());
164 * Returns the first serial column defined in the table, if any.
167 * @return array (column,use_native,sequence_name)
170 function sequenceKey()
172 $table = static::schemaDef();
173 foreach ($table['fields'] as $name => $column) {
174 if ($column['type'] == 'serial') {
175 // We have a serial/autoincrement column.
176 // Declare it to be a native sequence!
177 return array($name, true, false);
181 // No sequence key on this table.
182 return array(false, false, false);
186 * Return key definitions for DB_DataObject and Memcache_DataObject.
188 * DB_DataObject needs to know about keys that the table has; this function
191 * @return array key definitions
196 $table = static::schemaDef();
199 if (!empty($table['unique keys'])) {
200 foreach ($table['unique keys'] as $idx => $fields) {
201 foreach ($fields as $name) {
207 if (!empty($table['primary key'])) {
208 foreach ($table['primary key'] as $name) {
216 * Build the appropriate DB_DataObject bitfield map for this field.
218 * @param array $column
221 function columnBitmap($column)
223 $type = $column['type'];
225 // For quoting style...
226 $intTypes = array('int',
231 if (in_array($type, $intTypes)) {
232 $style = DB_DATAOBJECT_INT;
234 $style = DB_DATAOBJECT_STR;
237 // Data type formatting style...
238 $formatStyles = array('blob' => DB_DATAOBJECT_BLOB,
239 'text' => DB_DATAOBJECT_TXT,
240 'date' => DB_DATAOBJECT_DATE,
241 'time' => DB_DATAOBJECT_TIME,
242 'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
243 'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP);
245 if (isset($formatStyles[$type])) {
246 $style |= $formatStyles[$type];
250 if (!empty($column['not null'])) {
251 $style |= DB_DATAOBJECT_NOTNULL;
261 $table = static::schemaDef();
263 foreach ($table['foreign keys'] as $keyname => $keydef) {
264 if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
265 if (isset($keydef[1][0])) {
266 $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
274 * Return a list of all primary/unique keys / vals that will be used for
275 * caching. This will understand compound unique keys, which
276 * Memcached_DataObject doesn't have enough info to handle properly.
278 * @return array of strings
280 function _allCacheKeys()
282 $table = static::schemaDef();
285 if (!empty($table['unique keys'])) {
286 $keyNames = $table['unique keys'];
287 foreach ($keyNames as $idx => $fields) {
289 foreach ($fields as $name) {
290 $val[$name] = self::valueString($this->$name);
292 $ckeys[] = self::multicacheKey($this->tableName(), $val);
296 if (!empty($table['primary key'])) {
297 $fields = $table['primary key'];
299 foreach ($fields as $name) {
300 $val[$name] = self::valueString($this->$name);
302 $ckeys[] = self::multicacheKey($this->tableName(), $val);
307 public function escapedTableName()
309 return common_database_tablename($this->tableName());
313 * Returns an object by looking at the primary key column(s).
315 * Will require all primary key columns to be defined in an associative array
316 * and ignore any keys which are not part of the primary key.
318 * Will NOT accept NULL values as part of primary key.
320 * @param array $vals Must match all primary key columns for the dataobject.
322 * @return Managed_DataObject of the get_called_class() type
323 * @throws NoResultException if no object with that primary key
325 static function getByPK(array $vals)
327 $classname = get_called_class();
329 $pkey = static::pkeyCols();
330 if (is_null($pkey)) {
331 throw new ServerException("Failed to get primary key columns for class '{$classname}'");
334 $object = new $classname();
335 foreach ($pkey as $col) {
336 if (!array_key_exists($col, $vals)) {
337 throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
338 } elseif (is_null($vals[$col])) {
339 throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
341 $object->$col = $vals[$col];
343 if (!$object->find(true)) {
344 throw new NoResultException($object);
350 * Returns an object by looking at given unique key columns.
352 * Will NOT accept NULL values for a unique key column. Ignores non-key values.
354 * @param array $vals All array keys which are set must be non-null.
356 * @return Managed_DataObject of the get_called_class() type
357 * @throws NoResultException if no object with that primary key
359 static function getByKeys(array $vals)
361 $classname = get_called_class();
363 $object = new $classname();
365 $keys = $object->keys();
366 if (is_null($keys)) {
367 throw new ServerException("Failed to get key columns for class '{$classname}'");
370 foreach ($keys as $col) {
371 if (!array_key_exists($col, $vals)) {
373 } elseif (is_null($vals[$col])) {
374 throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
376 $object->$col = $vals[$col];
378 if (!$object->find(true)) {
379 throw new NoResultException($object);
384 static function getByID($id)
387 throw new EmptyIdException(get_called_class());
389 // getByPK throws exception if id is null
390 // or if the class does not have a single 'id' column as primary key
391 return static::getByPK(array('id' => $id));
395 * Returns an ID, checked that it is set and reasonably valid
397 * If this dataobject uses a special id field (not 'id'), just
398 * implement your ID getting method in the child class.
400 * @return int ID of dataobject
401 * @throws Exception (when ID is not available or not set yet)
403 public function getID()
405 // FIXME: Make these exceptions more specific (their own classes)
406 if (!isset($this->id)) {
407 throw new Exception('No ID set.');
408 } elseif (empty($this->id)) {
409 throw new Exception('Empty ID for object! (not inserted yet?).');
412 return intval($this->id);
415 // 'update' won't write key columns, so we have to do it ourselves.
416 // This also automatically calls "update" _before_ it sets the keys.
417 // FIXME: This only works with single-column primary keys so far! Beware!
419 * @param DB_DataObject &$orig Must be "instanceof" $this
420 * @param string $pid Primary ID column (no escaping is done on column name!)
422 public function updateWithKeys(Managed_DataObject $orig, $pid=null)
424 if (!$orig instanceof $this) {
425 throw new ServerException('Tried updating a DataObject with a different class than itself.');
429 throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
432 // do it in a transaction
433 $this->query('BEGIN');
436 foreach ($this->keys() as $k) {
437 if (strcmp($this->$k, $orig->$k) != 0) {
438 $parts[] = $k . ' = ' . $this->_quote($this->$k);
441 if (count($parts) == 0) {
442 // No changes to keys, it's safe to run ->update(...)
443 if ($this->update($orig) === false) {
444 common_log_db_error($this, 'UPDATE', __FILE__);
445 // rollback as something bad occurred
446 $this->query('ROLLBACK');
447 throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
452 // commit our db transaction since we won't reach the COMMIT below
453 $this->query('COMMIT');
454 // @FIXME return true only if something changed (otherwise 0)
459 $schema = static::schemaDef();
460 $pid = $schema['primary key'];
464 foreach((array)$pid as $pidCol) {
465 $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
467 if (empty($pidWhere)) {
468 throw new ServerException('No primary ID column(s) set for updateWithKeys');
471 $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s',
472 common_database_tablename($this->tableName()),
473 implode(', ', $parts),
474 implode(' AND ', $pidWhere));
476 $result = $this->query($qry);
477 if ($result === false) {
478 common_log_db_error($this, 'UPDATE', __FILE__);
479 // rollback as something bad occurred
480 $this->query('ROLLBACK');
481 throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
484 // Update non-keys too, if the previous endeavour worked.
485 // The ->update call uses "$this" values for keys, that's why we can't do this until
486 // the keys are updated (because they might differ from $orig and update the wrong entries).
487 if ($this->update($orig) === false) {
488 common_log_db_error($this, 'UPDATE', __FILE__);
489 // rollback as something bad occurred
490 $this->query('ROLLBACK');
491 throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
496 // commit our db transaction
497 $this->query('COMMIT');
498 // @FIXME return true only if something changed (otherwise 0)
502 static public function beforeSchemaUpdate()
507 static function newUri(Profile $actor, Managed_DataObject $object, $created=null)
509 if (is_null($created)) {
510 $created = common_sql_now();
512 return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
514 ActivityUtils::resolveUri($object->getObjectType(), true),
516 common_date_iso8601($created));
519 protected function onInsert()
524 protected function onUpdate($dataObject=false)
529 public function insert()
532 return parent::insert();
535 public function update($dataObject=false)
537 $this->onUpdate($dataObject);
538 return parent::update($dataObject);