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 = static::pkeyCols();
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 skip provided null values
72 * @return array Array of objects, in order
74 static function multiGetClass($cls, $keyCol, array $keyVals, $skipNulls=true)
78 // PHP compatible datatype for settype() below
79 $colType = $obj->columnType($keyCol);
81 if (!in_array($colType, array('integer', 'int'))) {
82 // This is because I'm afraid to escape strings incorrectly
83 // in the way we use them below in FIND_IN_SET for MariaDB
84 throw new ServerException('Cannot do multiGet on anything but integer columns');
88 foreach ($keyVals as $key=>$val) {
90 unset($keyVals[$key]);
95 $obj->whereAddIn($keyCol, $keyVals, $colType);
97 // Since we're inputting straight to a query: format and escape
98 foreach ($keyVals as $key=>$val) {
99 settype($val, $colType);
100 $keyVals[$key] = $obj->escape($val);
103 // FIND_IN_SET will make sure we keep the desired order
104 $obj->orderBy(sprintf("FIND_IN_SET(%s, '%s')", $keyCol, implode(',', $keyVals)));
111 * Get multiple items from the database by key
113 * @param string $cls Class to fetch
114 * @param string $keyCol name of column for key
115 * @param array $keyVals key values to fetch
116 * @param boolean $otherCols Other columns to hold fixed
118 * @return array Array mapping $keyVals to objects, or null if not found
120 static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
122 if (is_array($keyCol)) {
123 foreach ($keyVals as $keyVal) {
124 $result[implode(',', $keyVal)] = null;
127 $result = array_fill_keys($keyVals, null);
132 foreach ($keyVals as $keyVal) {
134 if (is_array($keyCol)) {
135 $kv = array_combine($keyCol, $keyVal);
137 $kv = array($keyCol => $keyVal);
140 $kv = array_merge($otherCols, $kv);
142 $i = self::multicache($cls, $kv);
145 if (is_array($keyCol)) {
146 $result[implode(',', $keyVal)] = $i;
148 $result[$keyVal] = $i;
150 } else if (!empty($keyVal)) {
151 $toFetch[] = $keyVal;
155 if (count($toFetch) > 0) {
157 foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
158 $i->$otherKeyCol = $otherKeyVal;
160 if (is_array($keyCol)) {
161 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
163 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
166 while ($i->fetch()) {
169 if (is_array($keyCol)) {
171 foreach ($keyCol as $k) {
174 $result[implode(',', $vals)] = $copy;
176 $result[$i->$keyCol] = $copy;
181 // Save state of DB misses
183 foreach ($toFetch as $keyVal) {
185 if (is_array($keyCol)) {
186 $r = $result[implode(',', $keyVal)];
188 $r = $result[$keyVal];
191 if (is_array($keyCol)) {
192 $kv = array_combine($keyCol, $keyVal);
194 $kv = array($keyCol => $keyVal);
196 $kv = array_merge($otherCols, $kv);
197 // save the fact that no such row exists
198 $c = self::memcache();
200 $ck = self::multicacheKey($cls, $kv);
210 static function _inMultiKey($i, $cols, $values)
214 foreach ($cols as $col) {
215 $types[$col] = $i->columnType($col);
222 foreach ($values as $value) {
232 foreach ($cols as $col) {
238 switch ($types[$col]) {
241 $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
244 $query .= sprintf("%s = %s", $col, $value[$i]);
258 static function pkeyColsClass($cls)
261 $types = $i->keyTypes();
266 foreach ($types as $key => $type) {
267 if ($type == 'K' || $type == 'N') {
275 static function listFindClass($cls, $keyCol, array $keyVals)
278 $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
280 throw new NoResultException($i);
286 static function listGetClass($cls, $keyCol, array $keyVals)
288 $pkeyMap = array_fill_keys($keyVals, array());
289 $result = array_fill_keys($keyVals, array());
291 $pkeyCols = static::pkeyCols();
296 // We only cache keys -- not objects!
298 foreach ($keyVals as $keyVal) {
299 $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
301 $pkeyMap[$keyVal] = $l;
302 foreach ($l as $pkey) {
306 $toFetch[] = $keyVal;
310 if (count($allPkeys) > 0) {
311 $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
313 foreach ($pkeyMap as $keyVal => $pkeyList) {
314 foreach ($pkeyList as $pkeyVal) {
315 $i = $keyResults[implode(',',$pkeyVal)];
317 $result[$keyVal][] = $i;
323 if (count($toFetch) > 0) {
325 $i = self::listFindClass($cls, $keyCol, $toFetch);
327 while ($i->fetch()) {
330 $result[$i->$keyCol][] = $copy;
332 foreach ($pkeyCols as $pkeyCol) {
333 $pkeyVal[] = $i->$pkeyCol;
335 $pkeyMap[$i->$keyCol][] = $pkeyVal;
337 } catch (NoResultException $e) {
338 // no results found for our keyVals, so we leave them as empty arrays
340 foreach ($toFetch as $keyVal) {
341 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
349 function columnType($columnName)
351 $keys = $this->table();
352 if (!array_key_exists($columnName, $keys)) {
353 throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
356 $def = $keys[$columnName];
358 if ($def & DB_DATAOBJECT_INT) {
366 * @todo FIXME: Should this return false on lookup fail to match getKV?
368 static function pkeyGetClass($cls, array $kv)
370 $i = self::multicache($cls, $kv);
371 if ($i !== false) { // false == cache miss
375 foreach ($kv as $k => $v) {
377 // XXX: possible SQL injection...? Don't
378 // pass keys from the browser, eh.
379 $i->whereAdd("$k is null");
384 if ($i->find(true)) {
388 $c = self::memcache();
390 $ck = self::multicacheKey($cls, $kv);
400 $result = parent::insert();
402 $this->fixupTimestamps();
403 $this->encache(); // in case of cached negative lookups
408 function update($dataObject=false)
410 if (is_object($dataObject) && $dataObject instanceof Memcached_DataObject) {
411 $dataObject->decache(); # might be different keys
413 $result = parent::update($dataObject);
414 if ($result !== false) {
415 $this->fixupTimestamps();
421 function delete($useWhere=false)
423 $this->decache(); # while we still have the values!
424 return parent::delete($useWhere);
427 static function memcache() {
428 return Cache::instance();
431 static function cacheKey($cls, $k, $v) {
432 if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
433 $e = new Exception();
434 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
435 str_replace("\n", " ", $e->getTraceAsString()));
437 $vstr = self::valueString($v);
438 return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
441 static function getcached($cls, $k, $v) {
442 $c = self::memcache();
446 $obj = $c->get(self::cacheKey($cls, $k, $v));
447 if (0 == strcasecmp($cls, 'User')) {
448 // Special case for User
449 if (is_object($obj) && is_object($obj->id)) {
450 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
451 $c->delete(self::cacheKey($cls, $k, $v));
461 // ini-based classes return number-indexed arrays. handbuilt
462 // classes return column => keytype. Make this uniform.
464 $keys = $this->keys();
466 $keyskeys = array_keys($keys);
468 if (is_string($keyskeys[0])) {
472 global $_DB_DATAOBJECT;
473 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
474 $this->databaseStructure();
477 return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"];
482 $c = self::memcache();
486 } else if ($this->tableName() == 'user' && is_object($this->id)) {
487 // Special case for User bug
488 $e = new Exception();
489 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
490 str_replace("\n", " ", $e->getTraceAsString()));
493 $keys = $this->_allCacheKeys();
495 foreach ($keys as $key) {
496 $c->set($key, $this);
503 $c = self::memcache();
509 $keys = $this->_allCacheKeys();
511 foreach ($keys as $key) {
512 $c->delete($key, $this);
516 function _allCacheKeys()
520 $types = $this->keyTypes();
526 foreach ($types as $key => $type) {
528 assert(!empty($key));
531 if (empty($this->$key)) {
534 $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
535 } else if ($type == 'K' || $type == 'N') {
537 $pval[] = self::valueString($this->$key);
539 // Low level exception. No need for i18n as discussed with Brion.
540 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
544 assert(count($pkey) > 0);
546 // XXX: should work for both compound and scalar pkeys
547 $pvals = implode(',', $pval);
548 $pkeys = implode(',', $pkey);
550 $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
555 static function multicache($cls, $kv)
558 $c = self::memcache();
562 return $c->get(self::multicacheKey($cls, $kv));
566 static function multicacheKey($cls, $kv)
569 $pkeys = implode(',', array_keys($kv));
570 $pvals = implode(',', array_values($kv));
571 return self::cacheKey($cls, $pkeys, $pvals);
574 function getSearchEngine($table)
576 require_once INSTALLDIR.'/lib/search_engines.php';
578 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
579 if ('mysql' === common_config('db', 'type')) {
580 $type = common_config('search', 'type');
581 if ($type == 'like') {
582 $search_engine = new MySQLLikeSearch($this, $table);
583 } else if ($type == 'fulltext') {
584 $search_engine = new MySQLSearch($this, $table);
586 // Low level exception. No need for i18n as discussed with Brion.
587 throw new ServerException('Unknown search type: ' . $type);
590 $search_engine = new PGSearch($this, $table);
594 return $search_engine;
597 static function cachedQuery($cls, $qry, $expiry=3600)
599 $c = self::memcache();
605 $key_part = Cache::keyize($cls).':'.md5($qry);
606 $ckey = Cache::key($key_part);
607 $stored = $c->get($ckey);
609 if ($stored !== false) {
610 return new ArrayWrapper($stored);
616 while ($inst->fetch()) {
617 $cached[] = clone($inst);
620 $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
621 return new ArrayWrapper($cached);
625 * sends query to database - this is the private one that must work
626 * - internal functions use this rather than $this->query()
628 * Overridden to do logging.
630 * @param string $string
632 * @return mixed none or PEAR_Error
634 function _query($string)
636 if (common_config('db', 'annotate_queries')) {
637 $string = $this->annotateQuery($string);
640 $start = microtime(true);
643 if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
644 common_perf_counter('query', $string);
646 $result = parent::_query($string);
647 } catch (Exception $e) {
650 Event::handle('EndDBQuery', array($this, $string, &$result));
652 $delta = microtime(true) - $start;
654 $limit = common_config('db', 'log_slow_queries');
655 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
656 $clean = $this->sanitizeQuery($string);
658 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
660 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
662 common_log(LOG_DEBUG, $msg);
672 * Find the first caller in the stack trace that's not a
673 * low-level database function and add a comment to the
674 * query string. This should then be visible in process lists
675 * and slow query logs, to help identify problem areas.
677 * Also marks whether this was a web GET/POST or which daemon
680 * @param string $string SQL query string
681 * @return string SQL query string, with a comment in it
683 function annotateQuery($string)
685 $ignore = array('annotateQuery',
693 $ignoreStatic = array('getKV',
698 $here = get_class($this); // if we get confused
699 $bt = debug_backtrace();
701 // Find the first caller that's not us?
702 foreach ($bt as $frame) {
703 $func = $frame['function'];
704 if (isset($frame['type']) && $frame['type'] == '::') {
705 if (in_array($func, $ignoreStatic)) {
708 $here = $frame['class'] . '::' . $func;
710 } else if (isset($frame['type']) && $frame['type'] == '->') {
711 if ($frame['object'] === $this && in_array($func, $ignore)) {
714 if (in_array($func, $ignoreStatic)) {
715 continue; // @todo FIXME: This shouldn't be needed?
717 $here = get_class($frame['object']) . '->' . $func;
724 if (php_sapi_name() == 'cli') {
725 $context = basename($_SERVER['PHP_SELF']);
727 $context = $_SERVER['REQUEST_METHOD'];
730 // Slip the comment in after the first command,
731 // or DB_DataObject gets confused about handling inserts and such.
732 $parts = explode(' ', $string, 2);
733 $parts[0] .= " /* $context $here */";
734 return implode(' ', $parts);
737 // Sanitize a query for logging
738 // @fixme don't trim spaces in string literals
739 function sanitizeQuery($string)
741 $string = preg_replace('/\s+/', ' ', $string);
742 $string = trim($string);
746 // We overload so that 'SET NAMES "utf8mb4"' is called for
751 global $_DB_DATAOBJECT, $_PEAR;
753 $sum = $this->_getDbDsnMD5();
755 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
756 !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
762 // @fixme horrible evil hack!
764 // In multisite configuration we don't want to keep around a separate
765 // connection for every database; we could end up with thousands of
766 // connections open per thread. In an ideal world we might keep
767 // a connection per server and select different databases, but that'd
768 // be reliant on having the same db username/pass as well.
770 // MySQL connections are cheap enough we're going to try just
771 // closing out the old connection and reopening when we encounter
774 // WARNING WARNING if we end up actually using multiple DBs at a time
775 // we'll need some fancier logic here.
776 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
777 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
778 if ($_PEAR->isError($conn)) {
779 common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
780 } elseif (!empty($conn)) {
783 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
787 $result = parent::_connect();
789 if ($result && !$exists) {
790 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
791 if (common_config('db', 'type') == 'mysql' &&
792 common_config('db', 'utf8')) {
793 $conn = $DB->connection;
795 if ($DB instanceof DB_mysqli || $DB instanceof MDB2_Driver_mysqli) {
796 mysqli_set_charset($conn, 'utf8mb4');
797 } else if ($DB instanceof DB_mysql || $DB instanceof MDB2_Driver_mysql) {
798 mysql_set_charset('utf8mb4', $conn);
802 // Needed to make timestamp values usefully comparable.
803 if (common_config('db', 'type') == 'mysql') {
804 parent::_query("set time_zone='+0:00'");
811 // XXX: largely cadged from DB_DataObject
813 function _getDbDsnMD5()
815 if ($this->_database_dsn_md5) {
816 return $this->_database_dsn_md5;
819 $dsn = $this->_getDbDsn();
821 if (is_string($dsn)) {
824 /// support array based dsn's
825 $sum = md5(serialize($dsn));
833 global $_DB_DATAOBJECT;
835 if (empty($_DB_DATAOBJECT['CONFIG'])) {
839 $options = &$_DB_DATAOBJECT['CONFIG'];
841 // if the databse dsn dis defined in the object..
843 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
847 if (!$this->_database) {
848 $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
851 if ($this->_database && !empty($options["database_{$this->_database}"])) {
852 $dsn = $options["database_{$this->_database}"];
853 } else if (!empty($options['database'])) {
854 $dsn = $options['database'];
859 // TRANS: Exception thrown when database name or Data Source Name could not be found.
860 throw new Exception(_('No database name or DSN found anywhere.'));
866 static function blow()
868 $c = self::memcache();
874 $args = func_get_args();
876 $format = array_shift($args);
878 $keyPart = vsprintf($format, $args);
880 $cacheKey = Cache::key($keyPart);
882 return $c->delete($cacheKey);
885 function fixupTimestamps()
887 // Fake up timestamp columns
888 $columns = $this->table();
889 foreach ($columns as $name => $type) {
890 if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
891 $this->$name = common_sql_now();
898 common_debug("debugDump: " . common_log_objstring($this));
901 function raiseError($message, $type = null, $behaviour = null)
903 $id = get_class($this);
904 if (!empty($this->id)) {
905 $id .= ':' . $this->id;
907 if ($message instanceof PEAR_Error) {
908 $message = $message->getMessage();
910 // Low level exception. No need for i18n as discussed with Brion.
911 throw new ServerException("[$id] DB_DataObject error [$type]: $message");
914 static function cacheGet($keyPart)
916 $c = self::memcache();
922 $cacheKey = Cache::key($keyPart);
924 return $c->get($cacheKey);
927 static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
929 $c = self::memcache();
935 $cacheKey = Cache::key($keyPart);
937 return $c->set($cacheKey, $value, $flag, $expiry);
940 static function valueString($v)
943 if (is_object($v) && $v instanceof DB_DataObject_Cast) {
946 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
953 // Low level exception. No need for i18n as discussed with Brion.
954 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
957 // Low level exception. No need for i18n as discussed with Brion.
958 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");