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