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)
37 $keys = self::pkeyCols($cls);
38 if (count($keys) > 1) {
39 // FIXME: maybe call pkeyGet() ourselves?
40 throw new Exception('Use pkeyGet() for compound primary keys');
44 $i = Memcached_DataObject::getcached($cls, $k, $v);
45 if ($i === false) { // false == cache miss
46 $i = DB_DataObject::factory($cls);
51 $result = $i->get($k, $v);
56 // save the fact that no such row exists
57 $c = self::memcache();
59 $ck = self::cachekey($cls, $k, $v);
69 * Get multiple items from the database by key
71 * @param string $cls Class to fetch
72 * @param string $keyCol name of column for key
73 * @param array $keyVals key values to fetch
74 * @param boolean $skipNulls return only non-null results?
76 * @return array Array of objects, in order
78 function multiGet($cls, $keyCol, $keyVals, $skipNulls=true)
80 $result = self::pivotGet($cls, $keyCol, $keyVals);
82 $values = array_values($result);
86 foreach ($values as $value) {
94 return new ArrayWrapper($values);
98 * Get multiple items from the database by key
100 * @param string $cls Class to fetch
101 * @param string $keyCol name of column for key
102 * @param array $keyVals key values to fetch
103 * @param boolean $otherCols Other columns to hold fixed
105 * @return array Array mapping $keyVals to objects, or null if not found
107 static function pivotGet($cls, $keyCol, $keyVals, $otherCols = array())
109 if (is_array($keyCol)) {
110 foreach ($keyVals as $keyVal) {
111 $result[implode(',', $keyVal)] = null;
114 $result = array_fill_keys($keyVals, null);
119 foreach ($keyVals as $keyVal) {
121 if (is_array($keyCol)) {
122 $kv = array_combine($keyCol, $keyVal);
124 $kv = array($keyCol => $keyVal);
127 $kv = array_merge($otherCols, $kv);
129 $i = self::multicache($cls, $kv);
132 if (is_array($keyCol)) {
133 $result[implode(',', $keyVal)] = $i;
135 $result[$keyVal] = $i;
137 } else if (!empty($keyVal)) {
138 $toFetch[] = $keyVal;
142 if (count($toFetch) > 0) {
143 $i = DB_DataObject::factory($cls);
145 throw new Exception(_('Cannot instantiate class ' . $cls));
147 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
148 $i->$otherKeyCol = $otherKeyVal;
150 if (is_array($keyCol)) {
151 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
153 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
156 while ($i->fetch()) {
159 if (is_array($keyCol)) {
161 foreach ($keyCol as $k) {
164 $result[implode(',', $vals)] = $copy;
166 $result[$i->$keyCol] = $copy;
171 // Save state of DB misses
173 foreach ($toFetch as $keyVal) {
175 if (is_array($keyCol)) {
176 $r = $result[implode(',', $keyVal)];
178 $r = $result[$keyVal];
181 if (is_array($keyCol)) {
182 $kv = array_combine($keyCol, $keyVal);
184 $kv = array($keyCol => $keyVal);
186 $kv = array_merge($otherCols, $kv);
187 // save the fact that no such row exists
188 $c = self::memcache();
190 $ck = self::multicacheKey($cls, $kv);
200 static function _inMultiKey($i, $cols, $values)
204 foreach ($cols as $col) {
205 $types[$col] = $i->columnType($col);
212 foreach ($values as $value) {
222 foreach ($cols as $col) {
228 switch ($types[$col]) {
231 $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
234 $query .= sprintf("%s = %s", $col, $value[$i]);
248 static function pkeyCols($cls)
250 $i = DB_DataObject::factory($cls);
252 throw new Exception(_('Cannot instantiate a ' . $cls));
254 $types = $i->keyTypes();
259 foreach ($types as $key => $type) {
260 if ($type == 'K' || $type == 'N') {
268 function listGet($cls, $keyCol, $keyVals)
270 $pkeyMap = array_fill_keys($keyVals, array());
271 $result = array_fill_keys($keyVals, array());
273 $pkeyCols = self::pkeyCols($cls);
278 // We only cache keys -- not objects!
280 foreach ($keyVals as $keyVal) {
281 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
283 $pkeyMap[$keyVal] = $l;
284 foreach ($l as $pkey) {
288 $toFetch[] = $keyVal;
292 if (count($allPkeys) > 0) {
293 $keyResults = self::pivotGet($cls, $pkeyCols, $allPkeys);
295 foreach ($pkeyMap as $keyVal => $pkeyList) {
296 foreach ($pkeyList as $pkeyVal) {
297 $i = $keyResults[implode(',',$pkeyVal)];
299 $result[$keyVal][] = $i;
305 if (count($toFetch) > 0) {
306 $i = DB_DataObject::factory($cls);
308 throw new Exception(_('Cannot instantiate class ' . $cls));
310 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
312 sprintf("listGet() got {$i->N} results for class $cls key $keyCol");
313 while ($i->fetch()) {
316 $result[$i->$keyCol][] = $copy;
318 foreach ($pkeyCols as $pkeyCol) {
319 $pkeyVal[] = $i->$pkeyCol;
321 $pkeyMap[$i->$keyCol][] = $pkeyVal;
324 foreach ($toFetch as $keyVal) {
325 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
333 function columnType($columnName)
335 $keys = $this->table();
336 if (!array_key_exists($columnName, $keys)) {
337 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
340 $def = $keys[$columnName];
342 if ($def & DB_DATAOBJECT_INT) {
350 * @todo FIXME: Should this return false on lookup fail to match staticGet?
352 function pkeyGet($cls, $kv)
354 $i = Memcached_DataObject::multicache($cls, $kv);
355 if ($i !== false) { // false == cache miss
358 $i = DB_DataObject::factory($cls);
359 if (empty($i) || PEAR::isError($i)) {
362 foreach ($kv as $k => $v) {
364 // XXX: possible SQL injection...? Don't
365 // pass keys from the browser, eh.
366 $i->whereAdd("$k is null");
371 if ($i->find(true)) {
375 $c = self::memcache();
377 $ck = self::multicacheKey($cls, $kv);
387 $result = parent::insert();
389 $this->fixupTimestamps();
390 $this->encache(); // in case of cached negative lookups
395 function update($orig=null)
397 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
398 $orig->decache(); # might be different keys
400 $result = parent::update($orig);
402 $this->fixupTimestamps();
410 $this->decache(); # while we still have the values!
411 return parent::delete();
414 static function memcache() {
415 return Cache::instance();
418 static function cacheKey($cls, $k, $v) {
419 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
420 $e = new Exception();
421 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
422 str_replace("\n", " ", $e->getTraceAsString()));
424 $vstr = self::valueString($v);
425 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
428 static function getcached($cls, $k, $v) {
429 $c = Memcached_DataObject::memcache();
433 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
434 if (0 == strcasecmp($cls, 'User')) {
435 // Special case for User
436 if (is_object($obj) && is_object($obj->id)) {
437 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
438 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
448 // ini-based classes return number-indexed arrays. handbuilt
449 // classes return column => keytype. Make this uniform.
451 $keys = $this->keys();
453 $keyskeys = array_keys($keys);
455 if (is_string($keyskeys[0])) {
459 global $_DB_DATAOBJECT;
460 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
461 $this->databaseStructure();
464 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
469 $c = $this->memcache();
473 } else if ($this->tableName() == 'user' && is_object($this->id)) {
474 // Special case for User bug
475 $e = new Exception();
476 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
477 str_replace("\n", " ", $e->getTraceAsString()));
480 $keys = $this->_allCacheKeys();
482 foreach ($keys as $key) {
483 $c->set($key, $this);
490 $c = $this->memcache();
496 $keys = $this->_allCacheKeys();
498 foreach ($keys as $key) {
499 $c->delete($key, $this);
503 function _allCacheKeys()
507 $types = $this->keyTypes();
513 foreach ($types as $key => $type) {
515 assert(!empty($key));
518 if (empty($this->$key)) {
521 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
522 } else if ($type == 'K' || $type == 'N') {
524 $pval[] = self::valueString($this->$key);
526 // Low level exception. No need for i18n as discussed with Brion.
527 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
531 assert(count($pkey) > 0);
533 // XXX: should work for both compound and scalar pkeys
534 $pvals = implode(',', $pval);
535 $pkeys = implode(',', $pkey);
537 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
542 function multicache($cls, $kv)
545 $c = self::memcache();
549 return $c->get(self::multicacheKey($cls, $kv));
553 static function multicacheKey($cls, $kv)
556 $pkeys = implode(',', array_keys($kv));
557 $pvals = implode(',', array_values($kv));
558 return self::cacheKey($cls, $pkeys, $pvals);
561 function getSearchEngine($table)
563 require_once INSTALLDIR.'/lib/search_engines.php';
565 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
566 if ('mysql' === common_config('db', 'type')) {
567 $type = common_config('search', 'type');
568 if ($type == 'like') {
569 $search_engine = new MySQLLikeSearch($this, $table);
570 } else if ($type == 'fulltext') {
571 $search_engine = new MySQLSearch($this, $table);
573 // Low level exception. No need for i18n as discussed with Brion.
574 throw new ServerException('Unknown search type: ' . $type);
577 $search_engine = new PGSearch($this, $table);
581 return $search_engine;
584 static function cachedQuery($cls, $qry, $expiry=3600)
586 $c = Memcached_DataObject::memcache();
592 $key_part = Cache::keyize($cls).':'.md5($qry);
593 $ckey = Cache::key($key_part);
594 $stored = $c->get($ckey);
596 if ($stored !== false) {
597 return new ArrayWrapper($stored);
603 while ($inst->fetch()) {
604 $cached[] = clone($inst);
607 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
608 return new ArrayWrapper($cached);
612 * sends query to database - this is the private one that must work
613 * - internal functions use this rather than $this->query()
615 * Overridden to do logging.
617 * @param string $string
619 * @return mixed none or PEAR_Error
621 function _query($string)
623 if (common_config('db', 'annotate_queries')) {
624 $string = $this->annotateQuery($string);
627 $start = microtime(true);
630 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
631 common_perf_counter('query', $string);
633 $result = parent::_query($string);
634 } catch (Exception $e) {
637 Event::handle('EndDBQuery', array($this, $string, &$result));
639 $delta = microtime(true) - $start;
641 $limit = common_config('db', 'log_slow_queries');
642 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
643 $clean = $this->sanitizeQuery($string);
645 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
647 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
649 common_log(LOG_DEBUG, $msg);
659 * Find the first caller in the stack trace that's not a
660 * low-level database function and add a comment to the
661 * query string. This should then be visible in process lists
662 * and slow query logs, to help identify problem areas.
664 * Also marks whether this was a web GET/POST or which daemon
667 * @param string $string SQL query string
668 * @return string SQL query string, with a comment in it
670 function annotateQuery($string)
672 $ignore = array('annotateQuery',
680 $ignoreStatic = array('staticGet',
683 $here = get_class($this); // if we get confused
684 $bt = debug_backtrace();
686 // Find the first caller that's not us?
687 foreach ($bt as $frame) {
688 $func = $frame['function'];
689 if (isset($frame['type']) && $frame['type'] == '::') {
690 if (in_array($func, $ignoreStatic)) {
693 $here = $frame['class'] . '::' . $func;
695 } else if (isset($frame['type']) && $frame['type'] == '->') {
696 if ($frame['object'] === $this && in_array($func, $ignore)) {
699 if (in_array($func, $ignoreStatic)) {
700 continue; // @todo FIXME: This shouldn't be needed?
702 $here = get_class($frame['object']) . '->' . $func;
709 if (php_sapi_name() == 'cli') {
710 $context = basename($_SERVER['PHP_SELF']);
712 $context = $_SERVER['REQUEST_METHOD'];
715 // Slip the comment in after the first command,
716 // or DB_DataObject gets confused about handling inserts and such.
717 $parts = explode(' ', $string, 2);
718 $parts[0] .= " /* $context $here */";
719 return implode(' ', $parts);
722 // Sanitize a query for logging
723 // @fixme don't trim spaces in string literals
724 function sanitizeQuery($string)
726 $string = preg_replace('/\s+/', ' ', $string);
727 $string = trim($string);
731 // We overload so that 'SET NAMES "utf8"' is called for
736 global $_DB_DATAOBJECT;
738 $sum = $this->_getDbDsnMD5();
740 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
741 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
747 // @fixme horrible evil hack!
749 // In multisite configuration we don't want to keep around a separate
750 // connection for every database; we could end up with thousands of
751 // connections open per thread. In an ideal world we might keep
752 // a connection per server and select different databases, but that'd
753 // be reliant on having the same db username/pass as well.
755 // MySQL connections are cheap enough we're going to try just
756 // closing out the old connection and reopening when we encounter
759 // WARNING WARNING if we end up actually using multiple DBs at a time
760 // we'll need some fancier logic here.
761 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
762 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
766 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
770 $result = parent::_connect();
772 if ($result && !$exists) {
773 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
774 if (common_config('db', 'type') == 'mysql' &&
775 common_config('db', 'utf8')) {
776 $conn = $DB->connection;
778 if ($DB instanceof DB_mysqli) {
779 mysqli_set_charset($conn, 'utf8');
780 } else if ($DB instanceof DB_mysql) {
781 mysql_set_charset('utf8', $conn);
785 // Needed to make timestamp values usefully comparable.
786 if (common_config('db', 'type') == 'mysql') {
787 parent::_query("set time_zone='+0:00'");
794 // XXX: largely cadged from DB_DataObject
796 function _getDbDsnMD5()
798 if ($this->_database_dsn_md5) {
799 return $this->_database_dsn_md5;
802 $dsn = $this->_getDbDsn();
804 if (is_string($dsn)) {
807 /// support array based dsn's
808 $sum = md5(serialize($dsn));
816 global $_DB_DATAOBJECT;
818 if (empty($_DB_DATAOBJECT['CONFIG'])) {
819 DB_DataObject::_loadConfig();
822 $options = &$_DB_DATAOBJECT['CONFIG'];
824 // if the databse dsn dis defined in the object..
826 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
830 if (!$this->_database) {
831 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
834 if ($this->_database && !empty($options["database_{$this->_database}"])) {
835 $dsn = $options["database_{$this->_database}"];
836 } else if (!empty($options['database'])) {
837 $dsn = $options['database'];
842 // TRANS: Exception thrown when database name or Data Source Name could not be found.
843 throw new Exception(_('No database name or DSN found anywhere.'));
849 static function blow()
851 $c = self::memcache();
857 $args = func_get_args();
859 $format = array_shift($args);
861 $keyPart = vsprintf($format, $args);
863 $cacheKey = Cache::key($keyPart);
865 return $c->delete($cacheKey);
868 function fixupTimestamps()
870 // Fake up timestamp columns
871 $columns = $this->table();
872 foreach ($columns as $name => $type) {
873 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
874 $this->$name = common_sql_now();
881 common_debug("debugDump: " . common_log_objstring($this));
884 function raiseError($message, $type = null, $behaviour = null)
886 $id = get_class($this);
887 if (!empty($this->id)) {
888 $id .= ':' . $this->id;
890 if ($message instanceof PEAR_Error) {
891 $message = $message->getMessage();
893 // Low level exception. No need for i18n as discussed with Brion.
894 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
897 static function cacheGet($keyPart)
899 $c = self::memcache();
905 $cacheKey = Cache::key($keyPart);
907 return $c->get($cacheKey);
910 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
912 $c = self::memcache();
918 $cacheKey = Cache::key($keyPart);
920 return $c->set($cacheKey, $value, $flag, $expiry);
923 static function valueString($v)
926 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
929 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
936 // Low level exception. No need for i18n as discussed with Brion.
937 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
940 // Low level exception. No need for i18n as discussed with Brion.
941 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");