3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 class Memcached_DataObject extends Safe_DataObject
25 * Wrapper for DB_DataObject's static lookup using memcached
26 * as backing instead of an in-process cache array.
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
33 function &staticGet($cls, $k, $v=null)
43 $i = Memcached_DataObject::getcached($cls, $k, $v);
44 if ($i === false) { // false == cache miss
45 $i = DB_DataObject::factory($cls);
50 $result = $i->get($k, $v);
55 // save the fact that no such row exists
56 $c = self::memcache();
58 $ck = self::cachekey($cls, $k, $v);
68 * Get multiple items from the database by key
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?
75 * @return array Array of objects, in order
77 function multiGet($cls, $keyCol, $keyVals, $skipNulls=true)
79 $result = self::pivotGet($cls, $keyCol, $keyVals);
81 common_log(LOG_INFO, sprintf("Got %d results for class %s with %d keys on column %s",
87 $values = array_values($result);
91 foreach ($values as $value) {
99 return new ArrayWrapper($values);
103 * Get multiple items from the database by key
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
110 * @return array Array mapping $keyVals to objects, or null if not found
112 static function pivotGet($cls, $keyCol, $keyVals, $otherCols = array())
114 $result = array_fill_keys($keyVals, null);
118 foreach ($keyVals as $keyVal) {
120 $kv = array_merge($otherCols, array($keyCol => $keyVal));
122 $i = self::multicache($cls, $kv);
125 $result[$keyVal] = $i;
126 } else if (!empty($keyVal)) {
127 $toFetch[] = $keyVal;
131 if (count($toFetch) > 0) {
132 $i = DB_DataObject::factory($cls);
134 throw new Exception(_('Cannot instantiate class ' . $cls));
136 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
137 $i->$otherKeyCol = $otherKeyVal;
139 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
141 while ($i->fetch()) {
144 $result[$i->$keyCol] = $copy;
148 // Save state of DB misses
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();
156 $ck = self::multicacheKey($cls, $keyCol, $keyVal);
166 function columnType($columnName)
168 $keys = $this->table();
169 if (!array_key_exists($columnName, $keys)) {
170 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
173 $def = $keys[$columnName];
175 if ($def & DB_DATAOBJECT_INT) {
183 * @fixme Should this return false on lookup fail to match staticGet?
185 function pkeyGet($cls, $kv)
187 $i = Memcached_DataObject::multicache($cls, $kv);
188 if ($i !== false) { // false == cache miss
191 $i = DB_DataObject::factory($cls);
192 if (empty($i) || PEAR::isError($i)) {
195 foreach ($kv as $k => $v) {
197 // XXX: possible SQL injection...? Don't
198 // pass keys from the browser, eh.
199 $i->whereAdd("$k is null");
204 if ($i->find(true)) {
208 $c = self::memcache();
210 $ck = self::multicacheKey($cls, $kv);
220 $result = parent::insert();
222 $this->fixupTimestamps();
223 $this->encache(); // in case of cached negative lookups
228 function update($orig=null)
230 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
231 $orig->decache(); # might be different keys
233 $result = parent::update($orig);
235 $this->fixupTimestamps();
243 $this->decache(); # while we still have the values!
244 return parent::delete();
247 static function memcache() {
248 return Cache::instance();
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()));
257 $vstr = self::valueString($v);
258 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
261 static function getcached($cls, $k, $v) {
262 $c = Memcached_DataObject::memcache();
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));
281 // ini-based classes return number-indexed arrays. handbuilt
282 // classes return column => keytype. Make this uniform.
284 $keys = $this->keys();
286 $keyskeys = array_keys($keys);
288 if (is_string($keyskeys[0])) {
292 global $_DB_DATAOBJECT;
293 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
294 $this->databaseStructure();
297 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
302 $c = $this->memcache();
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()));
313 $keys = $this->_allCacheKeys();
315 foreach ($keys as $key) {
316 $c->set($key, $this);
323 $c = $this->memcache();
329 $keys = $this->_allCacheKeys();
331 foreach ($keys as $key) {
332 $c->delete($key, $this);
336 function _allCacheKeys()
340 $types = $this->keyTypes();
346 foreach ($types as $key => $type) {
348 assert(!empty($key));
351 if (empty($this->$key)) {
354 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
355 } else if ($type == 'K' || $type == 'N') {
357 $pval[] = self::valueString($this->$key);
359 // Low level exception. No need for i18n as discussed with Brion.
360 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
364 assert(count($pkey) > 0);
366 // XXX: should work for both compound and scalar pkeys
367 $pvals = implode(',', $pval);
368 $pkeys = implode(',', $pkey);
370 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
375 function multicache($cls, $kv)
378 $c = self::memcache();
382 return $c->get(self::multicacheKey($cls, $kv));
386 static function multicacheKey($cls, $kv)
389 $pkeys = implode(',', array_keys($kv));
390 $pvals = implode(',', array_values($kv));
391 return self::cacheKey($cls, $pkeys, $pvals);
394 function getSearchEngine($table)
396 require_once INSTALLDIR.'/lib/search_engines.php';
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);
406 // Low level exception. No need for i18n as discussed with Brion.
407 throw new ServerException('Unknown search type: ' . $type);
410 $search_engine = new PGSearch($this, $table);
414 return $search_engine;
417 static function cachedQuery($cls, $qry, $expiry=3600)
419 $c = Memcached_DataObject::memcache();
425 $key_part = Cache::keyize($cls).':'.md5($qry);
426 $ckey = Cache::key($key_part);
427 $stored = $c->get($ckey);
429 if ($stored !== false) {
430 return new ArrayWrapper($stored);
436 while ($inst->fetch()) {
437 $cached[] = clone($inst);
440 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
441 return new ArrayWrapper($cached);
445 * sends query to database - this is the private one that must work
446 * - internal functions use this rather than $this->query()
448 * Overridden to do logging.
450 * @param string $string
452 * @return mixed none or PEAR_Error
454 function _query($string)
456 if (common_config('db', 'annotate_queries')) {
457 $string = $this->annotateQuery($string);
460 $start = microtime(true);
463 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
464 common_perf_counter('query', $string);
466 $result = parent::_query($string);
467 } catch (Exception $e) {
470 Event::handle('EndDBQuery', array($this, $string, &$result));
472 $delta = microtime(true) - $start;
474 $limit = common_config('db', 'log_slow_queries');
475 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
476 $clean = $this->sanitizeQuery($string);
478 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
480 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
482 common_log(LOG_DEBUG, $msg);
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.
497 * Also marks whether this was a web GET/POST or which daemon
500 * @param string $string SQL query string
501 * @return string SQL query string, with a comment in it
503 function annotateQuery($string)
505 $ignore = array('annotateQuery',
513 $ignoreStatic = array('staticGet',
516 $here = get_class($this); // if we get confused
517 $bt = debug_backtrace();
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)) {
526 $here = $frame['class'] . '::' . $func;
528 } else if (isset($frame['type']) && $frame['type'] == '->') {
529 if ($frame['object'] === $this && in_array($func, $ignore)) {
532 if (in_array($func, $ignoreStatic)) {
533 continue; // @fixme this shouldn't be needed?
535 $here = get_class($frame['object']) . '->' . $func;
542 if (php_sapi_name() == 'cli') {
543 $context = basename($_SERVER['PHP_SELF']);
545 $context = $_SERVER['REQUEST_METHOD'];
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);
555 // Sanitize a query for logging
556 // @fixme don't trim spaces in string literals
557 function sanitizeQuery($string)
559 $string = preg_replace('/\s+/', ' ', $string);
560 $string = trim($string);
564 // We overload so that 'SET NAMES "utf8"' is called for
569 global $_DB_DATAOBJECT;
571 $sum = $this->_getDbDsnMD5();
573 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
574 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
580 // @fixme horrible evil hack!
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.
588 // MySQL connections are cheap enough we're going to try just
589 // closing out the old connection and reopening when we encounter
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) {
599 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
603 $result = parent::_connect();
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;
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);
618 // Needed to make timestamp values usefully comparable.
619 if (common_config('db', 'type') == 'mysql') {
620 parent::_query("set time_zone='+0:00'");
627 // XXX: largely cadged from DB_DataObject
629 function _getDbDsnMD5()
631 if ($this->_database_dsn_md5) {
632 return $this->_database_dsn_md5;
635 $dsn = $this->_getDbDsn();
637 if (is_string($dsn)) {
640 /// support array based dsn's
641 $sum = md5(serialize($dsn));
649 global $_DB_DATAOBJECT;
651 if (empty($_DB_DATAOBJECT['CONFIG'])) {
652 DB_DataObject::_loadConfig();
655 $options = &$_DB_DATAOBJECT['CONFIG'];
657 // if the databse dsn dis defined in the object..
659 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
663 if (!$this->_database) {
664 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
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'];
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."));
682 static function blow()
684 $c = self::memcache();
690 $args = func_get_args();
692 $format = array_shift($args);
694 $keyPart = vsprintf($format, $args);
696 $cacheKey = Cache::key($keyPart);
698 return $c->delete($cacheKey);
701 function fixupTimestamps()
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();
714 common_debug("debugDump: " . common_log_objstring($this));
717 function raiseError($message, $type = null, $behaviour = null)
719 $id = get_class($this);
720 if (!empty($this->id)) {
721 $id .= ':' . $this->id;
723 if ($message instanceof PEAR_Error) {
724 $message = $message->getMessage();
726 // Low level exception. No need for i18n as discussed with Brion.
727 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
730 static function cacheGet($keyPart)
732 $c = self::memcache();
738 $cacheKey = Cache::key($keyPart);
740 return $c->get($cacheKey);
743 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
745 $c = self::memcache();
751 $cacheKey = Cache::key($keyPart);
753 return $c->set($cacheKey, $value, $flag, $expiry);
756 static function valueString($v)
759 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
762 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
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'");
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'");