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