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 listGetClass($cls, $keyCol, array $keyVals)
269 if (!is_a($cls, __CLASS__, true)) {
270 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
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::pivotGetClass($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) {
309 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
311 sprintf(__CLASS__ . "() got {$i->N} results for class $cls key $keyCol");
312 while ($i->fetch()) {
315 $result[$i->$keyCol][] = $copy;
317 foreach ($pkeyCols as $pkeyCol) {
318 $pkeyVal[] = $i->$pkeyCol;
320 $pkeyMap[$i->$keyCol][] = $pkeyVal;
323 foreach ($toFetch as $keyVal) {
324 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
332 function columnType($columnName)
334 $keys = $this->table();
335 if (!array_key_exists($columnName, $keys)) {
336 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
339 $def = $keys[$columnName];
341 if ($def & DB_DATAOBJECT_INT) {
349 * @todo FIXME: Should this return false on lookup fail to match getKV?
351 static function pkeyGetClass($cls, array $kv)
353 if (!is_a($cls, __CLASS__, true)) {
354 throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
356 $i = Memcached_DataObject::multicache($cls, $kv);
357 if ($i !== false) { // false == cache miss
361 foreach ($kv as $k => $v) {
363 // XXX: possible SQL injection...? Don't
364 // pass keys from the browser, eh.
365 $i->whereAdd("$k is null");
370 if ($i->find(true)) {
374 $c = self::memcache();
376 $ck = self::multicacheKey($cls, $kv);
386 $result = parent::insert();
388 $this->fixupTimestamps();
389 $this->encache(); // in case of cached negative lookups
394 function update($orig=null)
396 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
397 $orig->decache(); # might be different keys
399 $result = parent::update($orig);
401 $this->fixupTimestamps();
409 $this->decache(); # while we still have the values!
410 return parent::delete();
413 static function memcache() {
414 return Cache::instance();
417 static function cacheKey($cls, $k, $v) {
418 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
419 $e = new Exception();
420 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
421 str_replace("\n", " ", $e->getTraceAsString()));
423 $vstr = self::valueString($v);
424 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
427 static function getcached($cls, $k, $v) {
428 $c = Memcached_DataObject::memcache();
432 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
433 if (0 == strcasecmp($cls, 'User')) {
434 // Special case for User
435 if (is_object($obj) && is_object($obj->id)) {
436 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
437 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
447 // ini-based classes return number-indexed arrays. handbuilt
448 // classes return column => keytype. Make this uniform.
450 $keys = $this->keys();
452 $keyskeys = array_keys($keys);
454 if (is_string($keyskeys[0])) {
458 global $_DB_DATAOBJECT;
459 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
460 $this->databaseStructure();
463 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
468 $c = $this->memcache();
472 } else if ($this->tableName() == 'user' && is_object($this->id)) {
473 // Special case for User bug
474 $e = new Exception();
475 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
476 str_replace("\n", " ", $e->getTraceAsString()));
479 $keys = $this->_allCacheKeys();
481 foreach ($keys as $key) {
482 $c->set($key, $this);
489 $c = $this->memcache();
495 $keys = $this->_allCacheKeys();
497 foreach ($keys as $key) {
498 $c->delete($key, $this);
502 function _allCacheKeys()
506 $types = $this->keyTypes();
512 foreach ($types as $key => $type) {
514 assert(!empty($key));
517 if (empty($this->$key)) {
520 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
521 } else if ($type == 'K' || $type == 'N') {
523 $pval[] = self::valueString($this->$key);
525 // Low level exception. No need for i18n as discussed with Brion.
526 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
530 assert(count($pkey) > 0);
532 // XXX: should work for both compound and scalar pkeys
533 $pvals = implode(',', $pval);
534 $pkeys = implode(',', $pkey);
536 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
541 static function multicache($cls, $kv)
544 $c = self::memcache();
548 return $c->get(self::multicacheKey($cls, $kv));
552 static function multicacheKey($cls, $kv)
555 $pkeys = implode(',', array_keys($kv));
556 $pvals = implode(',', array_values($kv));
557 return self::cacheKey($cls, $pkeys, $pvals);
560 function getSearchEngine($table)
562 require_once INSTALLDIR.'/lib/search_engines.php';
564 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
565 if ('mysql' === common_config('db', 'type')) {
566 $type = common_config('search', 'type');
567 if ($type == 'like') {
568 $search_engine = new MySQLLikeSearch($this, $table);
569 } else if ($type == 'fulltext') {
570 $search_engine = new MySQLSearch($this, $table);
572 // Low level exception. No need for i18n as discussed with Brion.
573 throw new ServerException('Unknown search type: ' . $type);
576 $search_engine = new PGSearch($this, $table);
580 return $search_engine;
583 static function cachedQuery($cls, $qry, $expiry=3600)
585 $c = Memcached_DataObject::memcache();
591 $key_part = Cache::keyize($cls).':'.md5($qry);
592 $ckey = Cache::key($key_part);
593 $stored = $c->get($ckey);
595 if ($stored !== false) {
596 return new ArrayWrapper($stored);
602 while ($inst->fetch()) {
603 $cached[] = clone($inst);
606 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
607 return new ArrayWrapper($cached);
611 * sends query to database - this is the private one that must work
612 * - internal functions use this rather than $this->query()
614 * Overridden to do logging.
616 * @param string $string
618 * @return mixed none or PEAR_Error
620 function _query($string)
622 if (common_config('db', 'annotate_queries')) {
623 $string = $this->annotateQuery($string);
626 $start = microtime(true);
629 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
630 common_perf_counter('query', $string);
632 $result = parent::_query($string);
633 } catch (Exception $e) {
636 Event::handle('EndDBQuery', array($this, $string, &$result));
638 $delta = microtime(true) - $start;
640 $limit = common_config('db', 'log_slow_queries');
641 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
642 $clean = $this->sanitizeQuery($string);
644 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
646 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
648 common_log(LOG_DEBUG, $msg);
658 * Find the first caller in the stack trace that's not a
659 * low-level database function and add a comment to the
660 * query string. This should then be visible in process lists
661 * and slow query logs, to help identify problem areas.
663 * Also marks whether this was a web GET/POST or which daemon
666 * @param string $string SQL query string
667 * @return string SQL query string, with a comment in it
669 function annotateQuery($string)
671 $ignore = array('annotateQuery',
679 $ignoreStatic = array('getKV',
684 $here = get_class($this); // if we get confused
685 $bt = debug_backtrace();
687 // Find the first caller that's not us?
688 foreach ($bt as $frame) {
689 $func = $frame['function'];
690 if (isset($frame['type']) && $frame['type'] == '::') {
691 if (in_array($func, $ignoreStatic)) {
694 $here = $frame['class'] . '::' . $func;
696 } else if (isset($frame['type']) && $frame['type'] == '->') {
697 if ($frame['object'] === $this && in_array($func, $ignore)) {
700 if (in_array($func, $ignoreStatic)) {
701 continue; // @todo FIXME: This shouldn't be needed?
703 $here = get_class($frame['object']) . '->' . $func;
710 if (php_sapi_name() == 'cli') {
711 $context = basename($_SERVER['PHP_SELF']);
713 $context = $_SERVER['REQUEST_METHOD'];
716 // Slip the comment in after the first command,
717 // or DB_DataObject gets confused about handling inserts and such.
718 $parts = explode(' ', $string, 2);
719 $parts[0] .= " /* $context $here */";
720 return implode(' ', $parts);
723 // Sanitize a query for logging
724 // @fixme don't trim spaces in string literals
725 function sanitizeQuery($string)
727 $string = preg_replace('/\s+/', ' ', $string);
728 $string = trim($string);
732 // We overload so that 'SET NAMES "utf8"' is called for
737 global $_DB_DATAOBJECT;
739 $sum = $this->_getDbDsnMD5();
741 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
742 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
748 // @fixme horrible evil hack!
750 // In multisite configuration we don't want to keep around a separate
751 // connection for every database; we could end up with thousands of
752 // connections open per thread. In an ideal world we might keep
753 // a connection per server and select different databases, but that'd
754 // be reliant on having the same db username/pass as well.
756 // MySQL connections are cheap enough we're going to try just
757 // closing out the old connection and reopening when we encounter
760 // WARNING WARNING if we end up actually using multiple DBs at a time
761 // we'll need some fancier logic here.
762 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
763 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
767 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
771 $result = parent::_connect();
773 if ($result && !$exists) {
774 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
775 if (common_config('db', 'type') == 'mysql' &&
776 common_config('db', 'utf8')) {
777 $conn = $DB->connection;
779 if ($DB instanceof DB_mysqli) {
780 mysqli_set_charset($conn, 'utf8');
781 } else if ($DB instanceof DB_mysql) {
782 mysql_set_charset('utf8', $conn);
786 // Needed to make timestamp values usefully comparable.
787 if (common_config('db', 'type') == 'mysql') {
788 parent::_query("set time_zone='+0:00'");
795 // XXX: largely cadged from DB_DataObject
797 function _getDbDsnMD5()
799 if ($this->_database_dsn_md5) {
800 return $this->_database_dsn_md5;
803 $dsn = $this->_getDbDsn();
805 if (is_string($dsn)) {
808 /// support array based dsn's
809 $sum = md5(serialize($dsn));
817 global $_DB_DATAOBJECT;
819 if (empty($_DB_DATAOBJECT['CONFIG'])) {
820 DB_DataObject::_loadConfig();
823 $options = &$_DB_DATAOBJECT['CONFIG'];
825 // if the databse dsn dis defined in the object..
827 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
831 if (!$this->_database) {
832 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
835 if ($this->_database && !empty($options["database_{$this->_database}"])) {
836 $dsn = $options["database_{$this->_database}"];
837 } else if (!empty($options['database'])) {
838 $dsn = $options['database'];
843 // TRANS: Exception thrown when database name or Data Source Name could not be found.
844 throw new Exception(_('No database name or DSN found anywhere.'));
850 static function blow()
852 $c = self::memcache();
858 $args = func_get_args();
860 $format = array_shift($args);
862 $keyPart = vsprintf($format, $args);
864 $cacheKey = Cache::key($keyPart);
866 return $c->delete($cacheKey);
869 function fixupTimestamps()
871 // Fake up timestamp columns
872 $columns = $this->table();
873 foreach ($columns as $name => $type) {
874 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
875 $this->$name = common_sql_now();
882 common_debug("debugDump: " . common_log_objstring($this));
885 function raiseError($message, $type = null, $behaviour = null)
887 $id = get_class($this);
888 if (!empty($this->id)) {
889 $id .= ':' . $this->id;
891 if ($message instanceof PEAR_Error) {
892 $message = $message->getMessage();
894 // Low level exception. No need for i18n as discussed with Brion.
895 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
898 static function cacheGet($keyPart)
900 $c = self::memcache();
906 $cacheKey = Cache::key($keyPart);
908 return $c->get($cacheKey);
911 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
913 $c = self::memcache();
919 $cacheKey = Cache::key($keyPart);
921 return $c->set($cacheKey, $value, $flag, $expiry);
924 static function valueString($v)
927 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
930 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
937 // Low level exception. No need for i18n as discussed with Brion.
938 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
941 // Low level exception. No need for i18n as discussed with Brion.
942 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");