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