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 = array_fill_keys($keyVals, null);
83 foreach ($keyVals as $keyVal) {
84 $i = self::getcached($cls, $keyCol, $keyVal);
86 $result[$keyVal] = $i;
87 } else if (!empty($keyVal)) {
92 if (count($toFetch) > 0) {
93 $i = DB_DataObject::factory($cls);
95 throw new Exception(_('Cannot instantiate class ' . $cls));
97 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
102 $result[$i->$keyCol] = $copy;
106 // Save state of DB misses
108 foreach ($toFetch as $keyVal) {
109 if (empty($result[$keyVal])) {
110 // save the fact that no such row exists
111 $c = self::memcache();
113 $ck = self::cachekey($cls, $keyCol, $keyVal);
120 $values = array_values($result);
124 foreach ($values as $value) {
125 if (!empty($value)) {
132 return new ArrayWrapper($values);
135 function columnType($columnName)
137 $keys = $this->table();
138 if (!array_key_exists($columnName, $keys)) {
139 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
142 $def = $keys[$columnName];
144 if ($def & DB_DATAOBJECT_INT) {
152 * @fixme Should this return false on lookup fail to match staticGet?
154 function pkeyGet($cls, $kv)
156 $i = Memcached_DataObject::multicache($cls, $kv);
157 if ($i !== false) { // false == cache miss
160 $i = DB_DataObject::factory($cls);
161 if (empty($i) || PEAR::isError($i)) {
164 foreach ($kv as $k => $v) {
166 // XXX: possible SQL injection...? Don't
167 // pass keys from the browser, eh.
168 $i->whereAdd("$k is null");
173 if ($i->find(true)) {
177 $c = self::memcache();
179 $ck = self::multicacheKey($cls, $kv);
189 $result = parent::insert();
191 $this->fixupTimestamps();
192 $this->encache(); // in case of cached negative lookups
197 function update($orig=null)
199 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
200 $orig->decache(); # might be different keys
202 $result = parent::update($orig);
204 $this->fixupTimestamps();
212 $this->decache(); # while we still have the values!
213 return parent::delete();
216 static function memcache() {
217 return Cache::instance();
220 static function cacheKey($cls, $k, $v) {
221 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
222 $e = new Exception();
223 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
224 str_replace("\n", " ", $e->getTraceAsString()));
226 $vstr = self::valueString($v);
227 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
230 static function getcached($cls, $k, $v) {
231 $c = Memcached_DataObject::memcache();
235 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
236 if (0 == strcasecmp($cls, 'User')) {
237 // Special case for User
238 if (is_object($obj) && is_object($obj->id)) {
239 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
240 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
250 // ini-based classes return number-indexed arrays. handbuilt
251 // classes return column => keytype. Make this uniform.
253 $keys = $this->keys();
255 $keyskeys = array_keys($keys);
257 if (is_string($keyskeys[0])) {
261 global $_DB_DATAOBJECT;
262 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
263 $this->databaseStructure();
266 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
271 $c = $this->memcache();
275 } else if ($this->tableName() == 'user' && is_object($this->id)) {
276 // Special case for User bug
277 $e = new Exception();
278 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
279 str_replace("\n", " ", $e->getTraceAsString()));
282 $keys = $this->_allCacheKeys();
284 foreach ($keys as $key) {
285 $c->set($key, $this);
292 $c = $this->memcache();
298 $keys = $this->_allCacheKeys();
300 foreach ($keys as $key) {
301 $c->delete($key, $this);
305 function _allCacheKeys()
309 $types = $this->keyTypes();
315 foreach ($types as $key => $type) {
317 assert(!empty($key));
320 if (empty($this->$key)) {
323 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
324 } else if ($type == 'K' || $type == 'N') {
326 $pval[] = self::valueString($this->$key);
328 // Low level exception. No need for i18n as discussed with Brion.
329 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
333 assert(count($pkey) > 0);
335 // XXX: should work for both compound and scalar pkeys
336 $pvals = implode(',', $pval);
337 $pkeys = implode(',', $pkey);
339 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
344 function multicache($cls, $kv)
347 $c = self::memcache();
351 return $c->get(self::multicacheKey($cls, $kv));
355 static function multicacheKey($cls, $kv)
358 $pkeys = implode(',', array_keys($kv));
359 $pvals = implode(',', array_values($kv));
360 return self::cacheKey($cls, $pkeys, $pvals);
363 function getSearchEngine($table)
365 require_once INSTALLDIR.'/lib/search_engines.php';
367 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
368 if ('mysql' === common_config('db', 'type')) {
369 $type = common_config('search', 'type');
370 if ($type == 'like') {
371 $search_engine = new MySQLLikeSearch($this, $table);
372 } else if ($type == 'fulltext') {
373 $search_engine = new MySQLSearch($this, $table);
375 // Low level exception. No need for i18n as discussed with Brion.
376 throw new ServerException('Unknown search type: ' . $type);
379 $search_engine = new PGSearch($this, $table);
383 return $search_engine;
386 static function cachedQuery($cls, $qry, $expiry=3600)
388 $c = Memcached_DataObject::memcache();
394 $key_part = Cache::keyize($cls).':'.md5($qry);
395 $ckey = Cache::key($key_part);
396 $stored = $c->get($ckey);
398 if ($stored !== false) {
399 return new ArrayWrapper($stored);
405 while ($inst->fetch()) {
406 $cached[] = clone($inst);
409 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
410 return new ArrayWrapper($cached);
414 * sends query to database - this is the private one that must work
415 * - internal functions use this rather than $this->query()
417 * Overridden to do logging.
419 * @param string $string
421 * @return mixed none or PEAR_Error
423 function _query($string)
425 if (common_config('db', 'annotate_queries')) {
426 $string = $this->annotateQuery($string);
429 $start = microtime(true);
432 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
433 common_perf_counter('query', $string);
435 $result = parent::_query($string);
436 } catch (Exception $e) {
439 Event::handle('EndDBQuery', array($this, $string, &$result));
441 $delta = microtime(true) - $start;
443 $limit = common_config('db', 'log_slow_queries');
444 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
445 $clean = $this->sanitizeQuery($string);
447 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
449 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
451 common_log(LOG_DEBUG, $msg);
461 * Find the first caller in the stack trace that's not a
462 * low-level database function and add a comment to the
463 * query string. This should then be visible in process lists
464 * and slow query logs, to help identify problem areas.
466 * Also marks whether this was a web GET/POST or which daemon
469 * @param string $string SQL query string
470 * @return string SQL query string, with a comment in it
472 function annotateQuery($string)
474 $ignore = array('annotateQuery',
482 $ignoreStatic = array('staticGet',
485 $here = get_class($this); // if we get confused
486 $bt = debug_backtrace();
488 // Find the first caller that's not us?
489 foreach ($bt as $frame) {
490 $func = $frame['function'];
491 if (isset($frame['type']) && $frame['type'] == '::') {
492 if (in_array($func, $ignoreStatic)) {
495 $here = $frame['class'] . '::' . $func;
497 } else if (isset($frame['type']) && $frame['type'] == '->') {
498 if ($frame['object'] === $this && in_array($func, $ignore)) {
501 if (in_array($func, $ignoreStatic)) {
502 continue; // @fixme this shouldn't be needed?
504 $here = get_class($frame['object']) . '->' . $func;
511 if (php_sapi_name() == 'cli') {
512 $context = basename($_SERVER['PHP_SELF']);
514 $context = $_SERVER['REQUEST_METHOD'];
517 // Slip the comment in after the first command,
518 // or DB_DataObject gets confused about handling inserts and such.
519 $parts = explode(' ', $string, 2);
520 $parts[0] .= " /* $context $here */";
521 return implode(' ', $parts);
524 // Sanitize a query for logging
525 // @fixme don't trim spaces in string literals
526 function sanitizeQuery($string)
528 $string = preg_replace('/\s+/', ' ', $string);
529 $string = trim($string);
533 // We overload so that 'SET NAMES "utf8"' is called for
538 global $_DB_DATAOBJECT;
540 $sum = $this->_getDbDsnMD5();
542 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
543 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
549 // @fixme horrible evil hack!
551 // In multisite configuration we don't want to keep around a separate
552 // connection for every database; we could end up with thousands of
553 // connections open per thread. In an ideal world we might keep
554 // a connection per server and select different databases, but that'd
555 // be reliant on having the same db username/pass as well.
557 // MySQL connections are cheap enough we're going to try just
558 // closing out the old connection and reopening when we encounter
561 // WARNING WARNING if we end up actually using multiple DBs at a time
562 // we'll need some fancier logic here.
563 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
564 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
568 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
572 $result = parent::_connect();
574 if ($result && !$exists) {
575 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
576 if (common_config('db', 'type') == 'mysql' &&
577 common_config('db', 'utf8')) {
578 $conn = $DB->connection;
580 if ($DB instanceof DB_mysqli) {
581 mysqli_set_charset($conn, 'utf8');
582 } else if ($DB instanceof DB_mysql) {
583 mysql_set_charset('utf8', $conn);
587 // Needed to make timestamp values usefully comparable.
588 if (common_config('db', 'type') == 'mysql') {
589 parent::_query("set time_zone='+0:00'");
596 // XXX: largely cadged from DB_DataObject
598 function _getDbDsnMD5()
600 if ($this->_database_dsn_md5) {
601 return $this->_database_dsn_md5;
604 $dsn = $this->_getDbDsn();
606 if (is_string($dsn)) {
609 /// support array based dsn's
610 $sum = md5(serialize($dsn));
618 global $_DB_DATAOBJECT;
620 if (empty($_DB_DATAOBJECT['CONFIG'])) {
621 DB_DataObject::_loadConfig();
624 $options = &$_DB_DATAOBJECT['CONFIG'];
626 // if the databse dsn dis defined in the object..
628 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
632 if (!$this->_database) {
633 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
636 if ($this->_database && !empty($options["database_{$this->_database}"])) {
637 $dsn = $options["database_{$this->_database}"];
638 } else if (!empty($options['database'])) {
639 $dsn = $options['database'];
644 // TRANS: Exception thrown when database name or Data Source Name could not be found.
645 throw new Exception(_("No database name or DSN found anywhere."));
651 static function blow()
653 $c = self::memcache();
659 $args = func_get_args();
661 $format = array_shift($args);
663 $keyPart = vsprintf($format, $args);
665 $cacheKey = Cache::key($keyPart);
667 return $c->delete($cacheKey);
670 function fixupTimestamps()
672 // Fake up timestamp columns
673 $columns = $this->table();
674 foreach ($columns as $name => $type) {
675 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
676 $this->$name = common_sql_now();
683 common_debug("debugDump: " . common_log_objstring($this));
686 function raiseError($message, $type = null, $behaviour = null)
688 $id = get_class($this);
689 if (!empty($this->id)) {
690 $id .= ':' . $this->id;
692 if ($message instanceof PEAR_Error) {
693 $message = $message->getMessage();
695 // Low level exception. No need for i18n as discussed with Brion.
696 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
699 static function cacheGet($keyPart)
701 $c = self::memcache();
707 $cacheKey = Cache::key($keyPart);
709 return $c->get($cacheKey);
712 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
714 $c = self::memcache();
720 $cacheKey = Cache::key($keyPart);
722 return $c->set($cacheKey, $value, $flag, $expiry);
725 static function valueString($v)
728 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
731 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
738 // Low level exception. No need for i18n as discussed with Brion.
739 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
742 // Low level exception. No need for i18n as discussed with Brion.
743 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");