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 * 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 function multiGet($cls, $keyCol, $keyVals, $skipNulls=true)
79 $result = self::pivotGet($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 pivotGet($cls, $keyCol, $keyVals, $otherCols = array())
108 if (is_array($keyCol)) {
109 foreach ($keyVals as $keyVal) {
110 $result[implode(',', $keyVal)] = null;
113 $result = array_fill_keys($keyVals, null);
118 foreach ($keyVals as $keyVal) {
120 if (is_array($keyCol)) {
121 $kv = array_combine($keyCol, $keyVal);
123 $kv = array($keyCol => $keyVal);
126 $kv = array_merge($otherCols, $kv);
128 $i = self::multicache($cls, $kv);
131 if (is_array($keyCol)) {
132 $result[implode(',', $keyVal)] = $i;
134 $result[$keyVal] = $i;
136 } else if (!empty($keyVal)) {
137 $toFetch[] = $keyVal;
141 if (count($toFetch) > 0) {
142 $i = DB_DataObject::factory($cls);
144 throw new Exception(_('Cannot instantiate class ' . $cls));
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 $i = DB_DataObject::factory($cls);
251 throw new Exception(_('Cannot instantiate a ' . $cls));
253 $types = $i->keyTypes();
258 foreach ($types as $key => $type) {
259 if ($type == 'K' || $type == 'N') {
267 function listGet($cls, $keyCol, $keyVals)
269 $pkeyMap = array_fill_keys($keyVals, array());
270 $results = array_fill_keys($keyVals, array());
272 $pkeyCols = self::pkeyCols($cls);
277 // We only cache keys -- not objects!
279 foreach ($keyVals as $keyVal) {
280 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", $cls, $keyCol, $keyVal));
282 $pkeyMap[$keyVal] = $l;
283 $allPkeys = array_merge($allPkeys, $l);
285 $toFetch[] = $keyVal;
289 $keyResults = self::pivotGet($cls, $pkeyCols, $allPkeys);
291 foreach ($pkeyMap as $keyVal => $pkeyList) {
292 foreach ($pkeyList as $pkeyVal) {
293 $i = $keyResults[$pkeyVal];
295 $results[$keyVal][] = $i;
300 if (count($toFetch) > 0) {
301 $i = DB_DataObject::factory($cls);
303 throw new Exception(_('Cannot instantiate class ' . $cls));
305 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
307 while ($i->fetch()) {
310 $result[$i->$keyCol][] = $copy;
312 foreach ($pkeyCols as $pkeyCol) {
313 $pkeyVal[] = $i->$pkeyCol;
315 $pkeyMap[$i->$keyCol][] = $pkeyVal;
318 foreach ($toFetch as $keyVal) {
319 self::cacheSet(sprintf("%s:list-ids:%s:%s", $cls, $keyCol, $keyVal),
327 function columnType($columnName)
329 $keys = $this->table();
330 if (!array_key_exists($columnName, $keys)) {
331 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
334 $def = $keys[$columnName];
336 if ($def & DB_DATAOBJECT_INT) {
344 * @fixme Should this return false on lookup fail to match staticGet?
346 function pkeyGet($cls, $kv)
348 $i = Memcached_DataObject::multicache($cls, $kv);
349 if ($i !== false) { // false == cache miss
352 $i = DB_DataObject::factory($cls);
353 if (empty($i) || PEAR::isError($i)) {
356 foreach ($kv as $k => $v) {
358 // XXX: possible SQL injection...? Don't
359 // pass keys from the browser, eh.
360 $i->whereAdd("$k is null");
365 if ($i->find(true)) {
369 $c = self::memcache();
371 $ck = self::multicacheKey($cls, $kv);
381 $result = parent::insert();
383 $this->fixupTimestamps();
384 $this->encache(); // in case of cached negative lookups
389 function update($orig=null)
391 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
392 $orig->decache(); # might be different keys
394 $result = parent::update($orig);
396 $this->fixupTimestamps();
404 $this->decache(); # while we still have the values!
405 return parent::delete();
408 static function memcache() {
409 return Cache::instance();
412 static function cacheKey($cls, $k, $v) {
413 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
414 $e = new Exception();
415 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
416 str_replace("\n", " ", $e->getTraceAsString()));
418 $vstr = self::valueString($v);
419 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
422 static function getcached($cls, $k, $v) {
423 $c = Memcached_DataObject::memcache();
427 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
428 if (0 == strcasecmp($cls, 'User')) {
429 // Special case for User
430 if (is_object($obj) && is_object($obj->id)) {
431 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
432 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
442 // ini-based classes return number-indexed arrays. handbuilt
443 // classes return column => keytype. Make this uniform.
445 $keys = $this->keys();
447 $keyskeys = array_keys($keys);
449 if (is_string($keyskeys[0])) {
453 global $_DB_DATAOBJECT;
454 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
455 $this->databaseStructure();
458 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
463 $c = $this->memcache();
467 } else if ($this->tableName() == 'user' && is_object($this->id)) {
468 // Special case for User bug
469 $e = new Exception();
470 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
471 str_replace("\n", " ", $e->getTraceAsString()));
474 $keys = $this->_allCacheKeys();
476 foreach ($keys as $key) {
477 $c->set($key, $this);
484 $c = $this->memcache();
490 $keys = $this->_allCacheKeys();
492 foreach ($keys as $key) {
493 $c->delete($key, $this);
497 function _allCacheKeys()
501 $types = $this->keyTypes();
507 foreach ($types as $key => $type) {
509 assert(!empty($key));
512 if (empty($this->$key)) {
515 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
516 } else if ($type == 'K' || $type == 'N') {
518 $pval[] = self::valueString($this->$key);
520 // Low level exception. No need for i18n as discussed with Brion.
521 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
525 assert(count($pkey) > 0);
527 // XXX: should work for both compound and scalar pkeys
528 $pvals = implode(',', $pval);
529 $pkeys = implode(',', $pkey);
531 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
536 function multicache($cls, $kv)
539 $c = self::memcache();
543 return $c->get(self::multicacheKey($cls, $kv));
547 static function multicacheKey($cls, $kv)
550 $pkeys = implode(',', array_keys($kv));
551 $pvals = implode(',', array_values($kv));
552 return self::cacheKey($cls, $pkeys, $pvals);
555 function getSearchEngine($table)
557 require_once INSTALLDIR.'/lib/search_engines.php';
559 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
560 if ('mysql' === common_config('db', 'type')) {
561 $type = common_config('search', 'type');
562 if ($type == 'like') {
563 $search_engine = new MySQLLikeSearch($this, $table);
564 } else if ($type == 'fulltext') {
565 $search_engine = new MySQLSearch($this, $table);
567 // Low level exception. No need for i18n as discussed with Brion.
568 throw new ServerException('Unknown search type: ' . $type);
571 $search_engine = new PGSearch($this, $table);
575 return $search_engine;
578 static function cachedQuery($cls, $qry, $expiry=3600)
580 $c = Memcached_DataObject::memcache();
586 $key_part = Cache::keyize($cls).':'.md5($qry);
587 $ckey = Cache::key($key_part);
588 $stored = $c->get($ckey);
590 if ($stored !== false) {
591 return new ArrayWrapper($stored);
597 while ($inst->fetch()) {
598 $cached[] = clone($inst);
601 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
602 return new ArrayWrapper($cached);
606 * sends query to database - this is the private one that must work
607 * - internal functions use this rather than $this->query()
609 * Overridden to do logging.
611 * @param string $string
613 * @return mixed none or PEAR_Error
615 function _query($string)
617 if (common_config('db', 'annotate_queries')) {
618 $string = $this->annotateQuery($string);
621 $start = microtime(true);
624 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
625 common_perf_counter('query', $string);
627 $result = parent::_query($string);
628 } catch (Exception $e) {
631 Event::handle('EndDBQuery', array($this, $string, &$result));
633 $delta = microtime(true) - $start;
635 $limit = common_config('db', 'log_slow_queries');
636 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
637 $clean = $this->sanitizeQuery($string);
639 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
641 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
643 common_log(LOG_DEBUG, $msg);
653 * Find the first caller in the stack trace that's not a
654 * low-level database function and add a comment to the
655 * query string. This should then be visible in process lists
656 * and slow query logs, to help identify problem areas.
658 * Also marks whether this was a web GET/POST or which daemon
661 * @param string $string SQL query string
662 * @return string SQL query string, with a comment in it
664 function annotateQuery($string)
666 $ignore = array('annotateQuery',
674 $ignoreStatic = array('staticGet',
677 $here = get_class($this); // if we get confused
678 $bt = debug_backtrace();
680 // Find the first caller that's not us?
681 foreach ($bt as $frame) {
682 $func = $frame['function'];
683 if (isset($frame['type']) && $frame['type'] == '::') {
684 if (in_array($func, $ignoreStatic)) {
687 $here = $frame['class'] . '::' . $func;
689 } else if (isset($frame['type']) && $frame['type'] == '->') {
690 if ($frame['object'] === $this && in_array($func, $ignore)) {
693 if (in_array($func, $ignoreStatic)) {
694 continue; // @fixme this shouldn't be needed?
696 $here = get_class($frame['object']) . '->' . $func;
703 if (php_sapi_name() == 'cli') {
704 $context = basename($_SERVER['PHP_SELF']);
706 $context = $_SERVER['REQUEST_METHOD'];
709 // Slip the comment in after the first command,
710 // or DB_DataObject gets confused about handling inserts and such.
711 $parts = explode(' ', $string, 2);
712 $parts[0] .= " /* $context $here */";
713 return implode(' ', $parts);
716 // Sanitize a query for logging
717 // @fixme don't trim spaces in string literals
718 function sanitizeQuery($string)
720 $string = preg_replace('/\s+/', ' ', $string);
721 $string = trim($string);
725 // We overload so that 'SET NAMES "utf8"' is called for
730 global $_DB_DATAOBJECT;
732 $sum = $this->_getDbDsnMD5();
734 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
735 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
741 // @fixme horrible evil hack!
743 // In multisite configuration we don't want to keep around a separate
744 // connection for every database; we could end up with thousands of
745 // connections open per thread. In an ideal world we might keep
746 // a connection per server and select different databases, but that'd
747 // be reliant on having the same db username/pass as well.
749 // MySQL connections are cheap enough we're going to try just
750 // closing out the old connection and reopening when we encounter
753 // WARNING WARNING if we end up actually using multiple DBs at a time
754 // we'll need some fancier logic here.
755 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
756 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
760 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
764 $result = parent::_connect();
766 if ($result && !$exists) {
767 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
768 if (common_config('db', 'type') == 'mysql' &&
769 common_config('db', 'utf8')) {
770 $conn = $DB->connection;
772 if ($DB instanceof DB_mysqli) {
773 mysqli_set_charset($conn, 'utf8');
774 } else if ($DB instanceof DB_mysql) {
775 mysql_set_charset('utf8', $conn);
779 // Needed to make timestamp values usefully comparable.
780 if (common_config('db', 'type') == 'mysql') {
781 parent::_query("set time_zone='+0:00'");
788 // XXX: largely cadged from DB_DataObject
790 function _getDbDsnMD5()
792 if ($this->_database_dsn_md5) {
793 return $this->_database_dsn_md5;
796 $dsn = $this->_getDbDsn();
798 if (is_string($dsn)) {
801 /// support array based dsn's
802 $sum = md5(serialize($dsn));
810 global $_DB_DATAOBJECT;
812 if (empty($_DB_DATAOBJECT['CONFIG'])) {
813 DB_DataObject::_loadConfig();
816 $options = &$_DB_DATAOBJECT['CONFIG'];
818 // if the databse dsn dis defined in the object..
820 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
824 if (!$this->_database) {
825 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
828 if ($this->_database && !empty($options["database_{$this->_database}"])) {
829 $dsn = $options["database_{$this->_database}"];
830 } else if (!empty($options['database'])) {
831 $dsn = $options['database'];
836 // TRANS: Exception thrown when database name or Data Source Name could not be found.
837 throw new Exception(_("No database name or DSN found anywhere."));
843 static function blow()
845 $c = self::memcache();
851 $args = func_get_args();
853 $format = array_shift($args);
855 $keyPart = vsprintf($format, $args);
857 $cacheKey = Cache::key($keyPart);
859 return $c->delete($cacheKey);
862 function fixupTimestamps()
864 // Fake up timestamp columns
865 $columns = $this->table();
866 foreach ($columns as $name => $type) {
867 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
868 $this->$name = common_sql_now();
875 common_debug("debugDump: " . common_log_objstring($this));
878 function raiseError($message, $type = null, $behaviour = null)
880 $id = get_class($this);
881 if (!empty($this->id)) {
882 $id .= ':' . $this->id;
884 if ($message instanceof PEAR_Error) {
885 $message = $message->getMessage();
887 // Low level exception. No need for i18n as discussed with Brion.
888 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
891 static function cacheGet($keyPart)
893 $c = self::memcache();
899 $cacheKey = Cache::key($keyPart);
901 return $c->get($cacheKey);
904 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
906 $c = self::memcache();
912 $cacheKey = Cache::key($keyPart);
914 return $c->set($cacheKey, $value, $flag, $expiry);
917 static function valueString($v)
920 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
923 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
930 // Low level exception. No need for i18n as discussed with Brion.
931 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
934 // Low level exception. No need for i18n as discussed with Brion.
935 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");