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 static function getClassKV($cls, $k, $v=null)
35 if (!is_a($cls, __CLASS__, true)) {
36 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
40 $keys = self::pkeyCols($cls);
41 if (count($keys) > 1) {
42 // FIXME: maybe call pkeyGetClass() ourselves?
43 throw new Exception('Use pkeyGetClass() for compound primary keys');
47 $i = self::getcached($cls, $k, $v);
48 if ($i === false) { // false == cache miss
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 static function multiGetClass($cls, $keyCol, array $keyVals, $skipNulls=true)
79 $result = self::pivotGetClass($cls, $keyCol, $keyVals);
81 $values = array_values($result);
85 foreach ($values as $value) {
93 return new ArrayWrapper($values);
97 * Get multiple items from the database by key
99 * @param string $cls Class to fetch
100 * @param string $keyCol name of column for key
101 * @param array $keyVals key values to fetch
102 * @param boolean $otherCols Other columns to hold fixed
104 * @return array Array mapping $keyVals to objects, or null if not found
106 static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
108 if (!is_a($cls, __CLASS__, true)) {
109 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
111 if (is_array($keyCol)) {
112 foreach ($keyVals as $keyVal) {
113 $result[implode(',', $keyVal)] = null;
116 $result = array_fill_keys($keyVals, null);
121 foreach ($keyVals as $keyVal) {
123 if (is_array($keyCol)) {
124 $kv = array_combine($keyCol, $keyVal);
126 $kv = array($keyCol => $keyVal);
129 $kv = array_merge($otherCols, $kv);
131 $i = self::multicache($cls, $kv);
134 if (is_array($keyCol)) {
135 $result[implode(',', $keyVal)] = $i;
137 $result[$keyVal] = $i;
139 } else if (!empty($keyVal)) {
140 $toFetch[] = $keyVal;
144 if (count($toFetch) > 0) {
146 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
147 $i->$otherKeyCol = $otherKeyVal;
149 if (is_array($keyCol)) {
150 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
152 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
155 while ($i->fetch()) {
158 if (is_array($keyCol)) {
160 foreach ($keyCol as $k) {
163 $result[implode(',', $vals)] = $copy;
165 $result[$i->$keyCol] = $copy;
170 // Save state of DB misses
172 foreach ($toFetch as $keyVal) {
174 if (is_array($keyCol)) {
175 $r = $result[implode(',', $keyVal)];
177 $r = $result[$keyVal];
180 if (is_array($keyCol)) {
181 $kv = array_combine($keyCol, $keyVal);
183 $kv = array($keyCol => $keyVal);
185 $kv = array_merge($otherCols, $kv);
186 // save the fact that no such row exists
187 $c = self::memcache();
189 $ck = self::multicacheKey($cls, $kv);
199 static function _inMultiKey($i, $cols, $values)
203 foreach ($cols as $col) {
204 $types[$col] = $i->columnType($col);
211 foreach ($values as $value) {
221 foreach ($cols as $col) {
227 switch ($types[$col]) {
230 $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
233 $query .= sprintf("%s = %s", $col, $value[$i]);
247 static function pkeyCols($cls)
249 if (!is_a($cls, __CLASS__, true)) {
250 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
253 $types = $i->keyTypes();
258 foreach ($types as $key => $type) {
259 if ($type == 'K' || $type == 'N') {
267 static function listFindClass($cls, $keyCol, array $keyVals)
269 if (!is_a($cls, __CLASS__, true)) {
270 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
274 $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
276 throw new NoResultException($i);
279 sprintf(__CLASS__ . "() got {$i->N} results for class $cls key $keyCol");
283 static function listGetClass($cls, $keyCol, array $keyVals)
285 if (!is_a($cls, __CLASS__, true)) {
286 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
288 $pkeyMap = array_fill_keys($keyVals, array());
289 $result = array_fill_keys($keyVals, array());
291 $pkeyCols = self::pkeyCols($cls);
296 // We only cache keys -- not objects!
298 foreach ($keyVals as $keyVal) {
299 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
301 $pkeyMap[$keyVal] = $l;
302 foreach ($l as $pkey) {
306 $toFetch[] = $keyVal;
310 if (count($allPkeys) > 0) {
311 $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
313 foreach ($pkeyMap as $keyVal => $pkeyList) {
314 foreach ($pkeyList as $pkeyVal) {
315 $i = $keyResults[implode(',',$pkeyVal)];
317 $result[$keyVal][] = $i;
323 if (count($toFetch) > 0) {
325 $i = self::listFindClass($cls, $keyCol, $toFetch);
327 while ($i->fetch()) {
330 $result[$i->$keyCol][] = $copy;
332 foreach ($pkeyCols as $pkeyCol) {
333 $pkeyVal[] = $i->$pkeyCol;
335 $pkeyMap[$i->$keyCol][] = $pkeyVal;
337 } catch (NoResultException $e) {
338 // no results foudn for our keyVals, so we leave them as empty arrays
340 foreach ($toFetch as $keyVal) {
341 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
349 function columnType($columnName)
351 $keys = $this->table();
352 if (!array_key_exists($columnName, $keys)) {
353 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
356 $def = $keys[$columnName];
358 if ($def & DB_DATAOBJECT_INT) {
366 * @todo FIXME: Should this return false on lookup fail to match getKV?
368 static function pkeyGetClass($cls, array $kv)
370 if (!is_a($cls, __CLASS__, true)) {
371 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
373 $i = Memcached_DataObject::multicache($cls, $kv);
374 if ($i !== false) { // false == cache miss
378 foreach ($kv as $k => $v) {
380 // XXX: possible SQL injection...? Don't
381 // pass keys from the browser, eh.
382 $i->whereAdd("$k is null");
387 if ($i->find(true)) {
391 $c = self::memcache();
393 $ck = self::multicacheKey($cls, $kv);
403 $result = parent::insert();
405 $this->fixupTimestamps();
406 $this->encache(); // in case of cached negative lookups
411 function update($orig=null)
413 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
414 $orig->decache(); # might be different keys
416 $result = parent::update($orig);
418 $this->fixupTimestamps();
426 $this->decache(); # while we still have the values!
427 return parent::delete();
430 static function memcache() {
431 return Cache::instance();
434 static function cacheKey($cls, $k, $v) {
435 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
436 $e = new Exception();
437 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
438 str_replace("\n", " ", $e->getTraceAsString()));
440 $vstr = self::valueString($v);
441 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
444 static function getcached($cls, $k, $v) {
445 $c = Memcached_DataObject::memcache();
449 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
450 if (0 == strcasecmp($cls, 'User')) {
451 // Special case for User
452 if (is_object($obj) && is_object($obj->id)) {
453 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
454 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
464 // ini-based classes return number-indexed arrays. handbuilt
465 // classes return column => keytype. Make this uniform.
467 $keys = $this->keys();
469 $keyskeys = array_keys($keys);
471 if (is_string($keyskeys[0])) {
475 global $_DB_DATAOBJECT;
476 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
477 $this->databaseStructure();
480 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
485 $c = $this->memcache();
489 } else if ($this->tableName() == 'user' && is_object($this->id)) {
490 // Special case for User bug
491 $e = new Exception();
492 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
493 str_replace("\n", " ", $e->getTraceAsString()));
496 $keys = $this->_allCacheKeys();
498 foreach ($keys as $key) {
499 $c->set($key, $this);
506 $c = $this->memcache();
512 $keys = $this->_allCacheKeys();
514 foreach ($keys as $key) {
515 $c->delete($key, $this);
519 function _allCacheKeys()
523 $types = $this->keyTypes();
529 foreach ($types as $key => $type) {
531 assert(!empty($key));
534 if (empty($this->$key)) {
537 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
538 } else if ($type == 'K' || $type == 'N') {
540 $pval[] = self::valueString($this->$key);
542 // Low level exception. No need for i18n as discussed with Brion.
543 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
547 assert(count($pkey) > 0);
549 // XXX: should work for both compound and scalar pkeys
550 $pvals = implode(',', $pval);
551 $pkeys = implode(',', $pkey);
553 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
558 static function multicache($cls, $kv)
561 $c = self::memcache();
565 return $c->get(self::multicacheKey($cls, $kv));
569 static function multicacheKey($cls, $kv)
572 $pkeys = implode(',', array_keys($kv));
573 $pvals = implode(',', array_values($kv));
574 return self::cacheKey($cls, $pkeys, $pvals);
577 function getSearchEngine($table)
579 require_once INSTALLDIR.'/lib/search_engines.php';
581 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
582 if ('mysql' === common_config('db', 'type')) {
583 $type = common_config('search', 'type');
584 if ($type == 'like') {
585 $search_engine = new MySQLLikeSearch($this, $table);
586 } else if ($type == 'fulltext') {
587 $search_engine = new MySQLSearch($this, $table);
589 // Low level exception. No need for i18n as discussed with Brion.
590 throw new ServerException('Unknown search type: ' . $type);
593 $search_engine = new PGSearch($this, $table);
597 return $search_engine;
600 static function cachedQuery($cls, $qry, $expiry=3600)
602 $c = Memcached_DataObject::memcache();
608 $key_part = Cache::keyize($cls).':'.md5($qry);
609 $ckey = Cache::key($key_part);
610 $stored = $c->get($ckey);
612 if ($stored !== false) {
613 return new ArrayWrapper($stored);
619 while ($inst->fetch()) {
620 $cached[] = clone($inst);
623 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
624 return new ArrayWrapper($cached);
628 * sends query to database - this is the private one that must work
629 * - internal functions use this rather than $this->query()
631 * Overridden to do logging.
633 * @param string $string
635 * @return mixed none or PEAR_Error
637 function _query($string)
639 if (common_config('db', 'annotate_queries')) {
640 $string = $this->annotateQuery($string);
643 $start = microtime(true);
646 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
647 common_perf_counter('query', $string);
649 $result = parent::_query($string);
650 } catch (Exception $e) {
653 Event::handle('EndDBQuery', array($this, $string, &$result));
655 $delta = microtime(true) - $start;
657 $limit = common_config('db', 'log_slow_queries');
658 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
659 $clean = $this->sanitizeQuery($string);
661 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
663 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
665 common_log(LOG_DEBUG, $msg);
675 * Find the first caller in the stack trace that's not a
676 * low-level database function and add a comment to the
677 * query string. This should then be visible in process lists
678 * and slow query logs, to help identify problem areas.
680 * Also marks whether this was a web GET/POST or which daemon
683 * @param string $string SQL query string
684 * @return string SQL query string, with a comment in it
686 function annotateQuery($string)
688 $ignore = array('annotateQuery',
696 $ignoreStatic = array('getKV',
701 $here = get_class($this); // if we get confused
702 $bt = debug_backtrace();
704 // Find the first caller that's not us?
705 foreach ($bt as $frame) {
706 $func = $frame['function'];
707 if (isset($frame['type']) && $frame['type'] == '::') {
708 if (in_array($func, $ignoreStatic)) {
711 $here = $frame['class'] . '::' . $func;
713 } else if (isset($frame['type']) && $frame['type'] == '->') {
714 if ($frame['object'] === $this && in_array($func, $ignore)) {
717 if (in_array($func, $ignoreStatic)) {
718 continue; // @todo FIXME: This shouldn't be needed?
720 $here = get_class($frame['object']) . '->' . $func;
727 if (php_sapi_name() == 'cli') {
728 $context = basename($_SERVER['PHP_SELF']);
730 $context = $_SERVER['REQUEST_METHOD'];
733 // Slip the comment in after the first command,
734 // or DB_DataObject gets confused about handling inserts and such.
735 $parts = explode(' ', $string, 2);
736 $parts[0] .= " /* $context $here */";
737 return implode(' ', $parts);
740 // Sanitize a query for logging
741 // @fixme don't trim spaces in string literals
742 function sanitizeQuery($string)
744 $string = preg_replace('/\s+/', ' ', $string);
745 $string = trim($string);
749 // We overload so that 'SET NAMES "utf8"' is called for
754 global $_DB_DATAOBJECT;
756 $sum = $this->_getDbDsnMD5();
758 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
759 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
765 // @fixme horrible evil hack!
767 // In multisite configuration we don't want to keep around a separate
768 // connection for every database; we could end up with thousands of
769 // connections open per thread. In an ideal world we might keep
770 // a connection per server and select different databases, but that'd
771 // be reliant on having the same db username/pass as well.
773 // MySQL connections are cheap enough we're going to try just
774 // closing out the old connection and reopening when we encounter
777 // WARNING WARNING if we end up actually using multiple DBs at a time
778 // we'll need some fancier logic here.
779 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
780 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
784 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
788 $result = parent::_connect();
790 if ($result && !$exists) {
791 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
792 if (common_config('db', 'type') == 'mysql' &&
793 common_config('db', 'utf8')) {
794 $conn = $DB->connection;
796 if ($DB instanceof DB_mysqli) {
797 mysqli_set_charset($conn, 'utf8');
798 } else if ($DB instanceof DB_mysql) {
799 mysql_set_charset('utf8', $conn);
803 // Needed to make timestamp values usefully comparable.
804 if (common_config('db', 'type') == 'mysql') {
805 parent::_query("set time_zone='+0:00'");
812 // XXX: largely cadged from DB_DataObject
814 function _getDbDsnMD5()
816 if ($this->_database_dsn_md5) {
817 return $this->_database_dsn_md5;
820 $dsn = $this->_getDbDsn();
822 if (is_string($dsn)) {
825 /// support array based dsn's
826 $sum = md5(serialize($dsn));
834 global $_DB_DATAOBJECT;
836 if (empty($_DB_DATAOBJECT['CONFIG'])) {
837 DB_DataObject::_loadConfig();
840 $options = &$_DB_DATAOBJECT['CONFIG'];
842 // if the databse dsn dis defined in the object..
844 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
848 if (!$this->_database) {
849 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
852 if ($this->_database && !empty($options["database_{$this->_database}"])) {
853 $dsn = $options["database_{$this->_database}"];
854 } else if (!empty($options['database'])) {
855 $dsn = $options['database'];
860 // TRANS: Exception thrown when database name or Data Source Name could not be found.
861 throw new Exception(_('No database name or DSN found anywhere.'));
867 static function blow()
869 $c = self::memcache();
875 $args = func_get_args();
877 $format = array_shift($args);
879 $keyPart = vsprintf($format, $args);
881 $cacheKey = Cache::key($keyPart);
883 return $c->delete($cacheKey);
886 function fixupTimestamps()
888 // Fake up timestamp columns
889 $columns = $this->table();
890 foreach ($columns as $name => $type) {
891 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
892 $this->$name = common_sql_now();
899 common_debug("debugDump: " . common_log_objstring($this));
902 function raiseError($message, $type = null, $behaviour = null)
904 $id = get_class($this);
905 if (!empty($this->id)) {
906 $id .= ':' . $this->id;
908 if ($message instanceof PEAR_Error) {
909 $message = $message->getMessage();
911 // Low level exception. No need for i18n as discussed with Brion.
912 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
915 static function cacheGet($keyPart)
917 $c = self::memcache();
923 $cacheKey = Cache::key($keyPart);
925 return $c->get($cacheKey);
928 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
930 $c = self::memcache();
936 $cacheKey = Cache::key($keyPart);
938 return $c->set($cacheKey, $value, $flag, $expiry);
941 static function valueString($v)
944 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
947 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
954 // Low level exception. No need for i18n as discussed with Brion.
955 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
958 // Low level exception. No need for i18n as discussed with Brion.
959 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");