]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Managed_DataObject.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / classes / Managed_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 /**
21  * Wrapper for Memcached_DataObject which knows its own schema definition.
22  * Builds its own damn settings from a schema definition.
23  *
24  * @author Brion Vibber <brion@status.net>
25  */
26 abstract class Managed_DataObject extends Memcached_DataObject
27 {
28     /**
29      * The One True Thingy that must be defined and declared.
30      */
31     public static function schemaDef()
32     {
33         throw new MethodNotImplementedException(__METHOD__);
34     }
35
36     /**
37      * Get an instance by key
38      *
39      * @param string $k Key to use to lookup (usually 'id' for this class)
40      * @param mixed  $v Value to lookup
41      *
42      * @return get_called_class() object if found, or null for no hits
43      *
44      */
45     static function getKV($k,$v=NULL)
46     {
47         return parent::getClassKV(get_called_class(), $k, $v);
48     }
49
50     /**
51      * Get an instance by compound key
52      *
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
55      * the name.
56      *
57      * @param array $kv array of key-value mappings
58      *
59      * @return get_called_class() object if found, or null for no hits
60      *
61      */
62     static function pkeyGet(array $kv)
63     {
64         return parent::pkeyGetClass(get_called_class(), $kv);
65     }
66
67     static function pkeyCols()
68     {
69         return parent::pkeyColsClass(get_called_class());
70     }
71
72     /**
73      * Get multiple items from the database by key
74      *
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?
78      *
79      * @return array Array of objects, in order
80      */
81         static function multiGet($keyCol, array $keyVals, $skipNulls=true)
82         {
83             return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
84         }
85
86     /**
87      * Get multiple items from the database by key
88      *
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
92      *
93      * @return array Array mapping $keyVals to objects, or null if not found
94      */
95         static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
96         {
97             return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
98         }
99
100     /**
101      * Get a multi-instance object
102      *
103      * This is a utility method to get multiple instances with a given set of
104      * values for a specific column.
105      *
106      * @param string $keyCol  key column name
107      * @param array  $keyVals array of key values
108      *
109      * @return get_called_class() object with multiple instances if found,
110      *         Exception is thrown when no entries are found.
111      *
112      */
113     static function listFind($keyCol, array $keyVals)
114     {
115         return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
116     }
117
118     /**
119      * Get a multi-instance object separated into an array
120      *
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.
124      *
125      * @param string $keyCol  key column name
126      * @param array  $keyVals array of key values
127      *
128      * @return array with an get_called_class() object for each $keyVals entry
129      *
130      */
131     static function listGet($keyCol, array $keyVals)
132     {
133         return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
134     }
135
136     /**
137      * get/set an associative array of table columns
138      *
139      * @access public
140      * @return array (associative)
141      */
142     public function table()
143     {
144         $table = static::schemaDef();
145         return array_map(array($this, 'columnBitmap'), $table['fields']);
146     }
147
148     /**
149      * get/set an  array of table primary keys
150      *
151      * Key info is pulled from the table definition array.
152      * 
153      * @access private
154      * @return array
155      */
156     function keys()
157     {
158         return array_keys($this->keyTypes());
159     }
160
161     /**
162      * Get a sequence key
163      *
164      * Returns the first serial column defined in the table, if any.
165      *
166      * @access private
167      * @return array (column,use_native,sequence_name)
168      */
169
170     function sequenceKey()
171     {
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);
178             }
179         }
180
181         // No sequence key on this table.
182         return array(false, false, false);
183     }
184
185     /**
186      * Return key definitions for DB_DataObject and Memcache_DataObject.
187      *
188      * DB_DataObject needs to know about keys that the table has; this function
189      * defines them.
190      *
191      * @return array key definitions
192      */
193
194     function keyTypes()
195     {
196         $table = static::schemaDef();
197         $keys = array();
198
199         if (!empty($table['unique keys'])) {
200             foreach ($table['unique keys'] as $idx => $fields) {
201                 foreach ($fields as $name) {
202                     $keys[$name] = 'U';
203                 }
204             }
205         }
206
207         if (!empty($table['primary key'])) {
208             foreach ($table['primary key'] as $name) {
209                 $keys[$name] = 'K';
210             }
211         }
212         return $keys;
213     }
214
215     /**
216      * Build the appropriate DB_DataObject bitfield map for this field.
217      *
218      * @param array $column
219      * @return int
220      */
221     function columnBitmap($column)
222     {
223         $type = $column['type'];
224
225         // For quoting style...
226         $intTypes = array('int',
227                           'integer',
228                           'float',
229                           'serial',
230                           'numeric');
231         if (in_array($type, $intTypes)) {
232             $style = DB_DATAOBJECT_INT;
233         } else {
234             $style = DB_DATAOBJECT_STR;
235         }
236
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);
244
245         if (isset($formatStyles[$type])) {
246             $style |= $formatStyles[$type];
247         }
248
249         // Nullable?
250         if (!empty($column['not null'])) {
251             $style |= DB_DATAOBJECT_NOTNULL;
252         }
253
254         return $style;
255     }
256
257     function links()
258     {
259         $links = array();
260
261         $table = static::schemaDef();
262
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];
267                 }
268             }
269         }
270         return $links;
271     }
272
273     /**
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.
277      *
278      * @return array of strings
279      */
280     function _allCacheKeys()
281     {
282         $table = static::schemaDef();
283         $ckeys = array();
284
285         if (!empty($table['unique keys'])) {
286             $keyNames = $table['unique keys'];
287             foreach ($keyNames as $idx => $fields) {
288                 $val = array();
289                 foreach ($fields as $name) {
290                     $val[$name] = self::valueString($this->$name);
291                 }
292                 $ckeys[] = self::multicacheKey($this->tableName(), $val);
293             }
294         }
295
296         if (!empty($table['primary key'])) {
297             $fields = $table['primary key'];
298             $val = array();
299             foreach ($fields as $name) {
300                 $val[$name] = self::valueString($this->$name);
301             }
302             $ckeys[] = self::multicacheKey($this->tableName(), $val);
303         }
304         return $ckeys;
305     }
306
307     public function escapedTableName()
308     {
309         return common_database_tablename($this->tableName());
310     }
311
312     /**
313      * Returns an object by looking at the primary key column(s).
314      *
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.
317      *
318      * Will NOT accept NULL values as part of primary key.
319      *
320      * @param   array   $vals       Must match all primary key columns for the dataobject.
321      *
322      * @return  Managed_DataObject  of the get_called_class() type
323      * @throws  NoResultException   if no object with that primary key
324      */
325     static function getByPK(array $vals)
326     {
327         $classname = get_called_class();
328
329         $pkey = static::pkeyCols();
330         if (is_null($pkey)) {
331             throw new ServerException("Failed to get primary key columns for class '{$classname}'");
332         }
333
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}'");
340             }
341             $object->$col = $vals[$col];
342         }
343         if (!$object->find(true)) {
344             throw new NoResultException($object);
345         }
346         return $object;
347     }
348
349     /**
350      * Returns an object by looking at given unique key columns.
351      *
352      * Will NOT accept NULL values for a unique key column. Ignores non-key values.
353      *
354      * @param   array   $vals       All array keys which are set must be non-null.
355      *
356      * @return  Managed_DataObject  of the get_called_class() type
357      * @throws  NoResultException   if no object with that primary key
358      */
359     static function getByKeys(array $vals)
360     {
361         $classname = get_called_class();
362
363         $object = new $classname();
364
365         $keys = $object->keys();
366         if (is_null($keys)) {
367             throw new ServerException("Failed to get key columns for class '{$classname}'");
368         }
369
370         foreach ($keys as $col) {
371             if (!array_key_exists($col, $vals)) {
372                 continue;
373             } elseif (is_null($vals[$col])) {
374                 throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
375             }
376             $object->$col = $vals[$col];
377         }
378         if (!$object->find(true)) {
379             throw new NoResultException($object);
380         }
381         return $object;
382     }
383
384     static function getByID($id)
385     {
386         if (empty($id)) {
387             throw new ServerException('Empty ID on lookup');
388         }
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));
392     }
393
394     /**
395      * Returns an ID, checked that it is set and reasonably valid
396      *
397      * If this dataobject uses a special id field (not 'id'), just
398      * implement your ID getting method in the child class.
399      *
400      * @return int ID of dataobject
401      * @throws Exception (when ID is not available or not set yet)
402      */
403     public function getID()
404     {
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?).');
410         }
411
412         // FIXME: How about forcing to return an int? Or will that overflow eventually?
413         return $this->id;
414     }
415
416     // 'update' won't write key columns, so we have to do it ourselves.
417     // This also automatically calls "update" _before_ it sets the keys.
418     // FIXME: This only works with single-column primary keys so far! Beware!
419     /**
420      * @param DB_DataObject &$orig  Must be "instanceof" $this
421      * @param string         $pid   Primary ID column (no escaping is done on column name!)
422      */
423     public function updateWithKeys(&$orig, $pid='id')
424     {
425         if (!$orig instanceof $this) {
426             throw new ServerException('Tried updating a DataObject with a different class than itself.');
427         }
428
429         // do it in a transaction
430         $this->query('BEGIN');
431
432         $parts = array();
433         foreach ($this->keys() as $k) {
434             if (strcmp($this->$k, $orig->$k) != 0) {
435                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
436             }
437         }
438         if (count($parts) == 0) {
439             // No changes to keys, it's safe to run ->update(...)
440             if ($this->update($orig) === false) {
441                 common_log_db_error($this, 'UPDATE', __FILE__);
442                 // rollback as something bad occurred
443                 $this->query('ROLLBACK');
444                 throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
445             }
446             $orig->decache();
447             $this->encache();
448
449             // commit our db transaction since we won't reach the COMMIT below
450             $this->query('COMMIT');
451             // @FIXME return true only if something changed (otherwise 0)
452             return true;
453         }
454
455         $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s = %4$s',
456                             common_database_tablename($this->tableName()),
457                             implode(', ', $parts),
458                             $pid,
459                             $this->_quote($this->$pid));
460
461         $result = $this->query($qry);
462         if ($result === false) {
463             common_log_db_error($this, 'UPDATE', __FILE__);
464             // rollback as something bad occurred
465             $this->query('ROLLBACK');
466             throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
467         }
468
469         // Update non-keys too, if the previous endeavour worked.
470         // The ->update call uses "$this" values for keys, that's why we can't do this until
471         // the keys are updated (because they might differ from $orig and update the wrong entries).
472         if ($this->update($orig) === false) {
473             common_log_db_error($this, 'UPDATE', __FILE__);
474             // rollback as something bad occurred
475             $this->query('ROLLBACK');
476             throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
477         }
478         $orig->decache();
479         $this->encache();
480
481         // commit our db transaction
482         $this->query('COMMIT');
483         // @FIXME return true only if something changed (otherwise 0)
484         return $result;
485     }
486
487     static public function beforeSchemaUpdate()
488     {
489         // NOOP
490     }
491
492     static function newUri(Profile $actor, Managed_DataObject $object, $created=null)
493     {
494         if (is_null($created)) {
495             $created = common_sql_now();
496         }
497         return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
498                                         $actor->getID(),
499                                         ActivityUtils::resolveUri($object->getObjectType(), true),
500                                         $object->getID(),
501                                         common_date_iso8601($created));
502     }
503 }