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);
77 if (empty($i) || PEAR::isError($i)) {
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 Cache::instance();
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 $vstr = self::valueString($v);
137 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
140 static function getcached($cls, $k, $v) {
141 $c = Memcached_DataObject::memcache();
145 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
146 if (0 == strcasecmp($cls, 'User')) {
147 // Special case for User
148 if (is_object($obj) && is_object($obj->id)) {
149 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
150 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
160 // ini-based classes return number-indexed arrays. handbuilt
161 // classes return column => keytype. Make this uniform.
163 $keys = $this->keys();
165 $keyskeys = array_keys($keys);
167 if (is_string($keyskeys[0])) {
171 global $_DB_DATAOBJECT;
172 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
173 $this->databaseStructure();
176 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
181 $c = $this->memcache();
185 } else if ($this->tableName() == 'user' && is_object($this->id)) {
186 // Special case for User bug
187 $e = new Exception();
188 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
189 str_replace("\n", " ", $e->getTraceAsString()));
192 $keys = $this->_allCacheKeys();
194 foreach ($keys as $key) {
195 $c->set($key, $this);
202 $c = $this->memcache();
208 $keys = $this->_allCacheKeys();
210 foreach ($keys as $key) {
211 $c->delete($key, $this);
215 function _allCacheKeys()
219 $types = $this->keyTypes();
225 foreach ($types as $key => $type) {
227 assert(!empty($key));
230 if (empty($this->$key)) {
233 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
234 } else if ($type == 'K' || $type == 'N') {
236 $pval[] = self::valueString($this->$key);
238 // Low level exception. No need for i18n as discussed with Brion.
239 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
243 assert(count($pkey) > 0);
245 // XXX: should work for both compound and scalar pkeys
246 $pvals = implode(',', $pval);
247 $pkeys = implode(',', $pkey);
249 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
254 function multicache($cls, $kv)
257 $c = self::memcache();
261 return $c->get(self::multicacheKey($cls, $kv));
265 static function multicacheKey($cls, $kv)
268 $pkeys = implode(',', array_keys($kv));
269 $pvals = implode(',', array_values($kv));
270 return self::cacheKey($cls, $pkeys, $pvals);
273 function getSearchEngine($table)
275 require_once INSTALLDIR.'/lib/search_engines.php';
276 static $search_engine;
277 if (!isset($search_engine)) {
278 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
279 if ('mysql' === common_config('db', 'type')) {
280 $type = common_config('search', 'type');
281 if ($type == 'like') {
282 $search_engine = new MySQLLikeSearch($this, $table);
283 } else if ($type == 'fulltext') {
284 $search_engine = new MySQLSearch($this, $table);
286 // Low level exception. No need for i18n as discussed with Brion.
287 throw new ServerException('Unknown search type: ' . $type);
290 $search_engine = new PGSearch($this, $table);
294 return $search_engine;
297 static function cachedQuery($cls, $qry, $expiry=3600)
299 $c = Memcached_DataObject::memcache();
305 $key_part = Cache::keyize($cls).':'.md5($qry);
306 $ckey = Cache::key($key_part);
307 $stored = $c->get($ckey);
309 if ($stored !== false) {
310 return new ArrayWrapper($stored);
316 while ($inst->fetch()) {
317 $cached[] = clone($inst);
320 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
321 return new ArrayWrapper($cached);
325 * sends query to database - this is the private one that must work
326 * - internal functions use this rather than $this->query()
328 * Overridden to do logging.
330 * @param string $string
332 * @return mixed none or PEAR_Error
334 function _query($string)
336 if (common_config('db', 'annotate_queries')) {
337 $string = $this->annotateQuery($string);
340 $start = microtime(true);
343 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
344 common_perf_counter('query', $string);
346 $result = parent::_query($string);
347 } catch (Exception $e) {
350 Event::handle('EndDBQuery', array($this, $string, &$result));
352 $delta = microtime(true) - $start;
354 $limit = common_config('db', 'log_slow_queries');
355 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
356 $clean = $this->sanitizeQuery($string);
358 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
360 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
362 common_log(LOG_DEBUG, $msg);
372 * Find the first caller in the stack trace that's not a
373 * low-level database function and add a comment to the
374 * query string. This should then be visible in process lists
375 * and slow query logs, to help identify problem areas.
377 * Also marks whether this was a web GET/POST or which daemon
380 * @param string $string SQL query string
381 * @return string SQL query string, with a comment in it
383 function annotateQuery($string)
385 $ignore = array('annotateQuery',
393 $ignoreStatic = array('staticGet',
396 $here = get_class($this); // if we get confused
397 $bt = debug_backtrace();
399 // Find the first caller that's not us?
400 foreach ($bt as $frame) {
401 $func = $frame['function'];
402 if (isset($frame['type']) && $frame['type'] == '::') {
403 if (in_array($func, $ignoreStatic)) {
406 $here = $frame['class'] . '::' . $func;
408 } else if (isset($frame['type']) && $frame['type'] == '->') {
409 if ($frame['object'] === $this && in_array($func, $ignore)) {
412 if (in_array($func, $ignoreStatic)) {
413 continue; // @fixme this shouldn't be needed?
415 $here = get_class($frame['object']) . '->' . $func;
422 if (php_sapi_name() == 'cli') {
423 $context = basename($_SERVER['PHP_SELF']);
425 $context = $_SERVER['REQUEST_METHOD'];
428 // Slip the comment in after the first command,
429 // or DB_DataObject gets confused about handling inserts and such.
430 $parts = explode(' ', $string, 2);
431 $parts[0] .= " /* $context $here */";
432 return implode(' ', $parts);
435 // Sanitize a query for logging
436 // @fixme don't trim spaces in string literals
437 function sanitizeQuery($string)
439 $string = preg_replace('/\s+/', ' ', $string);
440 $string = trim($string);
444 // We overload so that 'SET NAMES "utf8"' is called for
449 global $_DB_DATAOBJECT;
451 $sum = $this->_getDbDsnMD5();
453 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
454 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
460 // @fixme horrible evil hack!
462 // In multisite configuration we don't want to keep around a separate
463 // connection for every database; we could end up with thousands of
464 // connections open per thread. In an ideal world we might keep
465 // a connection per server and select different databases, but that'd
466 // be reliant on having the same db username/pass as well.
468 // MySQL connections are cheap enough we're going to try just
469 // closing out the old connection and reopening when we encounter
472 // WARNING WARNING if we end up actually using multiple DBs at a time
473 // we'll need some fancier logic here.
474 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
475 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
479 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
483 $result = parent::_connect();
485 if ($result && !$exists) {
486 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
487 if (common_config('db', 'type') == 'mysql' &&
488 common_config('db', 'utf8')) {
489 $conn = $DB->connection;
491 if ($DB instanceof DB_mysqli) {
492 mysqli_set_charset($conn, 'utf8');
493 } else if ($DB instanceof DB_mysql) {
494 mysql_set_charset('utf8', $conn);
498 // Needed to make timestamp values usefully comparable.
499 if (common_config('db', 'type') == 'mysql') {
500 parent::_query("set time_zone='+0:00'");
507 // XXX: largely cadged from DB_DataObject
509 function _getDbDsnMD5()
511 if ($this->_database_dsn_md5) {
512 return $this->_database_dsn_md5;
515 $dsn = $this->_getDbDsn();
517 if (is_string($dsn)) {
520 /// support array based dsn's
521 $sum = md5(serialize($dsn));
529 global $_DB_DATAOBJECT;
531 if (empty($_DB_DATAOBJECT['CONFIG'])) {
532 DB_DataObject::_loadConfig();
535 $options = &$_DB_DATAOBJECT['CONFIG'];
537 // if the databse dsn dis defined in the object..
539 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
543 if (!$this->_database) {
544 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
547 if ($this->_database && !empty($options["database_{$this->_database}"])) {
548 $dsn = $options["database_{$this->_database}"];
549 } else if (!empty($options['database'])) {
550 $dsn = $options['database'];
555 // TRANS: Exception thrown when database name or Data Source Name could not be found.
556 throw new Exception(_("No database name or DSN found anywhere."));
562 static function blow()
564 $c = self::memcache();
570 $args = func_get_args();
572 $format = array_shift($args);
574 $keyPart = vsprintf($format, $args);
576 $cacheKey = Cache::key($keyPart);
578 return $c->delete($cacheKey);
581 function fixupTimestamps()
583 // Fake up timestamp columns
584 $columns = $this->table();
585 foreach ($columns as $name => $type) {
586 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
587 $this->$name = common_sql_now();
594 common_debug("debugDump: " . common_log_objstring($this));
597 function raiseError($message, $type = null, $behaviour = null)
599 $id = get_class($this);
600 if (!empty($this->id)) {
601 $id .= ':' . $this->id;
603 if ($message instanceof PEAR_Error) {
604 $message = $message->getMessage();
606 // Low level exception. No need for i18n as discussed with Brion.
607 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
610 static function cacheGet($keyPart)
612 $c = self::memcache();
618 $cacheKey = Cache::key($keyPart);
620 return $c->get($cacheKey);
623 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
625 $c = self::memcache();
631 $cacheKey = Cache::key($keyPart);
633 return $c->set($cacheKey, $value, $flag, $expiry);
636 static function valueString($v)
639 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
642 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
649 // Low level exception. No need for i18n as discussed with Brion.
650 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
653 // Low level exception. No need for i18n as discussed with Brion.
654 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");