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) && !($v instanceof DB_DataObject_Cast))) {
132 $e = new Exception();
133 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
134 str_replace("\n", " ", $e->getTraceAsString()));
136 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
139 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
146 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
149 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
155 return common_cache_key(strtolower($cls).':'.$k.':'.$vstr);
158 static function getcached($cls, $k, $v) {
159 $c = Memcached_DataObject::memcache();
163 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
164 if (0 == strcasecmp($cls, 'User')) {
165 // Special case for User
166 if (is_object($obj) && is_object($obj->id)) {
167 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
168 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
178 // ini-based classes return number-indexed arrays. handbuilt
179 // classes return column => keytype. Make this uniform.
181 $keys = $this->keys();
183 $keyskeys = array_keys($keys);
185 if (is_string($keyskeys[0])) {
189 global $_DB_DATAOBJECT;
190 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
191 $this->databaseStructure();
194 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
199 $c = $this->memcache();
203 } else if ($this->tableName() == 'user' && is_object($this->id)) {
204 // Special case for User bug
205 $e = new Exception();
206 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
207 str_replace("\n", " ", $e->getTraceAsString()));
210 $keys = $this->_allCacheKeys();
212 foreach ($keys as $key) {
213 $c->set($key, $this);
220 $c = $this->memcache();
226 $keys = $this->_allCacheKeys();
228 foreach ($keys as $key) {
229 $c->delete($key, $this);
233 function _allCacheKeys()
237 $types = $this->keyTypes();
243 foreach ($types as $key => $type) {
245 assert(!empty($key));
248 if (empty($this->$key)) {
251 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
252 } else if ($type == 'K' || $type == 'N') {
254 $pval[] = $this->$key;
256 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
260 assert(count($pkey) > 0);
262 // XXX: should work for both compound and scalar pkeys
263 $pvals = implode(',', $pval);
264 $pkeys = implode(',', $pkey);
266 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
271 function multicache($cls, $kv)
274 $c = self::memcache();
278 return $c->get(self::multicacheKey($cls, $kv));
282 static function multicacheKey($cls, $kv)
285 $pkeys = implode(',', array_keys($kv));
286 $pvals = implode(',', array_values($kv));
287 return self::cacheKey($cls, $pkeys, $pvals);
290 function getSearchEngine($table)
292 require_once INSTALLDIR.'/lib/search_engines.php';
293 static $search_engine;
294 if (!isset($search_engine)) {
295 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
296 if ('mysql' === common_config('db', 'type')) {
297 $type = common_config('search', 'type');
298 if ($type == 'like') {
299 $search_engine = new MySQLLikeSearch($this, $table);
300 } else if ($type == 'fulltext') {
301 $search_engine = new MySQLSearch($this, $table);
303 throw new ServerException('Unknown search type: ' . $type);
306 $search_engine = new PGSearch($this, $table);
310 return $search_engine;
313 static function cachedQuery($cls, $qry, $expiry=3600)
315 $c = Memcached_DataObject::memcache();
321 $key_part = common_keyize($cls).':'.md5($qry);
322 $ckey = common_cache_key($key_part);
323 $stored = $c->get($ckey);
325 if ($stored !== false) {
326 return new ArrayWrapper($stored);
332 while ($inst->fetch()) {
333 $cached[] = clone($inst);
336 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
337 return new ArrayWrapper($cached);
341 * sends query to database - this is the private one that must work
342 * - internal functions use this rather than $this->query()
344 * Overridden to do logging.
346 * @param string $string
348 * @return mixed none or PEAR_Error
350 function _query($string)
352 if (common_config('db', 'annotate_queries')) {
353 $string = $this->annotateQuery($string);
356 $start = microtime(true);
357 $result = parent::_query($string);
358 $delta = microtime(true) - $start;
360 $limit = common_config('db', 'log_slow_queries');
361 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
362 $clean = $this->sanitizeQuery($string);
363 common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
369 * Find the first caller in the stack trace that's not a
370 * low-level database function and add a comment to the
371 * query string. This should then be visible in process lists
372 * and slow query logs, to help identify problem areas.
374 * Also marks whether this was a web GET/POST or which daemon
377 * @param string $string SQL query string
378 * @return string SQL query string, with a comment in it
380 function annotateQuery($string)
382 $ignore = array('annotateQuery',
390 $ignoreStatic = array('staticGet',
393 $here = get_class($this); // if we get confused
394 $bt = debug_backtrace();
396 // Find the first caller that's not us?
397 foreach ($bt as $frame) {
398 $func = $frame['function'];
399 if (isset($frame['type']) && $frame['type'] == '::') {
400 if (in_array($func, $ignoreStatic)) {
403 $here = $frame['class'] . '::' . $func;
405 } else if (isset($frame['type']) && $frame['type'] == '->') {
406 if ($frame['object'] === $this && in_array($func, $ignore)) {
409 if (in_array($func, $ignoreStatic)) {
410 continue; // @fixme this shouldn't be needed?
412 $here = get_class($frame['object']) . '->' . $func;
419 if (php_sapi_name() == 'cli') {
420 $context = basename($_SERVER['PHP_SELF']);
422 $context = $_SERVER['REQUEST_METHOD'];
425 // Slip the comment in after the first command,
426 // or DB_DataObject gets confused about handling inserts and such.
427 $parts = explode(' ', $string, 2);
428 $parts[0] .= " /* $context $here */";
429 return implode(' ', $parts);
432 // Sanitize a query for logging
433 // @fixme don't trim spaces in string literals
434 function sanitizeQuery($string)
436 $string = preg_replace('/\s+/', ' ', $string);
437 $string = trim($string);
441 // We overload so that 'SET NAMES "utf8"' is called for
446 global $_DB_DATAOBJECT;
448 $sum = $this->_getDbDsnMD5();
450 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
451 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
457 // @fixme horrible evil hack!
459 // In multisite configuration we don't want to keep around a separate
460 // connection for every database; we could end up with thousands of
461 // connections open per thread. In an ideal world we might keep
462 // a connection per server and select different databases, but that'd
463 // be reliant on having the same db username/pass as well.
465 // MySQL connections are cheap enough we're going to try just
466 // closing out the old connection and reopening when we encounter
469 // WARNING WARNING if we end up actually using multiple DBs at a time
470 // we'll need some fancier logic here.
471 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
472 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
476 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
480 $result = parent::_connect();
482 if ($result && !$exists) {
483 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
484 if (common_config('db', 'type') == 'mysql' &&
485 common_config('db', 'utf8')) {
486 $conn = $DB->connection;
488 if ($DB instanceof DB_mysqli) {
489 mysqli_set_charset($conn, 'utf8');
490 } else if ($DB instanceof DB_mysql) {
491 mysql_set_charset('utf8', $conn);
500 // XXX: largely cadged from DB_DataObject
502 function _getDbDsnMD5()
504 if ($this->_database_dsn_md5) {
505 return $this->_database_dsn_md5;
508 $dsn = $this->_getDbDsn();
510 if (is_string($dsn)) {
513 /// support array based dsn's
514 $sum = md5(serialize($dsn));
522 global $_DB_DATAOBJECT;
524 if (empty($_DB_DATAOBJECT['CONFIG'])) {
525 DB_DataObject::_loadConfig();
528 $options = &$_DB_DATAOBJECT['CONFIG'];
530 // if the databse dsn dis defined in the object..
532 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
536 if (!$this->_database) {
537 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
540 if ($this->_database && !empty($options["database_{$this->_database}"])) {
541 $dsn = $options["database_{$this->_database}"];
542 } else if (!empty($options['database'])) {
543 $dsn = $options['database'];
548 throw new Exception("No database name / dsn found anywhere");
554 static function blow()
556 $c = self::memcache();
562 $args = func_get_args();
564 $format = array_shift($args);
566 $keyPart = vsprintf($format, $args);
568 $cacheKey = common_cache_key($keyPart);
570 return $c->delete($cacheKey);
573 function fixupTimestamps()
575 // Fake up timestamp columns
576 $columns = $this->table();
577 foreach ($columns as $name => $type) {
578 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
579 $this->$name = common_sql_now();
586 common_debug("debugDump: " . common_log_objstring($this));
589 function raiseError($message, $type = null, $behaviour = null)
591 $id = get_class($this);
593 $id .= ':' . $this->id;
595 if ($message instanceof PEAR_Error) {
596 $message = $message->getMessage();
598 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
601 static function cacheGet($keyPart)
603 $c = self::memcache();
609 $cacheKey = common_cache_key($keyPart);
611 return $c->get($cacheKey);
614 static function cacheSet($keyPart, $value)
616 $c = self::memcache();
622 $cacheKey = common_cache_key($keyPart);
624 return $c->set($cacheKey, $value);