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