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