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