]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
New Managed_DataObject retrieval: listFind
[quix0rs-gnu-social.git] / classes / Memcached_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, 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 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 class Memcached_DataObject extends Safe_DataObject
23 {
24     /**
25      * Wrapper for DB_DataObject's static lookup using memcached
26      * as backing instead of an in-process cache array.
27      *
28      * @param string $cls classname of object type to load
29      * @param mixed $k key field name, or value for primary key
30      * @param mixed $v key field value, or leave out for primary key lookup
31      * @return mixed Memcached_DataObject subtype or false
32      */
33     static function getClassKV($cls, $k, $v=null)
34     {
35         if (!is_a($cls, __CLASS__, true)) {
36             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
37         }
38         if (is_null($v)) {
39             $v = $k;
40             $keys = self::pkeyCols($cls);
41             if (count($keys) > 1) {
42                 // FIXME: maybe call pkeyGetClass() ourselves?
43                 throw new Exception('Use pkeyGetClass() for compound primary keys');
44             }
45             $k = $keys[0];
46         }
47         $i = self::getcached($cls, $k, $v);
48         if ($i === false) { // false == cache miss
49             $i = new $cls;
50             $result = $i->get($k, $v);
51             if ($result) {
52                 // Hit!
53                 $i->encache();
54             } else {
55                 // save the fact that no such row exists
56                 $c = self::memcache();
57                 if (!empty($c)) {
58                     $ck = self::cachekey($cls, $k, $v);
59                     $c->set($ck, null);
60                 }
61                 $i = false;
62             }
63         }
64         return $i;
65     }
66
67     /**
68      * Get multiple items from the database by key
69      *
70      * @param string  $cls       Class to fetch
71      * @param string  $keyCol    name of column for key
72      * @param array   $keyVals   key values to fetch
73      * @param boolean $skipNulls return only non-null results?
74      *
75      * @return array Array of objects, in order
76      */
77     static function multiGetClass($cls, $keyCol, array $keyVals, $skipNulls=true)
78     {
79         $result = self::pivotGetClass($cls, $keyCol, $keyVals);
80
81         $values = array_values($result);
82
83         if ($skipNulls) {
84             $tmp = array();
85             foreach ($values as $value) {
86                 if (!empty($value)) {
87                     $tmp[] = $value;
88                 }
89             }
90             $values = $tmp;
91         }
92
93         return new ArrayWrapper($values);
94     }
95
96     /**
97      * Get multiple items from the database by key
98      *
99      * @param string  $cls       Class to fetch
100      * @param string  $keyCol    name of column for key
101      * @param array   $keyVals   key values to fetch
102      * @param boolean $otherCols Other columns to hold fixed
103      *
104      * @return array Array mapping $keyVals to objects, or null if not found
105      */
106     static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
107     {
108         if (!is_a($cls, __CLASS__, true)) {
109             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
110         }
111         if (is_array($keyCol)) {
112             foreach ($keyVals as $keyVal) {
113                 $result[implode(',', $keyVal)] = null;
114             }
115         } else {
116             $result = array_fill_keys($keyVals, null);
117         }
118
119         $toFetch = array();
120
121         foreach ($keyVals as $keyVal) {
122
123             if (is_array($keyCol)) {
124                 $kv = array_combine($keyCol, $keyVal);
125             } else {
126                 $kv = array($keyCol => $keyVal);
127             }
128
129             $kv = array_merge($otherCols, $kv);
130
131             $i = self::multicache($cls, $kv);
132
133             if ($i !== false) {
134                 if (is_array($keyCol)) {
135                     $result[implode(',', $keyVal)] = $i;
136                 } else {
137                     $result[$keyVal] = $i;
138                 }
139             } else if (!empty($keyVal)) {
140                 $toFetch[] = $keyVal;
141             }
142         }
143
144         if (count($toFetch) > 0) {
145             $i = new $cls;
146             foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
147                 $i->$otherKeyCol = $otherKeyVal;
148             }
149             if (is_array($keyCol)) {
150                 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
151             } else {
152                 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
153             }
154             if ($i->find()) {
155                 while ($i->fetch()) {
156                     $copy = clone($i);
157                     $copy->encache();
158                     if (is_array($keyCol)) {
159                         $vals = array();
160                         foreach ($keyCol as $k) {
161                             $vals[] = $i->$k;
162                         }
163                         $result[implode(',', $vals)] = $copy;
164                     } else {
165                         $result[$i->$keyCol] = $copy;
166                     }
167                 }
168             }
169
170             // Save state of DB misses
171
172             foreach ($toFetch as $keyVal) {
173                 $r = null;
174                 if (is_array($keyCol)) {
175                     $r = $result[implode(',', $keyVal)];
176                 } else {
177                     $r = $result[$keyVal];
178                 }
179                 if (empty($r)) {
180                     if (is_array($keyCol)) {
181                         $kv = array_combine($keyCol, $keyVal);
182                     } else {
183                         $kv = array($keyCol => $keyVal);
184                     }
185                     $kv = array_merge($otherCols, $kv);
186                     // save the fact that no such row exists
187                     $c = self::memcache();
188                     if (!empty($c)) {
189                         $ck = self::multicacheKey($cls, $kv);
190                         $c->set($ck, null);
191                     }
192                 }
193             }
194         }
195
196         return $result;
197     }
198
199     static function _inMultiKey($i, $cols, $values)
200     {
201         $types = array();
202
203         foreach ($cols as $col) {
204             $types[$col] = $i->columnType($col);
205         }
206
207         $first = true;
208
209         $query = '';
210
211         foreach ($values as $value) {
212             if ($first) {
213                 $query .= '( ';
214                 $first = false;
215             } else {
216                 $query .= ' OR ';
217             }
218             $query .= '( ';
219             $i = 0;
220             $firstc = true;
221             foreach ($cols as $col) {
222                 if (!$firstc) {
223                     $query .= ' AND ';
224                 } else {
225                     $firstc = false;
226                 }
227                 switch ($types[$col]) {
228                 case 'string':
229                 case 'datetime':
230                     $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
231                     break;
232                 default:
233                     $query .= sprintf("%s = %s", $col, $value[$i]);
234                     break;
235                 }
236             }
237             $query .= ') ';
238         }
239
240         if (!$first) {
241             $query .= ' )';
242         }
243
244         return $query;
245     }
246
247     static function pkeyCols($cls)
248     {
249         if (!is_a($cls, __CLASS__, true)) {
250             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
251         }
252         $i = new $cls;
253         $types = $i->keyTypes();
254         ksort($types);
255
256         $pkey = array();
257
258         foreach ($types as $key => $type) {
259             if ($type == 'K' || $type == 'N') {
260                 $pkey[] = $key;
261             }
262         }
263
264         return $pkey;
265     }
266
267     static function listFindClass($cls, $keyCol, array $keyVals)
268     {
269         if (!is_a($cls, __CLASS__, true)) {
270             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
271         }
272
273         $i = new $cls;
274         $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
275         if (!$i->find()) {
276             throw new NoResultException($i);
277         }
278
279         sprintf(__CLASS__ . "() got {$i->N} results for class $cls key $keyCol");
280         return $i;
281     }
282
283     static function listGetClass($cls, $keyCol, array $keyVals)
284     {
285         if (!is_a($cls, __CLASS__, true)) {
286             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
287         }
288         $pkeyMap = array_fill_keys($keyVals, array());
289         $result = array_fill_keys($keyVals, array());
290
291         $pkeyCols = self::pkeyCols($cls);
292
293         $toFetch = array();
294         $allPkeys = array();
295
296         // We only cache keys -- not objects!
297
298         foreach ($keyVals as $keyVal) {
299             $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
300             if ($l !== false) {
301                 $pkeyMap[$keyVal] = $l;
302                 foreach ($l as $pkey) {
303                     $allPkeys[] = $pkey;
304                 }
305             } else {
306                 $toFetch[] = $keyVal;
307             }
308         }
309
310         if (count($allPkeys) > 0) {
311             $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
312
313             foreach ($pkeyMap as $keyVal => $pkeyList) {
314                 foreach ($pkeyList as $pkeyVal) {
315                     $i = $keyResults[implode(',',$pkeyVal)];
316                     if (!empty($i)) {
317                         $result[$keyVal][] = $i;
318                     }
319                 }
320             }
321         }
322
323         if (count($toFetch) > 0) {
324             try {
325                 $i = self::listFindClass($cls, $keyCol, $toFetch);
326
327                 while ($i->fetch()) {
328                     $copy = clone($i);
329                     $copy->encache();
330                     $result[$i->$keyCol][] = $copy;
331                     $pkeyVal = array();
332                     foreach ($pkeyCols as $pkeyCol) {
333                         $pkeyVal[] = $i->$pkeyCol;
334                     }
335                     $pkeyMap[$i->$keyCol][] = $pkeyVal;
336                 }
337             } catch (NoResultException $e) {
338                 // no results foudn for our keyVals, so we leave them as empty arrays
339             }
340             foreach ($toFetch as $keyVal) {
341                 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
342                                $pkeyMap[$keyVal]);
343             }
344         }
345
346         return $result;
347     }
348
349     function columnType($columnName)
350     {
351         $keys = $this->table();
352         if (!array_key_exists($columnName, $keys)) {
353             throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
354         }
355
356         $def = $keys[$columnName];
357
358         if ($def & DB_DATAOBJECT_INT) {
359             return 'integer';
360         } else {
361             return 'string';
362         }
363     }
364
365     /**
366      * @todo FIXME: Should this return false on lookup fail to match getKV?
367      */
368     static function pkeyGetClass($cls, array $kv)
369     {
370         if (!is_a($cls, __CLASS__, true)) {
371             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
372         }
373         $i = Memcached_DataObject::multicache($cls, $kv);
374         if ($i !== false) { // false == cache miss
375             return $i;
376         } else {
377             $i = new $cls;
378             foreach ($kv as $k => $v) {
379                 if (is_null($v)) {
380                     // XXX: possible SQL injection...? Don't
381                     // pass keys from the browser, eh.
382                     $i->whereAdd("$k is null");
383                 } else {
384                     $i->$k = $v;
385                 }
386             }
387             if ($i->find(true)) {
388                 $i->encache();
389             } else {
390                 $i = null;
391                 $c = self::memcache();
392                 if (!empty($c)) {
393                     $ck = self::multicacheKey($cls, $kv);
394                     $c->set($ck, null);
395                 }
396             }
397             return $i;
398         }
399     }
400
401     function insert()
402     {
403         $result = parent::insert();
404         if ($result) {
405             $this->fixupTimestamps();
406             $this->encache(); // in case of cached negative lookups
407         }
408         return $result;
409     }
410
411     function update($orig=null)
412     {
413         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
414             $orig->decache(); # might be different keys
415         }
416         $result = parent::update($orig);
417         if ($result) {
418             $this->fixupTimestamps();
419             $this->encache();
420         }
421         return $result;
422     }
423
424     function delete()
425     {
426         $this->decache(); # while we still have the values!
427         return parent::delete();
428     }
429
430     static function memcache() {
431         return Cache::instance();
432     }
433
434     static function cacheKey($cls, $k, $v) {
435         if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
436             $e = new Exception();
437             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
438                 str_replace("\n", " ", $e->getTraceAsString()));
439         }
440         $vstr = self::valueString($v);
441         return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
442     }
443
444     static function getcached($cls, $k, $v) {
445         $c = Memcached_DataObject::memcache();
446         if (!$c) {
447             return false;
448         } else {
449             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
450             if (0 == strcasecmp($cls, 'User')) {
451                 // Special case for User
452                 if (is_object($obj) && is_object($obj->id)) {
453                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
454                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
455                     return false;
456                 }
457             }
458             return $obj;
459         }
460     }
461
462     function keyTypes()
463     {
464         // ini-based classes return number-indexed arrays. handbuilt
465         // classes return column => keytype. Make this uniform.
466
467         $keys = $this->keys();
468
469         $keyskeys = array_keys($keys);
470
471         if (is_string($keyskeys[0])) {
472             return $keys;
473         }
474
475         global $_DB_DATAOBJECT;
476         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
477             $this->databaseStructure();
478
479         }
480         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
481     }
482
483     function encache()
484     {
485         $c = $this->memcache();
486
487         if (!$c) {
488             return false;
489         } else if ($this->tableName() == 'user' && is_object($this->id)) {
490             // Special case for User bug
491             $e = new Exception();
492             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
493                        str_replace("\n", " ", $e->getTraceAsString()));
494             return false;
495         } else {
496             $keys = $this->_allCacheKeys();
497
498             foreach ($keys as $key) {
499                 $c->set($key, $this);
500             }
501         }
502     }
503
504     function decache()
505     {
506         $c = $this->memcache();
507
508         if (!$c) {
509             return false;
510         }
511
512         $keys = $this->_allCacheKeys();
513
514         foreach ($keys as $key) {
515             $c->delete($key, $this);
516         }
517     }
518
519     function _allCacheKeys()
520     {
521         $ckeys = array();
522
523         $types = $this->keyTypes();
524         ksort($types);
525
526         $pkey = array();
527         $pval = array();
528
529         foreach ($types as $key => $type) {
530
531             assert(!empty($key));
532
533             if ($type == 'U') {
534                 if (empty($this->$key)) {
535                     continue;
536                 }
537                 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
538             } else if ($type == 'K' || $type == 'N') {
539                 $pkey[] = $key;
540                 $pval[] = self::valueString($this->$key);
541             } else {
542                 // Low level exception. No need for i18n as discussed with Brion.
543                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
544             }
545         }
546
547         assert(count($pkey) > 0);
548
549         // XXX: should work for both compound and scalar pkeys
550         $pvals = implode(',', $pval);
551         $pkeys = implode(',', $pkey);
552
553         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
554
555         return $ckeys;
556     }
557
558     static function multicache($cls, $kv)
559     {
560         ksort($kv);
561         $c = self::memcache();
562         if (!$c) {
563             return false;
564         } else {
565             return $c->get(self::multicacheKey($cls, $kv));
566         }
567     }
568
569     static function multicacheKey($cls, $kv)
570     {
571         ksort($kv);
572         $pkeys = implode(',', array_keys($kv));
573         $pvals = implode(',', array_values($kv));
574         return self::cacheKey($cls, $pkeys, $pvals);
575     }
576
577     function getSearchEngine($table)
578     {
579         require_once INSTALLDIR.'/lib/search_engines.php';
580
581         if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
582             if ('mysql' === common_config('db', 'type')) {
583                 $type = common_config('search', 'type');
584                 if ($type == 'like') {
585                     $search_engine = new MySQLLikeSearch($this, $table);
586                 } else if ($type == 'fulltext') {
587                     $search_engine = new MySQLSearch($this, $table);
588                 } else {
589                     // Low level exception. No need for i18n as discussed with Brion.
590                     throw new ServerException('Unknown search type: ' . $type);
591                 }
592             } else {
593                 $search_engine = new PGSearch($this, $table);
594             }
595         }
596
597         return $search_engine;
598     }
599
600     static function cachedQuery($cls, $qry, $expiry=3600)
601     {
602         $c = Memcached_DataObject::memcache();
603         if (!$c) {
604             $inst = new $cls();
605             $inst->query($qry);
606             return $inst;
607         }
608         $key_part = Cache::keyize($cls).':'.md5($qry);
609         $ckey = Cache::key($key_part);
610         $stored = $c->get($ckey);
611
612         if ($stored !== false) {
613             return new ArrayWrapper($stored);
614         }
615
616         $inst = new $cls();
617         $inst->query($qry);
618         $cached = array();
619         while ($inst->fetch()) {
620             $cached[] = clone($inst);
621         }
622         $inst->free();
623         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
624         return new ArrayWrapper($cached);
625     }
626
627     /**
628      * sends query to database - this is the private one that must work
629      *   - internal functions use this rather than $this->query()
630      *
631      * Overridden to do logging.
632      *
633      * @param  string  $string
634      * @access private
635      * @return mixed none or PEAR_Error
636      */
637     function _query($string)
638     {
639         if (common_config('db', 'annotate_queries')) {
640             $string = $this->annotateQuery($string);
641         }
642
643         $start = microtime(true);
644         $fail = false;
645         $result = null;
646         if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
647             common_perf_counter('query', $string);
648             try {
649                 $result = parent::_query($string);
650             } catch (Exception $e) {
651                 $fail = $e;
652             }
653             Event::handle('EndDBQuery', array($this, $string, &$result));
654         }
655         $delta = microtime(true) - $start;
656
657         $limit = common_config('db', 'log_slow_queries');
658         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
659             $clean = $this->sanitizeQuery($string);
660             if ($fail) {
661                 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
662             } else {
663                 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
664             }
665             common_log(LOG_DEBUG, $msg);
666         }
667
668         if ($fail) {
669             throw $fail;
670         }
671         return $result;
672     }
673
674     /**
675      * Find the first caller in the stack trace that's not a
676      * low-level database function and add a comment to the
677      * query string. This should then be visible in process lists
678      * and slow query logs, to help identify problem areas.
679      *
680      * Also marks whether this was a web GET/POST or which daemon
681      * was running it.
682      *
683      * @param string $string SQL query string
684      * @return string SQL query string, with a comment in it
685      */
686     function annotateQuery($string)
687     {
688         $ignore = array('annotateQuery',
689                         '_query',
690                         'query',
691                         'get',
692                         'insert',
693                         'delete',
694                         'update',
695                         'find');
696         $ignoreStatic = array('getKV',
697                               'getClassKV',
698                               'pkeyGet',
699                               'pkeyGetClass',
700                               'cachedQuery');
701         $here = get_class($this); // if we get confused
702         $bt = debug_backtrace();
703
704         // Find the first caller that's not us?
705         foreach ($bt as $frame) {
706             $func = $frame['function'];
707             if (isset($frame['type']) && $frame['type'] == '::') {
708                 if (in_array($func, $ignoreStatic)) {
709                     continue;
710                 }
711                 $here = $frame['class'] . '::' . $func;
712                 break;
713             } else if (isset($frame['type']) && $frame['type'] == '->') {
714                 if ($frame['object'] === $this && in_array($func, $ignore)) {
715                     continue;
716                 }
717                 if (in_array($func, $ignoreStatic)) {
718                     continue; // @todo FIXME: This shouldn't be needed?
719                 }
720                 $here = get_class($frame['object']) . '->' . $func;
721                 break;
722             }
723             $here = $func;
724             break;
725         }
726
727         if (php_sapi_name() == 'cli') {
728             $context = basename($_SERVER['PHP_SELF']);
729         } else {
730             $context = $_SERVER['REQUEST_METHOD'];
731         }
732
733         // Slip the comment in after the first command,
734         // or DB_DataObject gets confused about handling inserts and such.
735         $parts = explode(' ', $string, 2);
736         $parts[0] .= " /* $context $here */";
737         return implode(' ', $parts);
738     }
739
740     // Sanitize a query for logging
741     // @fixme don't trim spaces in string literals
742     function sanitizeQuery($string)
743     {
744         $string = preg_replace('/\s+/', ' ', $string);
745         $string = trim($string);
746         return $string;
747     }
748
749     // We overload so that 'SET NAMES "utf8"' is called for
750     // each connection
751
752     function _connect()
753     {
754         global $_DB_DATAOBJECT;
755
756         $sum = $this->_getDbDsnMD5();
757
758         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
759             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
760             $exists = true;
761         } else {
762             $exists = false;
763        }
764
765         // @fixme horrible evil hack!
766         //
767         // In multisite configuration we don't want to keep around a separate
768         // connection for every database; we could end up with thousands of
769         // connections open per thread. In an ideal world we might keep
770         // a connection per server and select different databases, but that'd
771         // be reliant on having the same db username/pass as well.
772         //
773         // MySQL connections are cheap enough we're going to try just
774         // closing out the old connection and reopening when we encounter
775         // a new DSN.
776         //
777         // WARNING WARNING if we end up actually using multiple DBs at a time
778         // we'll need some fancier logic here.
779         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
780             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
781                 if (!empty($conn)) {
782                     $conn->disconnect();
783                 }
784                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
785             }
786         }
787
788         $result = parent::_connect();
789
790         if ($result && !$exists) {
791             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
792             if (common_config('db', 'type') == 'mysql' &&
793                 common_config('db', 'utf8')) {
794                 $conn = $DB->connection;
795                 if (!empty($conn)) {
796                     if ($DB instanceof DB_mysqli) {
797                         mysqli_set_charset($conn, 'utf8');
798                     } else if ($DB instanceof DB_mysql) {
799                         mysql_set_charset('utf8', $conn);
800                     }
801                 }
802             }
803             // Needed to make timestamp values usefully comparable.
804             if (common_config('db', 'type') == 'mysql') {
805                 parent::_query("set time_zone='+0:00'");
806             }
807         }
808
809         return $result;
810     }
811
812     // XXX: largely cadged from DB_DataObject
813
814     function _getDbDsnMD5()
815     {
816         if ($this->_database_dsn_md5) {
817             return $this->_database_dsn_md5;
818         }
819
820         $dsn = $this->_getDbDsn();
821
822         if (is_string($dsn)) {
823             $sum = md5($dsn);
824         } else {
825             /// support array based dsn's
826             $sum = md5(serialize($dsn));
827         }
828
829         return $sum;
830     }
831
832     function _getDbDsn()
833     {
834         global $_DB_DATAOBJECT;
835
836         if (empty($_DB_DATAOBJECT['CONFIG'])) {
837             DB_DataObject::_loadConfig();
838         }
839
840         $options = &$_DB_DATAOBJECT['CONFIG'];
841
842         // if the databse dsn dis defined in the object..
843
844         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
845
846         if (!$dsn) {
847
848             if (!$this->_database) {
849                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
850             }
851
852             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
853                 $dsn = $options["database_{$this->_database}"];
854             } else if (!empty($options['database'])) {
855                 $dsn = $options['database'];
856             }
857         }
858
859         if (!$dsn) {
860             // TRANS: Exception thrown when database name or Data Source Name could not be found.
861             throw new Exception(_('No database name or DSN found anywhere.'));
862         }
863
864         return $dsn;
865     }
866
867     static function blow()
868     {
869         $c = self::memcache();
870
871         if (empty($c)) {
872             return false;
873         }
874
875         $args = func_get_args();
876
877         $format = array_shift($args);
878
879         $keyPart = vsprintf($format, $args);
880
881         $cacheKey = Cache::key($keyPart);
882
883         return $c->delete($cacheKey);
884     }
885
886     function fixupTimestamps()
887     {
888         // Fake up timestamp columns
889         $columns = $this->table();
890         foreach ($columns as $name => $type) {
891             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
892                 $this->$name = common_sql_now();
893             }
894         }
895     }
896
897     function debugDump()
898     {
899         common_debug("debugDump: " . common_log_objstring($this));
900     }
901
902     function raiseError($message, $type = null, $behaviour = null)
903     {
904         $id = get_class($this);
905         if (!empty($this->id)) {
906             $id .= ':' . $this->id;
907         }
908         if ($message instanceof PEAR_Error) {
909             $message = $message->getMessage();
910         }
911         // Low level exception. No need for i18n as discussed with Brion.
912         throw new ServerException("[$id] DB_DataObject error [$type]: $message");
913     }
914
915     static function cacheGet($keyPart)
916     {
917         $c = self::memcache();
918
919         if (empty($c)) {
920             return false;
921         }
922
923         $cacheKey = Cache::key($keyPart);
924
925         return $c->get($cacheKey);
926     }
927
928     static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
929     {
930         $c = self::memcache();
931
932         if (empty($c)) {
933             return false;
934         }
935
936         $cacheKey = Cache::key($keyPart);
937
938         return $c->set($cacheKey, $value, $flag, $expiry);
939     }
940
941     static function valueString($v)
942     {
943         $vstr = null;
944         if (is_object($v) && $v instanceof DB_DataObject_Cast) {
945             switch ($v->type) {
946             case 'date':
947                 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
948                 break;
949             case 'blob':
950             case 'string':
951             case 'sql':
952             case 'datetime':
953             case 'time':
954                 // Low level exception. No need for i18n as discussed with Brion.
955                 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
956                 break;
957             default:
958                 // Low level exception. No need for i18n as discussed with Brion.
959                 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
960                 break;
961             }
962         } else {
963             $vstr = strval($v);
964         }
965         return $vstr;
966     }
967 }