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 DB_DataObject
25 * Destructor to free global memory resources associated with
26 * this data object when it's unset or goes out of scope.
27 * DB_DataObject doesn't do this yet by itself.
33 if (method_exists('DB_DataObject', '__destruct')) {
39 * Magic function called at serialize() time.
41 * We use this to drop a couple process-specific references
42 * from DB_DataObject which can cause trouble in future
45 * @return array of variable names to include in serialization.
49 $vars = array_keys(get_object_vars($this));
50 $skip = array('_DB_resultid', '_link_loaded');
51 return array_diff($vars, $skip);
55 * Magic function called at unserialize() time.
57 * Clean out some process-specific variables which might
58 * be floating around from a previous process's cached
61 * Old cached objects may still have them.
65 // Refers to global state info from a previous process.
66 // Clear this out so we don't accidentally break global
67 // state in *this* process.
68 $this->_DB_resultid = null;
69 // We don't have any local DBO refs, so clear these out.
70 $this->_link_loaded = false;
74 * Wrapper for DB_DataObject's static lookup using memcached
75 * as backing instead of an in-process cache array.
77 * @param string $cls classname of object type to load
78 * @param mixed $k key field name, or value for primary key
79 * @param mixed $v key field value, or leave out for primary key lookup
80 * @return mixed Memcached_DataObject subtype or false
82 function &staticGet($cls, $k, $v=null)
92 $i = Memcached_DataObject::getcached($cls, $k, $v);
93 if ($i === false) { // false == cache miss
94 $i = DB_DataObject::factory($cls);
99 $result = $i->get($k, $v);
104 // save the fact that no such row exists
105 $c = self::memcache();
107 $ck = self::cachekey($cls, $k, $v);
117 * @fixme Should this return false on lookup fail to match staticGet?
119 function pkeyGet($cls, $kv)
121 $i = Memcached_DataObject::multicache($cls, $kv);
122 if ($i !== false) { // false == cache miss
125 $i = DB_DataObject::factory($cls);
129 foreach ($kv as $k => $v) {
132 if ($i->find(true)) {
136 $c = self::memcache();
138 $ck = self::multicacheKey($cls, $kv);
148 $result = parent::insert();
150 $this->encache(); // in case of cached negative lookups
155 function update($orig=null)
157 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
158 $orig->decache(); # might be different keys
160 $result = parent::update($orig);
169 $this->decache(); # while we still have the values!
170 return parent::delete();
173 static function memcache() {
174 return common_memcache();
177 static function cacheKey($cls, $k, $v) {
178 if (is_object($cls) || is_object($k) || is_object($v)) {
179 $e = new Exception();
180 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
181 str_replace("\n", " ", $e->getTraceAsString()));
183 return common_cache_key(strtolower($cls).':'.$k.':'.$v);
186 static function getcached($cls, $k, $v) {
187 $c = Memcached_DataObject::memcache();
191 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
192 if (0 == strcasecmp($cls, 'User')) {
193 // Special case for User
194 if (is_object($obj) && is_object($obj->id)) {
195 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
196 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
206 // ini-based classes return number-indexed arrays. handbuilt
207 // classes return column => keytype. Make this uniform.
209 $keys = $this->keys();
211 $keyskeys = array_keys($keys);
213 if (is_string($keyskeys[0])) {
217 global $_DB_DATAOBJECT;
218 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
219 $this->databaseStructure();
222 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
227 $c = $this->memcache();
231 } else if ($this->tableName() == 'user' && is_object($this->id)) {
232 // Special case for User bug
233 $e = new Exception();
234 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
235 str_replace("\n", " ", $e->getTraceAsString()));
238 $keys = $this->_allCacheKeys();
240 foreach ($keys as $key) {
241 $c->set($key, $this);
248 $c = $this->memcache();
254 $keys = $this->_allCacheKeys();
256 foreach ($keys as $key) {
257 $c->delete($key, $this);
261 function _allCacheKeys()
265 $types = $this->keyTypes();
271 foreach ($types as $key => $type) {
273 assert(!empty($key));
276 if (empty($this->$key)) {
279 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
280 } else if ($type == 'K' || $type == 'N') {
282 $pval[] = $this->$key;
284 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
288 assert(count($pkey) > 0);
290 // XXX: should work for both compound and scalar pkeys
291 $pvals = implode(',', $pval);
292 $pkeys = implode(',', $pkey);
294 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
299 function multicache($cls, $kv)
302 $c = self::memcache();
306 return $c->get(self::multicacheKey($cls, $kv));
310 static function multicacheKey($cls, $kv)
313 $pkeys = implode(',', array_keys($kv));
314 $pvals = implode(',', array_values($kv));
315 return self::cacheKey($cls, $pkeys, $pvals);
318 function getSearchEngine($table)
320 require_once INSTALLDIR.'/lib/search_engines.php';
321 static $search_engine;
322 if (!isset($search_engine)) {
323 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
324 if ('mysql' === common_config('db', 'type')) {
325 $type = common_config('search', 'type');
326 if ($type == 'like') {
327 $search_engine = new MySQLLikeSearch($this, $table);
328 } else if ($type == 'fulltext') {
329 $search_engine = new MySQLSearch($this, $table);
331 throw new ServerException('Unknown search type: ' . $type);
334 $search_engine = new PGSearch($this, $table);
338 return $search_engine;
341 static function cachedQuery($cls, $qry, $expiry=3600)
343 $c = Memcached_DataObject::memcache();
349 $key_part = common_keyize($cls).':'.md5($qry);
350 $ckey = common_cache_key($key_part);
351 $stored = $c->get($ckey);
353 if ($stored !== false) {
354 return new ArrayWrapper($stored);
360 while ($inst->fetch()) {
361 $cached[] = clone($inst);
364 $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
365 return new ArrayWrapper($cached);
369 * sends query to database - this is the private one that must work
370 * - internal functions use this rather than $this->query()
372 * Overridden to do logging.
374 * @param string $string
376 * @return mixed none or PEAR_Error
378 function _query($string)
380 $start = microtime(true);
381 $result = parent::_query($string);
382 $delta = microtime(true) - $start;
384 $limit = common_config('db', 'log_slow_queries');
385 if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
386 $clean = $this->sanitizeQuery($string);
387 common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
392 // Sanitize a query for logging
393 // @fixme don't trim spaces in string literals
394 function sanitizeQuery($string)
396 $string = preg_replace('/\s+/', ' ', $string);
397 $string = trim($string);
401 // We overload so that 'SET NAMES "utf8"' is called for
406 global $_DB_DATAOBJECT;
408 $sum = $this->_getDbDsnMD5();
410 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
411 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
417 // @fixme horrible evil hack!
419 // In multisite configuration we don't want to keep around a separate
420 // connection for every database; we could end up with thousands of
421 // connections open per thread. In an ideal world we might keep
422 // a connection per server and select different databases, but that'd
423 // be reliant on having the same db username/pass as well.
425 // MySQL connections are cheap enough we're going to try just
426 // closing out the old connection and reopening when we encounter
429 // WARNING WARNING if we end up actually using multiple DBs at a time
430 // we'll need some fancier logic here.
431 if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS'])) {
432 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
436 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
440 $result = parent::_connect();
442 if ($result && !$exists) {
443 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
444 if (common_config('db', 'type') == 'mysql' &&
445 common_config('db', 'utf8')) {
446 $conn = $DB->connection;
448 if ($DB instanceof DB_mysqli) {
449 mysqli_set_charset($conn, 'utf8');
450 } else if ($DB instanceof DB_mysql) {
451 mysql_set_charset('utf8', $conn);
460 // XXX: largely cadged from DB_DataObject
462 function _getDbDsnMD5()
464 if ($this->_database_dsn_md5) {
465 return $this->_database_dsn_md5;
468 $dsn = $this->_getDbDsn();
470 if (is_string($dsn)) {
473 /// support array based dsn's
474 $sum = md5(serialize($dsn));
482 global $_DB_DATAOBJECT;
484 if (empty($_DB_DATAOBJECT['CONFIG'])) {
485 DB_DataObject::_loadConfig();
488 $options = &$_DB_DATAOBJECT['CONFIG'];
490 // if the databse dsn dis defined in the object..
492 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
496 if (!$this->_database) {
497 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
500 if ($this->_database && !empty($options["database_{$this->_database}"])) {
501 $dsn = $options["database_{$this->_database}"];
502 } else if (!empty($options['database'])) {
503 $dsn = $options['database'];
508 throw new Exception("No database name / dsn found anywhere");
514 static function blow()
516 $c = self::memcache();
522 $args = func_get_args();
524 $format = array_shift($args);
526 $keyPart = vsprintf($format, $args);
528 $cacheKey = common_cache_key($keyPart);
530 return $c->delete($cacheKey);