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
70 * @param boolean $skipNulls return only non-null results?
72 * @return array Array of objects, in order
74 static function multiGetClass($cls, $keyCol, array $keyVals, $skipNulls=true)
76 $result = self::pivotGetClass($cls, $keyCol, $keyVals);
78 $values = array_values($result);
82 foreach ($values as $value) {
90 return new ArrayWrapper($values);
94 * Get multiple items from the database by key
96 * @param string $cls Class to fetch
97 * @param string $keyCol name of column for key
98 * @param array $keyVals key values to fetch
99 * @param boolean $otherCols Other columns to hold fixed
101 * @return array Array mapping $keyVals to objects, or null if not found
103 static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
105 if (is_array($keyCol)) {
106 foreach ($keyVals as $keyVal) {
107 $result[implode(',', $keyVal)] = null;
110 $result = array_fill_keys($keyVals, null);
115 foreach ($keyVals as $keyVal) {
117 if (is_array($keyCol)) {
118 $kv = array_combine($keyCol, $keyVal);
120 $kv = array($keyCol => $keyVal);
123 $kv = array_merge($otherCols, $kv);
125 $i = self::multicache($cls, $kv);
128 if (is_array($keyCol)) {
129 $result[implode(',', $keyVal)] = $i;
131 $result[$keyVal] = $i;
133 } else if (!empty($keyVal)) {
134 $toFetch[] = $keyVal;
138 if (count($toFetch) > 0) {
140 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
141 $i->$otherKeyCol = $otherKeyVal;
143 if (is_array($keyCol)) {
144 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
146 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
149 while ($i->fetch()) {
152 if (is_array($keyCol)) {
154 foreach ($keyCol as $k) {
157 $result[implode(',', $vals)] = $copy;
159 $result[$i->$keyCol] = $copy;
164 // Save state of DB misses
166 foreach ($toFetch as $keyVal) {
168 if (is_array($keyCol)) {
169 $r = $result[implode(',', $keyVal)];
171 $r = $result[$keyVal];
174 if (is_array($keyCol)) {
175 $kv = array_combine($keyCol, $keyVal);
177 $kv = array($keyCol => $keyVal);
179 $kv = array_merge($otherCols, $kv);
180 // save the fact that no such row exists
181 $c = self::memcache();
183 $ck = self::multicacheKey($cls, $kv);
193 static function _inMultiKey($i, $cols, $values)
197 foreach ($cols as $col) {
198 $types[$col] = $i->columnType($col);
205 foreach ($values as $value) {
215 foreach ($cols as $col) {
221 switch ($types[$col]) {
224 $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
227 $query .= sprintf("%s = %s", $col, $value[$i]);
241 static function pkeyCols($cls)
244 $types = $i->keyTypes();
249 foreach ($types as $key => $type) {
250 if ($type == 'K' || $type == 'N') {
258 static function listFindClass($cls, $keyCol, array $keyVals)
261 $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
263 throw new NoResultException($i);
269 static function listGetClass($cls, $keyCol, array $keyVals)
271 $pkeyMap = array_fill_keys($keyVals, array());
272 $result = array_fill_keys($keyVals, array());
274 $pkeyCols = self::pkeyCols($cls);
279 // We only cache keys -- not objects!
281 foreach ($keyVals as $keyVal) {
282 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
284 $pkeyMap[$keyVal] = $l;
285 foreach ($l as $pkey) {
289 $toFetch[] = $keyVal;
293 if (count($allPkeys) > 0) {
294 $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
296 foreach ($pkeyMap as $keyVal => $pkeyList) {
297 foreach ($pkeyList as $pkeyVal) {
298 $i = $keyResults[implode(',',$pkeyVal)];
300 $result[$keyVal][] = $i;
306 if (count($toFetch) > 0) {
308 $i = self::listFindClass($cls, $keyCol, $toFetch);
310 while ($i->fetch()) {
313 $result[$i->$keyCol][] = $copy;
315 foreach ($pkeyCols as $pkeyCol) {
316 $pkeyVal[] = $i->$pkeyCol;
318 $pkeyMap[$i->$keyCol][] = $pkeyVal;
320 } catch (NoResultException $e) {
321 // no results found for our keyVals, so we leave them as empty arrays
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 $i = self::multicache($cls, $kv);
354 if ($i !== false) { // false == cache miss
358 foreach ($kv as $k => $v) {
360 // XXX: possible SQL injection...? Don't
361 // pass keys from the browser, eh.
362 $i->whereAdd("$k is null");
367 if ($i->find(true)) {
371 $c = self::memcache();
373 $ck = self::multicacheKey($cls, $kv);
383 $result = parent::insert();
385 $this->fixupTimestamps();
386 $this->encache(); // in case of cached negative lookups
391 function update($dataObject=false)
393 if (is_object($dataObject) && $dataObject instanceof Memcached_DataObject) {
394 $dataObject->decache(); # might be different keys
396 $result = parent::update($dataObject);
397 if ($result !== false) {
398 $this->fixupTimestamps();
406 $this->decache(); # while we still have the values!
407 return parent::delete();
410 static function memcache() {
411 return Cache::instance();
414 static function cacheKey($cls, $k, $v) {
415 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
416 $e = new Exception();
417 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
418 str_replace("\n", " ", $e->getTraceAsString()));
420 $vstr = self::valueString($v);
421 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
424 static function getcached($cls, $k, $v) {
425 $c = self::memcache();
429 $obj = $c->get(self::cacheKey($cls, $k, $v));
430 if (0 == strcasecmp($cls, 'User')) {
431 // Special case for User
432 if (is_object($obj) && is_object($obj->id)) {
433 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
434 $c->delete(self::cacheKey($cls, $k, $v));
444 // ini-based classes return number-indexed arrays. handbuilt
445 // classes return column => keytype. Make this uniform.
447 $keys = $this->keys();
449 $keyskeys = array_keys($keys);
451 if (is_string($keyskeys[0])) {
455 global $_DB_DATAOBJECT;
456 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
457 $this->databaseStructure();
460 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
465 $c = self::memcache();
469 } else if ($this->tableName() == 'user' && is_object($this->id)) {
470 // Special case for User bug
471 $e = new Exception();
472 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
473 str_replace("\n", " ", $e->getTraceAsString()));
476 $keys = $this->_allCacheKeys();
478 foreach ($keys as $key) {
479 $c->set($key, $this);
486 $c = self::memcache();
492 $keys = $this->_allCacheKeys();
494 foreach ($keys as $key) {
495 $c->delete($key, $this);
499 function _allCacheKeys()
503 $types = $this->keyTypes();
509 foreach ($types as $key => $type) {
511 assert(!empty($key));
514 if (empty($this->$key)) {
517 $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
518 } else if ($type == 'K' || $type == 'N') {
520 $pval[] = self::valueString($this->$key);
522 // Low level exception. No need for i18n as discussed with Brion.
523 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
527 assert(count($pkey) > 0);
529 // XXX: should work for both compound and scalar pkeys
530 $pvals = implode(',', $pval);
531 $pkeys = implode(',', $pkey);
533 $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
538 static function multicache($cls, $kv)
541 $c = self::memcache();
545 return $c->get(self::multicacheKey($cls, $kv));
549 static function multicacheKey($cls, $kv)
552 $pkeys = implode(',', array_keys($kv));
553 $pvals = implode(',', array_values($kv));
554 return self::cacheKey($cls, $pkeys, $pvals);
557 function getSearchEngine($table)
559 require_once INSTALLDIR.'/lib/search_engines.php';
561 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
562 if ('mysql' === common_config('db', 'type')) {
563 $type = common_config('search', 'type');
564 if ($type == 'like') {
565 $search_engine = new MySQLLikeSearch($this, $table);
566 } else if ($type == 'fulltext') {
567 $search_engine = new MySQLSearch($this, $table);
569 // Low level exception. No need for i18n as discussed with Brion.
570 throw new ServerException('Unknown search type: ' . $type);
573 $search_engine = new PGSearch($this, $table);
577 return $search_engine;
580 static function cachedQuery($cls, $qry, $expiry=3600)
582 $c = Memcached_DataObject::memcache();
588 $key_part = Cache::keyize($cls).':'.md5($qry);
589 $ckey = Cache::key($key_part);
590 $stored = $c->get($ckey);
592 if ($stored !== false) {
593 return new ArrayWrapper($stored);
599 while ($inst->fetch()) {
600 $cached[] = clone($inst);
603 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
604 return new ArrayWrapper($cached);
608 * sends query to database - this is the private one that must work
609 * - internal functions use this rather than $this->query()
611 * Overridden to do logging.
613 * @param string $string
615 * @return mixed none or PEAR_Error
617 function _query($string)
619 if (common_config('db', 'annotate_queries')) {
620 $string = $this->annotateQuery($string);
623 $start = microtime(true);
626 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
627 common_perf_counter('query', $string);
629 $result = parent::_query($string);
630 } catch (Exception $e) {
633 Event::handle('EndDBQuery', array($this, $string, &$result));
635 $delta = microtime(true) - $start;
637 $limit = common_config('db', 'log_slow_queries');
638 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
639 $clean = $this->sanitizeQuery($string);
641 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
643 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
645 common_log(LOG_DEBUG, $msg);
655 * Find the first caller in the stack trace that's not a
656 * low-level database function and add a comment to the
657 * query string. This should then be visible in process lists
658 * and slow query logs, to help identify problem areas.
660 * Also marks whether this was a web GET/POST or which daemon
663 * @param string $string SQL query string
664 * @return string SQL query string, with a comment in it
666 function annotateQuery($string)
668 $ignore = array('annotateQuery',
676 $ignoreStatic = array('getKV',
681 $here = get_class($this); // if we get confused
682 $bt = debug_backtrace();
684 // Find the first caller that's not us?
685 foreach ($bt as $frame) {
686 $func = $frame['function'];
687 if (isset($frame['type']) && $frame['type'] == '::') {
688 if (in_array($func, $ignoreStatic)) {
691 $here = $frame['class'] . '::' . $func;
693 } else if (isset($frame['type']) && $frame['type'] == '->') {
694 if ($frame['object'] === $this && in_array($func, $ignore)) {
697 if (in_array($func, $ignoreStatic)) {
698 continue; // @todo FIXME: This shouldn't be needed?
700 $here = get_class($frame['object']) . '->' . $func;
707 if (php_sapi_name() == 'cli') {
708 $context = basename($_SERVER['PHP_SELF']);
710 $context = $_SERVER['REQUEST_METHOD'];
713 // Slip the comment in after the first command,
714 // or DB_DataObject gets confused about handling inserts and such.
715 $parts = explode(' ', $string, 2);
716 $parts[0] .= " /* $context $here */";
717 return implode(' ', $parts);
720 // Sanitize a query for logging
721 // @fixme don't trim spaces in string literals
722 function sanitizeQuery($string)
724 $string = preg_replace('/\s+/', ' ', $string);
725 $string = trim($string);
729 // We overload so that 'SET NAMES "utf8"' is called for
734 global $_DB_DATAOBJECT, $_PEAR;
736 $sum = $this->_getDbDsnMD5();
738 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
739 !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
745 // @fixme horrible evil hack!
747 // In multisite configuration we don't want to keep around a separate
748 // connection for every database; we could end up with thousands of
749 // connections open per thread. In an ideal world we might keep
750 // a connection per server and select different databases, but that'd
751 // be reliant on having the same db username/pass as well.
753 // MySQL connections are cheap enough we're going to try just
754 // closing out the old connection and reopening when we encounter
757 // WARNING WARNING if we end up actually using multiple DBs at a time
758 // we'll need some fancier logic here.
759 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
760 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
761 if ($_PEAR->isError($conn)) {
762 common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
763 } elseif (!empty($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 || $DB instanceof MDB2_Driver_mysqli) {
779 mysqli_set_charset($conn, 'utf8');
780 } else if ($DB instanceof DB_mysql || $DB instanceof MDB2_Driver_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'");