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);
67 function multiGet($cls, $keyCol, $keyVals)
69 $result = array_fill_keys($keyVals, null);
73 foreach ($keyVals as $keyVal) {
74 $i = self::getcached($cls, $keyCol, $keyVal);
76 $result[$keyVal] = $i;
77 } else if (!empty($keyVal)) {
82 if (count($toFetch) > 0) {
83 $i = DB_DataObject::factory($cls);
85 throw new Exception(_('Cannot instantiate class ' . $cls));
87 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
92 $result[$i->$keyCol] = $copy;
97 return new ArrayWrapper(array_values($result));
100 function columnType($columnName)
102 $keys = $this->table();
103 if (!array_key_exists($columnName, $keys)) {
104 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
107 $def = $keys[$columnName];
109 if ($def & DB_DATAOBJECT_INT) {
117 * @fixme Should this return false on lookup fail to match staticGet?
119 function pkeyGet($cls, $kv)
121 $i = Memcached_DataObject::multicache($cls, $kv);
122 if ($i !== false) { // false == cache miss
125 $i = DB_DataObject::factory($cls);
126 if (empty($i) || PEAR::isError($i)) {
129 foreach ($kv as $k => $v) {
131 // XXX: possible SQL injection...? Don't
132 // pass keys from the browser, eh.
133 $i->whereAdd("$k is null");
138 if ($i->find(true)) {
142 $c = self::memcache();
144 $ck = self::multicacheKey($cls, $kv);
154 $result = parent::insert();
156 $this->fixupTimestamps();
157 $this->encache(); // in case of cached negative lookups
162 function update($orig=null)
164 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
165 $orig->decache(); # might be different keys
167 $result = parent::update($orig);
169 $this->fixupTimestamps();
177 $this->decache(); # while we still have the values!
178 return parent::delete();
181 static function memcache() {
182 return Cache::instance();
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()));
191 $vstr = self::valueString($v);
192 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
195 static function getcached($cls, $k, $v) {
196 $c = Memcached_DataObject::memcache();
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));
215 // ini-based classes return number-indexed arrays. handbuilt
216 // classes return column => keytype. Make this uniform.
218 $keys = $this->keys();
220 $keyskeys = array_keys($keys);
222 if (is_string($keyskeys[0])) {
226 global $_DB_DATAOBJECT;
227 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
228 $this->databaseStructure();
231 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
236 $c = $this->memcache();
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()));
247 $keys = $this->_allCacheKeys();
249 foreach ($keys as $key) {
250 $c->set($key, $this);
257 $c = $this->memcache();
263 $keys = $this->_allCacheKeys();
265 foreach ($keys as $key) {
266 $c->delete($key, $this);
270 function _allCacheKeys()
274 $types = $this->keyTypes();
280 foreach ($types as $key => $type) {
282 assert(!empty($key));
285 if (empty($this->$key)) {
288 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
289 } else if ($type == 'K' || $type == 'N') {
291 $pval[] = self::valueString($this->$key);
293 // Low level exception. No need for i18n as discussed with Brion.
294 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
298 assert(count($pkey) > 0);
300 // XXX: should work for both compound and scalar pkeys
301 $pvals = implode(',', $pval);
302 $pkeys = implode(',', $pkey);
304 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
309 function multicache($cls, $kv)
312 $c = self::memcache();
316 return $c->get(self::multicacheKey($cls, $kv));
320 static function multicacheKey($cls, $kv)
323 $pkeys = implode(',', array_keys($kv));
324 $pvals = implode(',', array_values($kv));
325 return self::cacheKey($cls, $pkeys, $pvals);
328 function getSearchEngine($table)
330 require_once INSTALLDIR.'/lib/search_engines.php';
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);
340 // Low level exception. No need for i18n as discussed with Brion.
341 throw new ServerException('Unknown search type: ' . $type);
344 $search_engine = new PGSearch($this, $table);
348 return $search_engine;
351 static function cachedQuery($cls, $qry, $expiry=3600)
353 $c = Memcached_DataObject::memcache();
359 $key_part = Cache::keyize($cls).':'.md5($qry);
360 $ckey = Cache::key($key_part);
361 $stored = $c->get($ckey);
363 if ($stored !== false) {
364 return new ArrayWrapper($stored);
370 while ($inst->fetch()) {
371 $cached[] = clone($inst);
374 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
375 return new ArrayWrapper($cached);
379 * sends query to database - this is the private one that must work
380 * - internal functions use this rather than $this->query()
382 * Overridden to do logging.
384 * @param string $string
386 * @return mixed none or PEAR_Error
388 function _query($string)
390 if (common_config('db', 'annotate_queries')) {
391 $string = $this->annotateQuery($string);
394 $start = microtime(true);
397 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
398 common_perf_counter('query', $string);
400 $result = parent::_query($string);
401 } catch (Exception $e) {
404 Event::handle('EndDBQuery', array($this, $string, &$result));
406 $delta = microtime(true) - $start;
408 $limit = common_config('db', 'log_slow_queries');
409 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
410 $clean = $this->sanitizeQuery($string);
412 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
414 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
416 common_log(LOG_DEBUG, $msg);
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.
431 * Also marks whether this was a web GET/POST or which daemon
434 * @param string $string SQL query string
435 * @return string SQL query string, with a comment in it
437 function annotateQuery($string)
439 $ignore = array('annotateQuery',
447 $ignoreStatic = array('staticGet',
450 $here = get_class($this); // if we get confused
451 $bt = debug_backtrace();
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)) {
460 $here = $frame['class'] . '::' . $func;
462 } else if (isset($frame['type']) && $frame['type'] == '->') {
463 if ($frame['object'] === $this && in_array($func, $ignore)) {
466 if (in_array($func, $ignoreStatic)) {
467 continue; // @fixme this shouldn't be needed?
469 $here = get_class($frame['object']) . '->' . $func;
476 if (php_sapi_name() == 'cli') {
477 $context = basename($_SERVER['PHP_SELF']);
479 $context = $_SERVER['REQUEST_METHOD'];
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);
489 // Sanitize a query for logging
490 // @fixme don't trim spaces in string literals
491 function sanitizeQuery($string)
493 $string = preg_replace('/\s+/', ' ', $string);
494 $string = trim($string);
498 // We overload so that 'SET NAMES "utf8"' is called for
503 global $_DB_DATAOBJECT;
505 $sum = $this->_getDbDsnMD5();
507 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
508 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
514 // @fixme horrible evil hack!
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.
522 // MySQL connections are cheap enough we're going to try just
523 // closing out the old connection and reopening when we encounter
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) {
533 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
537 $result = parent::_connect();
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;
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);
552 // Needed to make timestamp values usefully comparable.
553 if (common_config('db', 'type') == 'mysql') {
554 parent::_query("set time_zone='+0:00'");
561 // XXX: largely cadged from DB_DataObject
563 function _getDbDsnMD5()
565 if ($this->_database_dsn_md5) {
566 return $this->_database_dsn_md5;
569 $dsn = $this->_getDbDsn();
571 if (is_string($dsn)) {
574 /// support array based dsn's
575 $sum = md5(serialize($dsn));
583 global $_DB_DATAOBJECT;
585 if (empty($_DB_DATAOBJECT['CONFIG'])) {
586 DB_DataObject::_loadConfig();
589 $options = &$_DB_DATAOBJECT['CONFIG'];
591 // if the databse dsn dis defined in the object..
593 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
597 if (!$this->_database) {
598 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
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'];
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."));
616 static function blow()
618 $c = self::memcache();
624 $args = func_get_args();
626 $format = array_shift($args);
628 $keyPart = vsprintf($format, $args);
630 $cacheKey = Cache::key($keyPart);
632 return $c->delete($cacheKey);
635 function fixupTimestamps()
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();
648 common_debug("debugDump: " . common_log_objstring($this));
651 function raiseError($message, $type = null, $behaviour = null)
653 $id = get_class($this);
654 if (!empty($this->id)) {
655 $id .= ':' . $this->id;
657 if ($message instanceof PEAR_Error) {
658 $message = $message->getMessage();
660 // Low level exception. No need for i18n as discussed with Brion.
661 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
664 static function cacheGet($keyPart)
666 $c = self::memcache();
672 $cacheKey = Cache::key($keyPart);
674 return $c->get($cacheKey);
677 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
679 $c = self::memcache();
685 $cacheKey = Cache::key($keyPart);
687 return $c->set($cacheKey, $value, $flag, $expiry);
690 static function valueString($v)
693 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
696 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
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'");
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'");