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