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 // TRANS: Exception thrown when a program code class (%s) cannot be instantiated.
146 throw new Exception(sprintf(_('Cannot instantiate class %s.'),$cls));
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)
251 $i = DB_DataObject::factory($cls);
253 // TRANS: Exception thrown when a program code class (%s) cannot be instantiated.
254 throw new Exception(sprintf(_('Cannot instantiate class %s.'),$cls));
256 $types = $i->keyTypes();
261 foreach ($types as $key => $type) {
262 if ($type == 'K' || $type == 'N') {
270 function listGet($cls, $keyCol, $keyVals)
272 $pkeyMap = array_fill_keys($keyVals, array());
273 $result = array_fill_keys($keyVals, array());
275 $pkeyCols = self::pkeyCols($cls);
280 // We only cache keys -- not objects!
282 foreach ($keyVals as $keyVal) {
283 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
285 $pkeyMap[$keyVal] = $l;
286 foreach ($l as $pkey) {
290 $toFetch[] = $keyVal;
294 if (count($allPkeys) > 0) {
295 $keyResults = self::pivotGet($cls, $pkeyCols, $allPkeys);
297 foreach ($pkeyMap as $keyVal => $pkeyList) {
298 foreach ($pkeyList as $pkeyVal) {
299 $i = $keyResults[implode(',',$pkeyVal)];
301 $result[$keyVal][] = $i;
307 if (count($toFetch) > 0) {
308 $i = DB_DataObject::factory($cls);
310 // TRANS: Exception thrown when a program code class (%s) cannot be instantiated.
311 throw new Exception(sprintf(_('Cannot instantiate class %s.'),$cls));
313 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
315 sprintf("listGet() got {$i->N} results for class $cls key $keyCol");
316 while ($i->fetch()) {
319 $result[$i->$keyCol][] = $copy;
321 foreach ($pkeyCols as $pkeyCol) {
322 $pkeyVal[] = $i->$pkeyCol;
324 $pkeyMap[$i->$keyCol][] = $pkeyVal;
327 foreach ($toFetch as $keyVal) {
328 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
336 function columnType($columnName)
338 $keys = $this->table();
339 if (!array_key_exists($columnName, $keys)) {
340 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
343 $def = $keys[$columnName];
345 if ($def & DB_DATAOBJECT_INT) {
353 * @todo FIXME: Should this return false on lookup fail to match staticGet?
355 function pkeyGet($cls, $kv)
357 $i = Memcached_DataObject::multicache($cls, $kv);
358 if ($i !== false) { // false == cache miss
361 $i = DB_DataObject::factory($cls);
362 if (empty($i) || PEAR::isError($i)) {
365 foreach ($kv as $k => $v) {
367 // XXX: possible SQL injection...? Don't
368 // pass keys from the browser, eh.
369 $i->whereAdd("$k is null");
374 if ($i->find(true)) {
378 $c = self::memcache();
380 $ck = self::multicacheKey($cls, $kv);
390 $result = parent::insert();
392 $this->fixupTimestamps();
393 $this->encache(); // in case of cached negative lookups
398 function update($orig=null)
400 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
401 $orig->decache(); # might be different keys
403 $result = parent::update($orig);
405 $this->fixupTimestamps();
413 $this->decache(); # while we still have the values!
414 return parent::delete();
417 static function memcache() {
418 return Cache::instance();
421 static function cacheKey($cls, $k, $v) {
422 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
423 $e = new Exception();
424 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
425 str_replace("\n", " ", $e->getTraceAsString()));
427 $vstr = self::valueString($v);
428 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
431 static function getcached($cls, $k, $v) {
432 $c = Memcached_DataObject::memcache();
436 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
437 if (0 == strcasecmp($cls, 'User')) {
438 // Special case for User
439 if (is_object($obj) && is_object($obj->id)) {
440 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
441 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
451 // ini-based classes return number-indexed arrays. handbuilt
452 // classes return column => keytype. Make this uniform.
454 $keys = $this->keys();
456 $keyskeys = array_keys($keys);
458 if (is_string($keyskeys[0])) {
462 global $_DB_DATAOBJECT;
463 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
464 $this->databaseStructure();
467 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
472 $c = $this->memcache();
476 } else if ($this->tableName() == 'user' && is_object($this->id)) {
477 // Special case for User bug
478 $e = new Exception();
479 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
480 str_replace("\n", " ", $e->getTraceAsString()));
483 $keys = $this->_allCacheKeys();
485 foreach ($keys as $key) {
486 $c->set($key, $this);
493 $c = $this->memcache();
499 $keys = $this->_allCacheKeys();
501 foreach ($keys as $key) {
502 $c->delete($key, $this);
506 function _allCacheKeys()
510 $types = $this->keyTypes();
516 foreach ($types as $key => $type) {
518 assert(!empty($key));
521 if (empty($this->$key)) {
524 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
525 } else if ($type == 'K' || $type == 'N') {
527 $pval[] = self::valueString($this->$key);
529 // Low level exception. No need for i18n as discussed with Brion.
530 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
534 assert(count($pkey) > 0);
536 // XXX: should work for both compound and scalar pkeys
537 $pvals = implode(',', $pval);
538 $pkeys = implode(',', $pkey);
540 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
545 function multicache($cls, $kv)
548 $c = self::memcache();
552 return $c->get(self::multicacheKey($cls, $kv));
556 static function multicacheKey($cls, $kv)
559 $pkeys = implode(',', array_keys($kv));
560 $pvals = implode(',', array_values($kv));
561 return self::cacheKey($cls, $pkeys, $pvals);
564 function getSearchEngine($table)
566 require_once INSTALLDIR.'/lib/search_engines.php';
568 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
569 if ('mysql' === common_config('db', 'type')) {
570 $type = common_config('search', 'type');
571 if ($type == 'like') {
572 $search_engine = new MySQLLikeSearch($this, $table);
573 } else if ($type == 'fulltext') {
574 $search_engine = new MySQLSearch($this, $table);
576 // Low level exception. No need for i18n as discussed with Brion.
577 throw new ServerException('Unknown search type: ' . $type);
580 $search_engine = new PGSearch($this, $table);
584 return $search_engine;
587 static function cachedQuery($cls, $qry, $expiry=3600)
589 $c = Memcached_DataObject::memcache();
595 $key_part = Cache::keyize($cls).':'.md5($qry);
596 $ckey = Cache::key($key_part);
597 $stored = $c->get($ckey);
599 if ($stored !== false) {
600 return new ArrayWrapper($stored);
606 while ($inst->fetch()) {
607 $cached[] = clone($inst);
610 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
611 return new ArrayWrapper($cached);
615 * sends query to database - this is the private one that must work
616 * - internal functions use this rather than $this->query()
618 * Overridden to do logging.
620 * @param string $string
622 * @return mixed none or PEAR_Error
624 function _query($string)
626 if (common_config('db', 'annotate_queries')) {
627 $string = $this->annotateQuery($string);
630 $start = microtime(true);
633 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
634 common_perf_counter('query', $string);
636 $result = parent::_query($string);
637 } catch (Exception $e) {
640 Event::handle('EndDBQuery', array($this, $string, &$result));
642 $delta = microtime(true) - $start;
644 $limit = common_config('db', 'log_slow_queries');
645 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
646 $clean = $this->sanitizeQuery($string);
648 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
650 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
652 common_log(LOG_DEBUG, $msg);
662 * Find the first caller in the stack trace that's not a
663 * low-level database function and add a comment to the
664 * query string. This should then be visible in process lists
665 * and slow query logs, to help identify problem areas.
667 * Also marks whether this was a web GET/POST or which daemon
670 * @param string $string SQL query string
671 * @return string SQL query string, with a comment in it
673 function annotateQuery($string)
675 $ignore = array('annotateQuery',
683 $ignoreStatic = array('staticGet',
686 $here = get_class($this); // if we get confused
687 $bt = debug_backtrace();
689 // Find the first caller that's not us?
690 foreach ($bt as $frame) {
691 $func = $frame['function'];
692 if (isset($frame['type']) && $frame['type'] == '::') {
693 if (in_array($func, $ignoreStatic)) {
696 $here = $frame['class'] . '::' . $func;
698 } else if (isset($frame['type']) && $frame['type'] == '->') {
699 if ($frame['object'] === $this && in_array($func, $ignore)) {
702 if (in_array($func, $ignoreStatic)) {
703 continue; // @todo FIXME: This shouldn't be needed?
705 $here = get_class($frame['object']) . '->' . $func;
712 if (php_sapi_name() == 'cli') {
713 $context = basename($_SERVER['PHP_SELF']);
715 $context = $_SERVER['REQUEST_METHOD'];
718 // Slip the comment in after the first command,
719 // or DB_DataObject gets confused about handling inserts and such.
720 $parts = explode(' ', $string, 2);
721 $parts[0] .= " /* $context $here */";
722 return implode(' ', $parts);
725 // Sanitize a query for logging
726 // @fixme don't trim spaces in string literals
727 function sanitizeQuery($string)
729 $string = preg_replace('/\s+/', ' ', $string);
730 $string = trim($string);
734 // We overload so that 'SET NAMES "utf8"' is called for
739 global $_DB_DATAOBJECT;
741 $sum = $this->_getDbDsnMD5();
743 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
744 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
750 // @fixme horrible evil hack!
752 // In multisite configuration we don't want to keep around a separate
753 // connection for every database; we could end up with thousands of
754 // connections open per thread. In an ideal world we might keep
755 // a connection per server and select different databases, but that'd
756 // be reliant on having the same db username/pass as well.
758 // MySQL connections are cheap enough we're going to try just
759 // closing out the old connection and reopening when we encounter
762 // WARNING WARNING if we end up actually using multiple DBs at a time
763 // we'll need some fancier logic here.
764 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
765 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
769 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
773 $result = parent::_connect();
775 if ($result && !$exists) {
776 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
777 if (common_config('db', 'type') == 'mysql' &&
778 common_config('db', 'utf8')) {
779 $conn = $DB->connection;
781 if ($DB instanceof DB_mysqli) {
782 mysqli_set_charset($conn, 'utf8');
783 } else if ($DB instanceof DB_mysql) {
784 mysql_set_charset('utf8', $conn);
788 // Needed to make timestamp values usefully comparable.
789 if (common_config('db', 'type') == 'mysql') {
790 parent::_query("set time_zone='+0:00'");
797 // XXX: largely cadged from DB_DataObject
799 function _getDbDsnMD5()
801 if ($this->_database_dsn_md5) {
802 return $this->_database_dsn_md5;
805 $dsn = $this->_getDbDsn();
807 if (is_string($dsn)) {
810 /// support array based dsn's
811 $sum = md5(serialize($dsn));
819 global $_DB_DATAOBJECT;
821 if (empty($_DB_DATAOBJECT['CONFIG'])) {
822 DB_DataObject::_loadConfig();
825 $options = &$_DB_DATAOBJECT['CONFIG'];
827 // if the databse dsn dis defined in the object..
829 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
833 if (!$this->_database) {
834 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
837 if ($this->_database && !empty($options["database_{$this->_database}"])) {
838 $dsn = $options["database_{$this->_database}"];
839 } else if (!empty($options['database'])) {
840 $dsn = $options['database'];
845 // TRANS: Exception thrown when database name or Data Source Name could not be found.
846 throw new Exception(_('No database name or DSN found anywhere.'));
852 static function blow()
854 $c = self::memcache();
860 $args = func_get_args();
862 $format = array_shift($args);
864 $keyPart = vsprintf($format, $args);
866 $cacheKey = Cache::key($keyPart);
868 return $c->delete($cacheKey);
871 function fixupTimestamps()
873 // Fake up timestamp columns
874 $columns = $this->table();
875 foreach ($columns as $name => $type) {
876 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
877 $this->$name = common_sql_now();
884 common_debug("debugDump: " . common_log_objstring($this));
887 function raiseError($message, $type = null, $behaviour = null)
889 $id = get_class($this);
890 if (!empty($this->id)) {
891 $id .= ':' . $this->id;
893 if ($message instanceof PEAR_Error) {
894 $message = $message->getMessage();
896 // Low level exception. No need for i18n as discussed with Brion.
897 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
900 static function cacheGet($keyPart)
902 $c = self::memcache();
908 $cacheKey = Cache::key($keyPart);
910 return $c->get($cacheKey);
913 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
915 $c = self::memcache();
921 $cacheKey = Cache::key($keyPart);
923 return $c->set($cacheKey, $value, $flag, $expiry);
926 static function valueString($v)
929 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
932 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
939 // Low level exception. No need for i18n as discussed with Brion.
940 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
943 // Low level exception. No need for i18n as discussed with Brion.
944 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");