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