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 * @fixme Should this return false on lookup fail to match staticGet?
70 function pkeyGet($cls, $kv)
72 $i = Memcached_DataObject::multicache($cls, $kv);
73 if ($i !== false) { // false == cache miss
76 $i = DB_DataObject::factory($cls);
80 foreach ($kv as $k => $v) {
87 $c = self::memcache();
89 $ck = self::multicacheKey($cls, $kv);
99 $result = parent::insert();
101 $this->fixupTimestamps();
102 $this->encache(); // in case of cached negative lookups
107 function update($orig=null)
109 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
110 $orig->decache(); # might be different keys
112 $result = parent::update($orig);
114 $this->fixupTimestamps();
122 $this->decache(); # while we still have the values!
123 return parent::delete();
126 static function memcache() {
127 return common_memcache();
130 static function cacheKey($cls, $k, $v) {
131 if (is_object($cls) || is_object($k) || is_object($v)) {
132 $e = new Exception();
133 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
134 str_replace("\n", " ", $e->getTraceAsString()));
136 return common_cache_key(strtolower($cls).':'.$k.':'.$v);
139 static function getcached($cls, $k, $v) {
140 $c = Memcached_DataObject::memcache();
144 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
145 if (0 == strcasecmp($cls, 'User')) {
146 // Special case for User
147 if (is_object($obj) && is_object($obj->id)) {
148 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
149 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
159 // ini-based classes return number-indexed arrays. handbuilt
160 // classes return column => keytype. Make this uniform.
162 $keys = $this->keys();
164 $keyskeys = array_keys($keys);
166 if (is_string($keyskeys[0])) {
170 global $_DB_DATAOBJECT;
171 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
172 $this->databaseStructure();
175 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
180 $c = $this->memcache();
184 } else if ($this->tableName() == 'user' && is_object($this->id)) {
185 // Special case for User bug
186 $e = new Exception();
187 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
188 str_replace("\n", " ", $e->getTraceAsString()));
191 $keys = $this->_allCacheKeys();
193 foreach ($keys as $key) {
194 $c->set($key, $this);
201 $c = $this->memcache();
207 $keys = $this->_allCacheKeys();
209 foreach ($keys as $key) {
210 $c->delete($key, $this);
214 function _allCacheKeys()
218 $types = $this->keyTypes();
224 foreach ($types as $key => $type) {
226 assert(!empty($key));
229 if (empty($this->$key)) {
232 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
233 } else if ($type == 'K' || $type == 'N') {
235 $pval[] = $this->$key;
237 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
241 assert(count($pkey) > 0);
243 // XXX: should work for both compound and scalar pkeys
244 $pvals = implode(',', $pval);
245 $pkeys = implode(',', $pkey);
247 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
252 function multicache($cls, $kv)
255 $c = self::memcache();
259 return $c->get(self::multicacheKey($cls, $kv));
263 static function multicacheKey($cls, $kv)
266 $pkeys = implode(',', array_keys($kv));
267 $pvals = implode(',', array_values($kv));
268 return self::cacheKey($cls, $pkeys, $pvals);
271 function getSearchEngine($table)
273 require_once INSTALLDIR.'/lib/search_engines.php';
274 static $search_engine;
275 if (!isset($search_engine)) {
276 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
277 if ('mysql' === common_config('db', 'type')) {
278 $type = common_config('search', 'type');
279 if ($type == 'like') {
280 $search_engine = new MySQLLikeSearch($this, $table);
281 } else if ($type == 'fulltext') {
282 $search_engine = new MySQLSearch($this, $table);
284 throw new ServerException('Unknown search type: ' . $type);
287 $search_engine = new PGSearch($this, $table);
291 return $search_engine;
294 static function cachedQuery($cls, $qry, $expiry=3600)
296 $c = Memcached_DataObject::memcache();
302 $key_part = common_keyize($cls).':'.md5($qry);
303 $ckey = common_cache_key($key_part);
304 $stored = $c->get($ckey);
306 if ($stored !== false) {
307 return new ArrayWrapper($stored);
313 while ($inst->fetch()) {
314 $cached[] = clone($inst);
317 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
318 return new ArrayWrapper($cached);
322 * sends query to database - this is the private one that must work
323 * - internal functions use this rather than $this->query()
325 * Overridden to do logging.
327 * @param string $string
329 * @return mixed none or PEAR_Error
331 function _query($string)
333 if (common_config('db', 'annotate_queries')) {
334 $string = $this->annotateQuery($string);
337 $start = microtime(true);
338 $result = parent::_query($string);
339 $delta = microtime(true) - $start;
341 $limit = common_config('db', 'log_slow_queries');
342 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
343 $clean = $this->sanitizeQuery($string);
344 common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
350 * Find the first caller in the stack trace that's not a
351 * low-level database function and add a comment to the
352 * query string. This should then be visible in process lists
353 * and slow query logs, to help identify problem areas.
355 * Also marks whether this was a web GET/POST or which daemon
358 * @param string $string SQL query string
359 * @return string SQL query string, with a comment in it
361 function annotateQuery($string)
363 $ignore = array('annotateQuery',
371 $ignoreStatic = array('staticGet',
374 $here = get_class($this); // if we get confused
375 $bt = debug_backtrace();
377 // Find the first caller that's not us?
378 foreach ($bt as $frame) {
379 $func = $frame['function'];
380 if (isset($frame['type']) && $frame['type'] == '::') {
381 if (in_array($func, $ignoreStatic)) {
384 $here = $frame['class'] . '::' . $func;
386 } else if (isset($frame['type']) && $frame['type'] == '->') {
387 if ($frame['object'] === $this && in_array($func, $ignore)) {
390 if (in_array($func, $ignoreStatic)) {
391 continue; // @fixme this shouldn't be needed?
393 $here = get_class($frame['object']) . '->' . $func;
400 if (php_sapi_name() == 'cli') {
401 $context = basename($_SERVER['PHP_SELF']);
403 $context = $_SERVER['REQUEST_METHOD'];
406 // Slip the comment in after the first command,
407 // or DB_DataObject gets confused about handling inserts and such.
408 $parts = explode(' ', $string, 2);
409 $parts[0] .= " /* $context $here */";
410 return implode(' ', $parts);
413 // Sanitize a query for logging
414 // @fixme don't trim spaces in string literals
415 function sanitizeQuery($string)
417 $string = preg_replace('/\s+/', ' ', $string);
418 $string = trim($string);
422 // We overload so that 'SET NAMES "utf8"' is called for
427 global $_DB_DATAOBJECT;
429 $sum = $this->_getDbDsnMD5();
431 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
432 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
438 // @fixme horrible evil hack!
440 // In multisite configuration we don't want to keep around a separate
441 // connection for every database; we could end up with thousands of
442 // connections open per thread. In an ideal world we might keep
443 // a connection per server and select different databases, but that'd
444 // be reliant on having the same db username/pass as well.
446 // MySQL connections are cheap enough we're going to try just
447 // closing out the old connection and reopening when we encounter
450 // WARNING WARNING if we end up actually using multiple DBs at a time
451 // we'll need some fancier logic here.
452 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
453 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
457 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
461 $result = parent::_connect();
463 if ($result && !$exists) {
464 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
465 if (common_config('db', 'type') == 'mysql' &&
466 common_config('db', 'utf8')) {
467 $conn = $DB->connection;
469 if ($DB instanceof DB_mysqli) {
470 mysqli_set_charset($conn, 'utf8');
471 } else if ($DB instanceof DB_mysql) {
472 mysql_set_charset('utf8', $conn);
481 // XXX: largely cadged from DB_DataObject
483 function _getDbDsnMD5()
485 if ($this->_database_dsn_md5) {
486 return $this->_database_dsn_md5;
489 $dsn = $this->_getDbDsn();
491 if (is_string($dsn)) {
494 /// support array based dsn's
495 $sum = md5(serialize($dsn));
503 global $_DB_DATAOBJECT;
505 if (empty($_DB_DATAOBJECT['CONFIG'])) {
506 DB_DataObject::_loadConfig();
509 $options = &$_DB_DATAOBJECT['CONFIG'];
511 // if the databse dsn dis defined in the object..
513 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
517 if (!$this->_database) {
518 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
521 if ($this->_database && !empty($options["database_{$this->_database}"])) {
522 $dsn = $options["database_{$this->_database}"];
523 } else if (!empty($options['database'])) {
524 $dsn = $options['database'];
529 throw new Exception("No database name / dsn found anywhere");
535 static function blow()
537 $c = self::memcache();
543 $args = func_get_args();
545 $format = array_shift($args);
547 $keyPart = vsprintf($format, $args);
549 $cacheKey = common_cache_key($keyPart);
551 return $c->delete($cacheKey);
554 function fixupTimestamps()
556 // Fake up timestamp columns
557 $columns = $this->table();
558 foreach ($columns as $name => $type) {
559 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
560 $this->$name = common_sql_now();
567 common_debug("debugDump: " . common_log_objstring($this));
570 function raiseError($message, $type = null, $behaviour = null)
572 $id = get_class($this);
574 $id .= ':' . $this->id;
576 if ($message instanceof PEAR_Error) {
577 $message = $message->getMessage();
579 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
582 static function cacheGet($keyPart)
584 $c = self::memcache();
590 $cacheKey = common_cache_key($keyPart);
592 return $c->get($cacheKey);
595 static function cacheSet($keyPart, $value)
597 $c = self::memcache();
603 $cacheKey = common_cache_key($keyPart);
605 return $c->set($cacheKey, $value);