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('GNUSOCIAL')) { 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)
37 $keys = self::pkeyCols($cls);
38 if (count($keys) > 1) {
39 // FIXME: maybe call pkeyGetClass() ourselves?
40 throw new Exception('Use pkeyGetClass() for compound primary keys');
44 $i = self::getcached($cls, $k, $v);
45 if ($i === false) { // false == cache miss
47 $result = $i->get($k, $v);
52 // save the fact that no such row exists
53 $c = self::memcache();
55 $ck = self::cachekey($cls, $k, $v);
65 * Get multiple items from the database by key
67 * @param string $cls Class to fetch
68 * @param string $keyCol name of column for key
69 * @param array $keyVals key values to fetch
71 * @return array Array of objects, in order
73 static function multiGetClass($cls, $keyCol, array $keyVals)
77 // php-compatible, for settype(), datatype
78 $colType = $obj->columnType($keyCol);
80 if (!in_array($colType, array('integer', 'int'))) {
81 // This is because I'm afraid to escape strings incorrectly
82 // in the way we use them below in FIND_IN_SET for MariaDB
83 throw new ServerException('Cannot do multiGet on anything but integer columns');
86 $obj->whereAddIn($keyCol, $keyVals, $colType);
88 // Since we're inputting straight to a query: format and escape
89 foreach ($keyVals as $key=>$val) {
90 settype($val, $colType);
91 $keyVals[$key] = $obj->escape($val);
94 // FIND_IN_SET will make sure we keep the desired order
95 $obj->orderBy(sprintf("FIND_IN_SET(%s, '%s')", $keyCol, implode(',', $keyVals)));
102 * Get multiple items from the database by key
104 * @param string $cls Class to fetch
105 * @param string $keyCol name of column for key
106 * @param array $keyVals key values to fetch
107 * @param boolean $otherCols Other columns to hold fixed
109 * @return array Array mapping $keyVals to objects, or null if not found
111 static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
113 if (is_array($keyCol)) {
114 foreach ($keyVals as $keyVal) {
115 $result[implode(',', $keyVal)] = null;
118 $result = array_fill_keys($keyVals, null);
123 foreach ($keyVals as $keyVal) {
125 if (is_array($keyCol)) {
126 $kv = array_combine($keyCol, $keyVal);
128 $kv = array($keyCol => $keyVal);
131 $kv = array_merge($otherCols, $kv);
133 $i = self::multicache($cls, $kv);
136 if (is_array($keyCol)) {
137 $result[implode(',', $keyVal)] = $i;
139 $result[$keyVal] = $i;
141 } else if (!empty($keyVal)) {
142 $toFetch[] = $keyVal;
146 if (count($toFetch) > 0) {
148 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
149 $i->$otherKeyCol = $otherKeyVal;
151 if (is_array($keyCol)) {
152 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
154 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
157 while ($i->fetch()) {
160 if (is_array($keyCol)) {
162 foreach ($keyCol as $k) {
165 $result[implode(',', $vals)] = $copy;
167 $result[$i->$keyCol] = $copy;
172 // Save state of DB misses
174 foreach ($toFetch as $keyVal) {
176 if (is_array($keyCol)) {
177 $r = $result[implode(',', $keyVal)];
179 $r = $result[$keyVal];
182 if (is_array($keyCol)) {
183 $kv = array_combine($keyCol, $keyVal);
185 $kv = array($keyCol => $keyVal);
187 $kv = array_merge($otherCols, $kv);
188 // save the fact that no such row exists
189 $c = self::memcache();
191 $ck = self::multicacheKey($cls, $kv);
201 static function _inMultiKey($i, $cols, $values)
205 foreach ($cols as $col) {
206 $types[$col] = $i->columnType($col);
213 foreach ($values as $value) {
223 foreach ($cols as $col) {
229 switch ($types[$col]) {
232 $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
235 $query .= sprintf("%s = %s", $col, $value[$i]);
249 static function pkeyCols($cls)
252 $types = $i->keyTypes();
257 foreach ($types as $key => $type) {
258 if ($type == 'K' || $type == 'N') {
266 static function listFindClass($cls, $keyCol, array $keyVals)
269 $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
271 throw new NoResultException($i);
277 static function listGetClass($cls, $keyCol, array $keyVals)
279 $pkeyMap = array_fill_keys($keyVals, array());
280 $result = array_fill_keys($keyVals, array());
282 $pkeyCols = self::pkeyCols($cls);
287 // We only cache keys -- not objects!
289 foreach ($keyVals as $keyVal) {
290 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
292 $pkeyMap[$keyVal] = $l;
293 foreach ($l as $pkey) {
297 $toFetch[] = $keyVal;
301 if (count($allPkeys) > 0) {
302 $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
304 foreach ($pkeyMap as $keyVal => $pkeyList) {
305 foreach ($pkeyList as $pkeyVal) {
306 $i = $keyResults[implode(',',$pkeyVal)];
308 $result[$keyVal][] = $i;
314 if (count($toFetch) > 0) {
316 $i = self::listFindClass($cls, $keyCol, $toFetch);
318 while ($i->fetch()) {
321 $result[$i->$keyCol][] = $copy;
323 foreach ($pkeyCols as $pkeyCol) {
324 $pkeyVal[] = $i->$pkeyCol;
326 $pkeyMap[$i->$keyCol][] = $pkeyVal;
328 } catch (NoResultException $e) {
329 // no results found for our keyVals, so we leave them as empty arrays
331 foreach ($toFetch as $keyVal) {
332 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
340 function columnType($columnName)
342 $keys = $this->table();
343 if (!array_key_exists($columnName, $keys)) {
344 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
347 $def = $keys[$columnName];
349 if ($def & DB_DATAOBJECT_INT) {
357 * @todo FIXME: Should this return false on lookup fail to match getKV?
359 static function pkeyGetClass($cls, array $kv)
361 $i = self::multicache($cls, $kv);
362 if ($i !== false) { // false == cache miss
366 foreach ($kv as $k => $v) {
368 // XXX: possible SQL injection...? Don't
369 // pass keys from the browser, eh.
370 $i->whereAdd("$k is null");
375 if ($i->find(true)) {
379 $c = self::memcache();
381 $ck = self::multicacheKey($cls, $kv);
391 $result = parent::insert();
393 $this->fixupTimestamps();
394 $this->encache(); // in case of cached negative lookups
399 function update($dataObject=false)
401 if (is_object($dataObject) && $dataObject instanceof Memcached_DataObject) {
402 $dataObject->decache(); # might be different keys
404 $result = parent::update($dataObject);
405 if ($result !== false) {
406 $this->fixupTimestamps();
412 function delete($useWhere=false)
414 $this->decache(); # while we still have the values!
415 return parent::delete($useWhere);
418 static function memcache() {
419 return Cache::instance();
422 static function cacheKey($cls, $k, $v) {
423 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
424 $e = new Exception();
425 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
426 str_replace("\n", " ", $e->getTraceAsString()));
428 $vstr = self::valueString($v);
429 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
432 static function getcached($cls, $k, $v) {
433 $c = self::memcache();
437 $obj = $c->get(self::cacheKey($cls, $k, $v));
438 if (0 == strcasecmp($cls, 'User')) {
439 // Special case for User
440 if (is_object($obj) && is_object($obj->id)) {
441 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
442 $c->delete(self::cacheKey($cls, $k, $v));
452 // ini-based classes return number-indexed arrays. handbuilt
453 // classes return column => keytype. Make this uniform.
455 $keys = $this->keys();
457 $keyskeys = array_keys($keys);
459 if (is_string($keyskeys[0])) {
463 global $_DB_DATAOBJECT;
464 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
465 $this->databaseStructure();
468 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
473 $c = self::memcache();
477 } else if ($this->tableName() == 'user' && is_object($this->id)) {
478 // Special case for User bug
479 $e = new Exception();
480 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
481 str_replace("\n", " ", $e->getTraceAsString()));
484 $keys = $this->_allCacheKeys();
486 foreach ($keys as $key) {
487 $c->set($key, $this);
494 $c = self::memcache();
500 $keys = $this->_allCacheKeys();
502 foreach ($keys as $key) {
503 $c->delete($key, $this);
507 function _allCacheKeys()
511 $types = $this->keyTypes();
517 foreach ($types as $key => $type) {
519 assert(!empty($key));
522 if (empty($this->$key)) {
525 $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
526 } else if ($type == 'K' || $type == 'N') {
528 $pval[] = self::valueString($this->$key);
530 // Low level exception. No need for i18n as discussed with Brion.
531 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
535 assert(count($pkey) > 0);
537 // XXX: should work for both compound and scalar pkeys
538 $pvals = implode(',', $pval);
539 $pkeys = implode(',', $pkey);
541 $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
546 static function multicache($cls, $kv)
549 $c = self::memcache();
553 return $c->get(self::multicacheKey($cls, $kv));
557 static function multicacheKey($cls, $kv)
560 $pkeys = implode(',', array_keys($kv));
561 $pvals = implode(',', array_values($kv));
562 return self::cacheKey($cls, $pkeys, $pvals);
565 function getSearchEngine($table)
567 require_once INSTALLDIR.'/lib/search_engines.php';
569 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
570 if ('mysql' === common_config('db', 'type')) {
571 $type = common_config('search', 'type');
572 if ($type == 'like') {
573 $search_engine = new MySQLLikeSearch($this, $table);
574 } else if ($type == 'fulltext') {
575 $search_engine = new MySQLSearch($this, $table);
577 // Low level exception. No need for i18n as discussed with Brion.
578 throw new ServerException('Unknown search type: ' . $type);
581 $search_engine = new PGSearch($this, $table);
585 return $search_engine;
588 static function cachedQuery($cls, $qry, $expiry=3600)
590 $c = self::memcache();
596 $key_part = Cache::keyize($cls).':'.md5($qry);
597 $ckey = Cache::key($key_part);
598 $stored = $c->get($ckey);
600 if ($stored !== false) {
601 return new ArrayWrapper($stored);
607 while ($inst->fetch()) {
608 $cached[] = clone($inst);
611 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
612 return new ArrayWrapper($cached);
616 * sends query to database - this is the private one that must work
617 * - internal functions use this rather than $this->query()
619 * Overridden to do logging.
621 * @param string $string
623 * @return mixed none or PEAR_Error
625 function _query($string)
627 if (common_config('db', 'annotate_queries')) {
628 $string = $this->annotateQuery($string);
631 $start = microtime(true);
634 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
635 common_perf_counter('query', $string);
637 $result = parent::_query($string);
638 } catch (Exception $e) {
641 Event::handle('EndDBQuery', array($this, $string, &$result));
643 $delta = microtime(true) - $start;
645 $limit = common_config('db', 'log_slow_queries');
646 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
647 $clean = $this->sanitizeQuery($string);
649 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
651 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
663 * Find the first caller in the stack trace that's not a
664 * low-level database function and add a comment to the
665 * query string. This should then be visible in process lists
666 * and slow query logs, to help identify problem areas.
668 * Also marks whether this was a web GET/POST or which daemon
671 * @param string $string SQL query string
672 * @return string SQL query string, with a comment in it
674 function annotateQuery($string)
676 $ignore = array('annotateQuery',
684 $ignoreStatic = array('getKV',
689 $here = get_class($this); // if we get confused
690 $bt = debug_backtrace();
692 // Find the first caller that's not us?
693 foreach ($bt as $frame) {
694 $func = $frame['function'];
695 if (isset($frame['type']) && $frame['type'] == '::') {
696 if (in_array($func, $ignoreStatic)) {
699 $here = $frame['class'] . '::' . $func;
701 } else if (isset($frame['type']) && $frame['type'] == '->') {
702 if ($frame['object'] === $this && in_array($func, $ignore)) {
705 if (in_array($func, $ignoreStatic)) {
706 continue; // @todo FIXME: This shouldn't be needed?
708 $here = get_class($frame['object']) . '->' . $func;
715 if (php_sapi_name() == 'cli') {
716 $context = basename($_SERVER['PHP_SELF']);
718 $context = $_SERVER['REQUEST_METHOD'];
721 // Slip the comment in after the first command,
722 // or DB_DataObject gets confused about handling inserts and such.
723 $parts = explode(' ', $string, 2);
724 $parts[0] .= " /* $context $here */";
725 return implode(' ', $parts);
728 // Sanitize a query for logging
729 // @fixme don't trim spaces in string literals
730 function sanitizeQuery($string)
732 $string = preg_replace('/\s+/', ' ', $string);
733 $string = trim($string);
737 // We overload so that 'SET NAMES "utf8"' is called for
742 global $_DB_DATAOBJECT, $_PEAR;
744 $sum = $this->_getDbDsnMD5();
746 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
747 !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
753 // @fixme horrible evil hack!
755 // In multisite configuration we don't want to keep around a separate
756 // connection for every database; we could end up with thousands of
757 // connections open per thread. In an ideal world we might keep
758 // a connection per server and select different databases, but that'd
759 // be reliant on having the same db username/pass as well.
761 // MySQL connections are cheap enough we're going to try just
762 // closing out the old connection and reopening when we encounter
765 // WARNING WARNING if we end up actually using multiple DBs at a time
766 // we'll need some fancier logic here.
767 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
768 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
769 if ($_PEAR->isError($conn)) {
770 common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
771 } elseif (!empty($conn)) {
774 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
778 $result = parent::_connect();
780 if ($result && !$exists) {
781 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
782 if (common_config('db', 'type') == 'mysql' &&
783 common_config('db', 'utf8')) {
784 $conn = $DB->connection;
786 if ($DB instanceof DB_mysqli || $DB instanceof MDB2_Driver_mysqli) {
787 mysqli_set_charset($conn, 'utf8');
788 } else if ($DB instanceof DB_mysql || $DB instanceof MDB2_Driver_mysql) {
789 mysql_set_charset('utf8', $conn);
793 // Needed to make timestamp values usefully comparable.
794 if (common_config('db', 'type') == 'mysql') {
795 parent::_query("set time_zone='+0:00'");
802 // XXX: largely cadged from DB_DataObject
804 function _getDbDsnMD5()
806 if ($this->_database_dsn_md5) {
807 return $this->_database_dsn_md5;
810 $dsn = $this->_getDbDsn();
812 if (is_string($dsn)) {
815 /// support array based dsn's
816 $sum = md5(serialize($dsn));
824 global $_DB_DATAOBJECT;
826 if (empty($_DB_DATAOBJECT['CONFIG'])) {
827 DB_DataObject::_loadConfig();
830 $options = &$_DB_DATAOBJECT['CONFIG'];
832 // if the databse dsn dis defined in the object..
834 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
838 if (!$this->_database) {
839 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
842 if ($this->_database && !empty($options["database_{$this->_database}"])) {
843 $dsn = $options["database_{$this->_database}"];
844 } else if (!empty($options['database'])) {
845 $dsn = $options['database'];
850 // TRANS: Exception thrown when database name or Data Source Name could not be found.
851 throw new Exception(_('No database name or DSN found anywhere.'));
857 static function blow()
859 $c = self::memcache();
865 $args = func_get_args();
867 $format = array_shift($args);
869 $keyPart = vsprintf($format, $args);
871 $cacheKey = Cache::key($keyPart);
873 return $c->delete($cacheKey);
876 function fixupTimestamps()
878 // Fake up timestamp columns
879 $columns = $this->table();
880 foreach ($columns as $name => $type) {
881 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
882 $this->$name = common_sql_now();
889 common_debug("debugDump: " . common_log_objstring($this));
892 function raiseError($message, $type = null, $behaviour = null)
894 $id = get_class($this);
895 if (!empty($this->id)) {
896 $id .= ':' . $this->id;
898 if ($message instanceof PEAR_Error) {
899 $message = $message->getMessage();
901 // Low level exception. No need for i18n as discussed with Brion.
902 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
905 static function cacheGet($keyPart)
907 $c = self::memcache();
913 $cacheKey = Cache::key($keyPart);
915 return $c->get($cacheKey);
918 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
920 $c = self::memcache();
926 $cacheKey = Cache::key($keyPart);
928 return $c->set($cacheKey, $value, $flag, $expiry);
931 static function valueString($v)
934 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
937 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
944 // Low level exception. No need for i18n as discussed with Brion.
945 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
948 // Low level exception. No need for i18n as discussed with Brion.
949 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");