]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
strtolower() the class name in cache keys for listGet()
[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             $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                 throw new Exception(_('Cannot instantiate class ' . $cls));
146             }
147             foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
148                 $i->$otherKeyCol = $otherKeyVal;
149             }
150             if (is_array($keyCol)) {
151                 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
152             } else {
153                 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
154             }
155                 if ($i->find()) {
156                         while ($i->fetch()) {
157                                 $copy = clone($i);
158                                 $copy->encache();
159                     if (is_array($keyCol)) {
160                         $vals = array();
161                         foreach ($keyCol as $k) {
162                             $vals[] = $i->$k;
163                         }
164                         $result[implode(',', $vals)] = $copy;
165                     } else {
166                         $result[$i->$keyCol] = $copy;
167                     }
168                         }
169                 }
170                 
171                 // Save state of DB misses
172                 
173                 foreach ($toFetch as $keyVal) {
174                 $r = null;
175                 if (is_array($keyCol)) {
176                     $r = $result[implode(',', $keyVal)];
177                 } else {
178                     $r = $result[$keyVal];
179                 }
180                         if (empty($r)) {
181                     if (is_array($keyCol)) {
182                         $kv = array_combine($keyCol, $keyVal);
183                     } else {
184                         $kv = array($keyCol => $keyVal);
185                     }
186                     $kv = array_merge($otherCols, $kv);
187                         // save the fact that no such row exists
188                         $c = self::memcache();
189                         if (!empty($c)) {
190                         $ck = self::multicacheKey($cls, $kv);
191                         $c->set($ck, null);
192                         }       
193                         }
194                 }
195         }
196
197         return $result;
198     }
199
200     static function _inMultiKey($i, $cols, $values)
201     {
202         $types = array();
203
204         foreach ($cols as $col) {
205             $types[$col] = $i->columnType($col);
206         }
207
208         $first = true;
209
210         $query = '';
211
212         foreach ($values as $value) {
213             if ($first) {
214                 $query .= '( ';
215                 $first = false;
216             } else {
217                 $query .= ' OR ';
218             }
219             $query .= '( ';
220             $i = 0;
221             $firstc = true;
222             foreach ($cols as $col) {
223                 if (!$firstc) {
224                     $query .= ' AND ';
225                 } else {
226                     $firstc = false;
227                 }
228                 switch ($types[$col]) {
229                 case 'string':
230                 case 'datetime':
231                     $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
232                     break;
233                 default:
234                     $query .= sprintf("%s = %s", $col, $value[$i]);
235                     break;
236                 }
237             }
238             $query .= ') ';
239         }
240
241         if (!$first) {
242             $query .= ' )';
243         }
244
245         return $query;
246     }
247
248     static function pkeyCols($cls)
249     {
250         $i = DB_DataObject::factory($cls);
251         if (empty($i)) {
252             throw new Exception(_('Cannot instantiate a ' . $cls));
253         }
254         $types = $i->keyTypes();
255         ksort($types);
256
257         $pkey = array();
258
259         foreach ($types as $key => $type) {
260             if ($type == 'K' || $type == 'N') {
261                 $pkey[] = $key;
262             }
263         }
264
265         return $pkey;
266     }
267
268     function listGet($cls, $keyCol, $keyVals)
269     {
270         $pkeyMap = array_fill_keys($keyVals, array());
271         $result = array_fill_keys($keyVals, array());
272
273         $pkeyCols = self::pkeyCols($cls);
274
275         $toFetch = array();
276         $allPkeys = array();
277
278         // We only cache keys -- not objects!
279
280         foreach ($keyVals as $keyVal) {
281             $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
282             if ($l !== false) {
283                 $pkeyMap[$keyVal] = $l;
284                 foreach ($l as $pkey) {
285                     $allPkeys[] = $pkey;
286                 }
287             } else {
288                 $toFetch[] = $keyVal;
289             }
290         }
291
292         if (count($allPkeys) > 0) {
293             $keyResults = self::pivotGet($cls, $pkeyCols, $allPkeys);
294
295             foreach ($pkeyMap as $keyVal => $pkeyList) {
296                 foreach ($pkeyList as $pkeyVal) {
297                     $i = $keyResults[implode(',',$pkeyVal)];
298                     if (!empty($i)) {
299                         $result[$keyVal][] = $i;
300                     }
301                 }
302             }
303         }
304
305         if (count($toFetch) > 0) {
306                 $i = DB_DataObject::factory($cls);
307                 if (empty($i)) {
308                         throw new Exception(_('Cannot instantiate class ' . $cls));
309                 }
310             $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
311             if ($i->find()) {
312                 sprintf("listGet() got {$i->N} results for class $cls key $keyCol");
313                 while ($i->fetch()) {
314                     $copy = clone($i);
315                     $copy->encache();
316                     $result[$i->$keyCol][] = $copy;
317                     $pkeyVal = array();
318                     foreach ($pkeyCols as $pkeyCol) {
319                         $pkeyVal[] = $i->$pkeyCol;
320                     }
321                     $pkeyMap[$i->$keyCol][] = $pkeyVal;
322                 }
323             }       
324                 foreach ($toFetch as $keyVal) {
325                 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
326                                $pkeyMap[$keyVal]);
327             }      
328         }
329
330         return $result;        
331     }
332
333         function columnType($columnName)
334         {
335                 $keys = $this->table();
336                 if (!array_key_exists($columnName, $keys)) {
337                         throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
338                 }
339                 
340                 $def = $keys[$columnName];
341                 
342                 if ($def & DB_DATAOBJECT_INT) {
343                         return 'integer';
344                 } else {
345                         return 'string';
346                 }
347         }
348         
349     /**
350      * @todo FIXME: Should this return false on lookup fail to match staticGet?
351      */
352     function pkeyGet($cls, $kv)
353     {
354         $i = Memcached_DataObject::multicache($cls, $kv);
355         if ($i !== false) { // false == cache miss
356             return $i;
357         } else {
358             $i = DB_DataObject::factory($cls);
359             if (empty($i) || PEAR::isError($i)) {
360                 return false;
361             }
362             foreach ($kv as $k => $v) {
363                 if (is_null($v)) {
364                     // XXX: possible SQL injection...? Don't
365                     // pass keys from the browser, eh.
366                     $i->whereAdd("$k is null");
367                 } else {
368                     $i->$k = $v;
369                 }
370             }
371             if ($i->find(true)) {
372                 $i->encache();
373             } else {
374                 $i = null;
375                 $c = self::memcache();
376                 if (!empty($c)) {
377                     $ck = self::multicacheKey($cls, $kv);
378                     $c->set($ck, null);
379                 }
380             }
381             return $i;
382         }
383     }
384
385     function insert()
386     {
387         $result = parent::insert();
388         if ($result) {
389             $this->fixupTimestamps();
390             $this->encache(); // in case of cached negative lookups
391         }
392         return $result;
393     }
394
395     function update($orig=null)
396     {
397         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
398             $orig->decache(); # might be different keys
399         }
400         $result = parent::update($orig);
401         if ($result) {
402             $this->fixupTimestamps();
403             $this->encache();
404         }
405         return $result;
406     }
407
408     function delete()
409     {
410         $this->decache(); # while we still have the values!
411         return parent::delete();
412     }
413
414     static function memcache() {
415         return Cache::instance();
416     }
417
418     static function cacheKey($cls, $k, $v) {
419         if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
420             $e = new Exception();
421             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
422                 str_replace("\n", " ", $e->getTraceAsString()));
423         }
424         $vstr = self::valueString($v);
425         return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
426     }
427
428     static function getcached($cls, $k, $v) {
429         $c = Memcached_DataObject::memcache();
430         if (!$c) {
431             return false;
432         } else {
433             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
434             if (0 == strcasecmp($cls, 'User')) {
435                 // Special case for User
436                 if (is_object($obj) && is_object($obj->id)) {
437                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
438                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
439                     return false;
440                 }
441             }
442             return $obj;
443         }
444     }
445
446     function keyTypes()
447     {
448         // ini-based classes return number-indexed arrays. handbuilt
449         // classes return column => keytype. Make this uniform.
450
451         $keys = $this->keys();
452
453         $keyskeys = array_keys($keys);
454
455         if (is_string($keyskeys[0])) {
456             return $keys;
457         }
458
459         global $_DB_DATAOBJECT;
460         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
461             $this->databaseStructure();
462
463         }
464         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
465     }
466
467     function encache()
468     {
469         $c = $this->memcache();
470
471         if (!$c) {
472             return false;
473         } else if ($this->tableName() == 'user' && is_object($this->id)) {
474             // Special case for User bug
475             $e = new Exception();
476             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
477                        str_replace("\n", " ", $e->getTraceAsString()));
478             return false;
479         } else {
480             $keys = $this->_allCacheKeys();
481
482             foreach ($keys as $key) {
483                 $c->set($key, $this);
484             }
485         }
486     }
487
488     function decache()
489     {
490         $c = $this->memcache();
491
492         if (!$c) {
493             return false;
494         }
495
496         $keys = $this->_allCacheKeys();
497
498         foreach ($keys as $key) {
499             $c->delete($key, $this);
500         }
501     }
502
503     function _allCacheKeys()
504     {
505         $ckeys = array();
506
507         $types = $this->keyTypes();
508         ksort($types);
509
510         $pkey = array();
511         $pval = array();
512
513         foreach ($types as $key => $type) {
514
515             assert(!empty($key));
516
517             if ($type == 'U') {
518                 if (empty($this->$key)) {
519                     continue;
520                 }
521                 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
522             } else if ($type == 'K' || $type == 'N') {
523                 $pkey[] = $key;
524                 $pval[] = self::valueString($this->$key);
525             } else {
526                 // Low level exception. No need for i18n as discussed with Brion.
527                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
528             }
529         }
530
531         assert(count($pkey) > 0);
532
533         // XXX: should work for both compound and scalar pkeys
534         $pvals = implode(',', $pval);
535         $pkeys = implode(',', $pkey);
536
537         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
538
539         return $ckeys;
540     }
541
542     function multicache($cls, $kv)
543     {
544         ksort($kv);
545         $c = self::memcache();
546         if (!$c) {
547             return false;
548         } else {
549             return $c->get(self::multicacheKey($cls, $kv));
550         }
551     }
552
553     static function multicacheKey($cls, $kv)
554     {
555         ksort($kv);
556         $pkeys = implode(',', array_keys($kv));
557         $pvals = implode(',', array_values($kv));
558         return self::cacheKey($cls, $pkeys, $pvals);
559     }
560
561     function getSearchEngine($table)
562     {
563         require_once INSTALLDIR.'/lib/search_engines.php';
564
565         if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
566             if ('mysql' === common_config('db', 'type')) {
567                 $type = common_config('search', 'type');
568                 if ($type == 'like') {
569                     $search_engine = new MySQLLikeSearch($this, $table);
570                 } else if ($type == 'fulltext') {
571                     $search_engine = new MySQLSearch($this, $table);
572                 } else {
573                     // Low level exception. No need for i18n as discussed with Brion.
574                     throw new ServerException('Unknown search type: ' . $type);
575                 }
576             } else {
577                 $search_engine = new PGSearch($this, $table);
578             }
579         }
580
581         return $search_engine;
582     }
583
584     static function cachedQuery($cls, $qry, $expiry=3600)
585     {
586         $c = Memcached_DataObject::memcache();
587         if (!$c) {
588             $inst = new $cls();
589             $inst->query($qry);
590             return $inst;
591         }
592         $key_part = Cache::keyize($cls).':'.md5($qry);
593         $ckey = Cache::key($key_part);
594         $stored = $c->get($ckey);
595
596         if ($stored !== false) {
597             return new ArrayWrapper($stored);
598         }
599
600         $inst = new $cls();
601         $inst->query($qry);
602         $cached = array();
603         while ($inst->fetch()) {
604             $cached[] = clone($inst);
605         }
606         $inst->free();
607         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
608         return new ArrayWrapper($cached);
609     }
610
611     /**
612      * sends query to database - this is the private one that must work
613      *   - internal functions use this rather than $this->query()
614      *
615      * Overridden to do logging.
616      *
617      * @param  string  $string
618      * @access private
619      * @return mixed none or PEAR_Error
620      */
621     function _query($string)
622     {
623         if (common_config('db', 'annotate_queries')) {
624             $string = $this->annotateQuery($string);
625         }
626
627         $start = microtime(true);
628         $fail = false;
629         $result = null;
630         if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
631             common_perf_counter('query', $string);
632             try {
633                 $result = parent::_query($string);
634             } catch (Exception $e) {
635                 $fail = $e;
636             }
637             Event::handle('EndDBQuery', array($this, $string, &$result));
638         }
639         $delta = microtime(true) - $start;
640
641         $limit = common_config('db', 'log_slow_queries');
642         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
643             $clean = $this->sanitizeQuery($string);
644             if ($fail) {
645                 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
646             } else {
647                 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
648             }
649             common_log(LOG_DEBUG, $msg);
650         }
651
652         if ($fail) {
653             throw $fail;
654         }
655         return $result;
656     }
657
658     /**
659      * Find the first caller in the stack trace that's not a
660      * low-level database function and add a comment to the
661      * query string. This should then be visible in process lists
662      * and slow query logs, to help identify problem areas.
663      *
664      * Also marks whether this was a web GET/POST or which daemon
665      * was running it.
666      *
667      * @param string $string SQL query string
668      * @return string SQL query string, with a comment in it
669      */
670     function annotateQuery($string)
671     {
672         $ignore = array('annotateQuery',
673                         '_query',
674                         'query',
675                         'get',
676                         'insert',
677                         'delete',
678                         'update',
679                         'find');
680         $ignoreStatic = array('staticGet',
681                               'pkeyGet',
682                               'cachedQuery');
683         $here = get_class($this); // if we get confused
684         $bt = debug_backtrace();
685
686         // Find the first caller that's not us?
687         foreach ($bt as $frame) {
688             $func = $frame['function'];
689             if (isset($frame['type']) && $frame['type'] == '::') {
690                 if (in_array($func, $ignoreStatic)) {
691                     continue;
692                 }
693                 $here = $frame['class'] . '::' . $func;
694                 break;
695             } else if (isset($frame['type']) && $frame['type'] == '->') {
696                 if ($frame['object'] === $this && in_array($func, $ignore)) {
697                     continue;
698                 }
699                 if (in_array($func, $ignoreStatic)) {
700                     continue; // @todo FIXME: This shouldn't be needed?
701                 }
702                 $here = get_class($frame['object']) . '->' . $func;
703                 break;
704             }
705             $here = $func;
706             break;
707         }
708
709         if (php_sapi_name() == 'cli') {
710             $context = basename($_SERVER['PHP_SELF']);
711         } else {
712             $context = $_SERVER['REQUEST_METHOD'];
713         }
714
715         // Slip the comment in after the first command,
716         // or DB_DataObject gets confused about handling inserts and such.
717         $parts = explode(' ', $string, 2);
718         $parts[0] .= " /* $context $here */";
719         return implode(' ', $parts);
720     }
721
722     // Sanitize a query for logging
723     // @fixme don't trim spaces in string literals
724     function sanitizeQuery($string)
725     {
726         $string = preg_replace('/\s+/', ' ', $string);
727         $string = trim($string);
728         return $string;
729     }
730
731     // We overload so that 'SET NAMES "utf8"' is called for
732     // each connection
733
734     function _connect()
735     {
736         global $_DB_DATAOBJECT;
737
738         $sum = $this->_getDbDsnMD5();
739
740         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
741             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
742             $exists = true;
743         } else {
744             $exists = false;
745        }
746
747         // @fixme horrible evil hack!
748         //
749         // In multisite configuration we don't want to keep around a separate
750         // connection for every database; we could end up with thousands of
751         // connections open per thread. In an ideal world we might keep
752         // a connection per server and select different databases, but that'd
753         // be reliant on having the same db username/pass as well.
754         //
755         // MySQL connections are cheap enough we're going to try just
756         // closing out the old connection and reopening when we encounter
757         // a new DSN.
758         //
759         // WARNING WARNING if we end up actually using multiple DBs at a time
760         // we'll need some fancier logic here.
761         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
762             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
763                 if (!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) {
779                         mysqli_set_charset($conn, 'utf8');
780                     } else if ($DB instanceof DB_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 }