]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Managed_DataObject.php
Merge branch 'tagprofile-ajax-fix' into 'nightly'
[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}'");
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     static function getByID($id)
350     {
351         if (empty($id)) {
352             throw new ServerException('Empty ID on lookup');
353         }
354         // getByPK throws exception if id is null
355         // or if the class does not have a single 'id' column as primary key
356         return static::getByPK(array('id' => $id));
357     }
358
359     /**
360      * Returns an ID, checked that it is set and reasonably valid
361      *
362      * If this dataobject uses a special id field (not 'id'), just
363      * implement your ID getting method in the child class.
364      *
365      * @return int ID of dataobject
366      * @throws Exception (when ID is not available or not set yet)
367      */
368     public function getID()
369     {
370         // FIXME: Make these exceptions more specific (their own classes)
371         if (!isset($this->id)) {
372             throw new Exception('No ID set.');
373         } elseif (empty($this->id)) {
374             throw new Exception('Empty ID for object! (not inserted yet?).');
375         }
376
377         // FIXME: How about forcing to return an int? Or will that overflow eventually?
378         return $this->id;
379     }
380
381     // 'update' won't write key columns, so we have to do it ourselves.
382     // This also automatically calls "update" _before_ it sets the keys.
383     // FIXME: This only works with single-column primary keys so far! Beware!
384     /**
385      * @param DB_DataObject &$orig  Must be "instanceof" $this
386      * @param string         $pid   Primary ID column (no escaping is done on column name!)
387      */
388     public function updateWithKeys(&$orig, $pid='id')
389     {
390         if (!$orig instanceof $this) {
391             throw new ServerException('Tried updating a DataObject with a different class than itself.');
392         }
393
394         // do it in a transaction
395         $this->query('BEGIN');
396
397         $parts = array();
398         foreach ($this->keys() as $k) {
399             if (strcmp($this->$k, $orig->$k) != 0) {
400                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
401             }
402         }
403         if (count($parts) == 0) {
404             // No changes to keys, it's safe to run ->update(...)
405             if ($this->update($orig) === false) {
406                 common_log_db_error($this, 'UPDATE', __FILE__);
407                 // rollback as something bad occurred
408                 $this->query('ROLLBACK');
409                 throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
410             }
411             $orig->decache();
412             $this->encache();
413
414             // commit our db transaction since we won't reach the COMMIT below
415             $this->query('COMMIT');
416             // @FIXME return true only if something changed (otherwise 0)
417             return true;
418         }
419
420         $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s = %4$s',
421                             common_database_tablename($this->tableName()),
422                             implode(', ', $parts),
423                             $pid,
424                             $this->_quote($this->$pid));
425
426         $result = $this->query($qry);
427         if ($result === false) {
428             common_log_db_error($this, 'UPDATE', __FILE__);
429             // rollback as something bad occurred
430             $this->query('ROLLBACK');
431             throw new ServerException("Could not UPDATE key fields for {$this->__table}");
432         }
433
434         // Update non-keys too, if the previous endeavour worked.
435         // The ->update call uses "$this" values for keys, that's why we can't do this until
436         // the keys are updated (because they might differ from $orig and update the wrong entries).
437         if ($this->update($orig) === false) {
438             common_log_db_error($this, 'UPDATE', __FILE__);
439             // rollback as something bad occurred
440             $this->query('ROLLBACK');
441             throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
442         }
443         $orig->decache();
444         $this->encache();
445
446         // commit our db transaction
447         $this->query('COMMIT');
448         // @FIXME return true only if something changed (otherwise 0)
449         return $result;
450     }
451
452     static public function beforeSchemaUpdate()
453     {
454         // NOOP
455     }
456 }