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 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
24 class Memcached_DataObject extends DB_DataObject
27 * Destructor to free global memory resources associated with
28 * this data object when it's unset or goes out of scope.
29 * DB_DataObject doesn't do this yet by itself.
35 if (method_exists('DB_DataObject', '__destruct')) {
41 * Magic function called at serialize() time.
43 * We use this to drop a couple process-specific references
44 * from DB_DataObject which can cause trouble in future
47 * @return array of variable names to include in serialization.
51 $vars = array_keys(get_object_vars($this));
52 $skip = array('_DB_resultid', '_link_loaded');
53 return array_diff($vars, $skip);
57 * Magic function called at unserialize() time.
59 * Clean out some process-specific variables which might
60 * be floating around from a previous process's cached
63 * Old cached objects may still have them.
67 // Refers to global state info from a previous process.
68 // Clear this out so we don't accidentally break global
69 // state in *this* process.
70 $this->_DB_resultid = null;
72 // We don't have any local DBO refs, so clear these out.
73 $this->_link_loaded = false;
77 * Wrapper for DB_DataObject's static lookup using memcached
78 * as backing instead of an in-process cache array.
80 * @param string $cls classname of object type to load
81 * @param mixed $k key field name, or value for primary key
82 * @param mixed $v key field value, or leave out for primary key lookup
83 * @return mixed Memcached_DataObject subtype or false
85 function &staticGet($cls, $k, $v=null)
95 $i = Memcached_DataObject::getcached($cls, $k, $v);
99 $i = DB_DataObject::factory($cls);
103 $result = $i->get($k, $v);
113 function &pkeyGet($cls, $kv)
115 $i = Memcached_DataObject::multicache($cls, $kv);
120 foreach ($kv as $k => $v) {
123 if ($i->find(true)) {
134 $result = parent::insert();
138 function update($orig=null)
140 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
141 $orig->decache(); # might be different keys
143 $result = parent::update($orig);
152 $this->decache(); # while we still have the values!
153 return parent::delete();
156 static function memcache() {
157 return common_memcache();
160 static function cacheKey($cls, $k, $v) {
161 if (is_object($cls) || is_object($k) || is_object($v)) {
162 $e = new Exception();
163 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
164 str_replace("\n", " ", $e->getTraceAsString()));
166 return common_cache_key(strtolower($cls).':'.$k.':'.$v);
169 static function getcached($cls, $k, $v) {
170 $c = Memcached_DataObject::memcache();
174 $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
175 if (0 == strcasecmp($cls, 'User')) {
176 // Special case for User
177 if (is_object($obj->id)) {
178 common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
179 $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
189 global $_DB_DATAOBJECT;
190 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
191 $this->databaseStructure();
194 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
199 $c = $this->memcache();
202 } else if ($this->tableName() == 'user' && is_object($this->id)) {
203 // Special case for User bug
204 $e = new Exception();
205 common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
206 str_replace("\n", " ", $e->getTraceAsString()));
211 $types = $this->keyTypes();
213 foreach ($types as $key => $type) {
216 $pval[] = $this->$key;
218 $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
221 # XXX: should work for both compound and scalar pkeys
222 $pvals = implode(',', $pval);
223 $pkeys = implode(',', $pkey);
224 $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
230 $c = $this->memcache();
236 $types = $this->keyTypes();
238 foreach ($types as $key => $type) {
241 $pval[] = $this->$key;
243 $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
246 # should work for both compound and scalar pkeys
247 # XXX: comma works for now but may not be safe separator for future keys
248 $pvals = implode(',', $pval);
249 $pkeys = implode(',', $pkey);
250 $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
254 function multicache($cls, $kv)
257 $c = Memcached_DataObject::memcache();
261 $pkeys = implode(',', array_keys($kv));
262 $pvals = implode(',', array_values($kv));
263 return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
267 function getSearchEngine($table)
269 require_once INSTALLDIR.'/lib/search_engines.php';
270 static $search_engine;
271 if (!isset($search_engine)) {
272 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
273 if ('mysql' === common_config('db', 'type')) {
274 $type = common_config('search', 'type');
275 if ($type == 'like') {
276 $search_engine = new MySQLLikeSearch($this, $table);
277 } else if ($type == 'fulltext') {
278 $search_engine = new MySQLSearch($this, $table);
280 throw new ServerException('Unknown search type: ' . $type);
283 $search_engine = new PGSearch($this, $table);
287 return $search_engine;
290 static function cachedQuery($cls, $qry, $expiry=3600)
292 $c = Memcached_DataObject::memcache();
298 $key_part = common_keyize($cls).':'.md5($qry);
299 $ckey = common_cache_key($key_part);
300 $stored = $c->get($ckey);
302 return new ArrayWrapper($stored);
308 while ($inst->fetch()) {
309 $cached[] = clone($inst);
312 $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
313 return new ArrayWrapper($cached);
316 // We overload so that 'SET NAMES "utf8"' is called for
321 global $_DB_DATAOBJECT;
323 $sum = $this->_getDbDsnMD5();
325 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
326 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
332 $result = parent::_connect();
334 if ($result && !$exists) {
335 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
336 if (common_config('db', 'type') == 'mysql' &&
337 common_config('db', 'utf8')) {
338 $conn = $DB->connection;
340 if ($DB instanceof DB_mysqli) {
341 mysqli_set_charset($conn, 'utf8');
342 } else if ($DB instanceof DB_mysql) {
343 mysql_set_charset('utf8', $conn);
352 // XXX: largely cadged from DB_DataObject
354 function _getDbDsnMD5()
356 if ($this->_database_dsn_md5) {
357 return $this->_database_dsn_md5;
360 $dsn = $this->_getDbDsn();
362 if (is_string($dsn)) {
365 /// support array based dsn's
366 $sum = md5(serialize($dsn));
374 global $_DB_DATAOBJECT;
376 if (empty($_DB_DATAOBJECT['CONFIG'])) {
377 DB_DataObject::_loadConfig();
380 $options = &$_DB_DATAOBJECT['CONFIG'];
382 // if the databse dsn dis defined in the object..
384 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
388 if (!$this->_database) {
389 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
392 if ($this->_database && !empty($options["database_{$this->_database}"])) {
393 $dsn = $options["database_{$this->_database}"];
394 } else if (!empty($options['database'])) {
395 $dsn = $options['database'];
400 throw new Exception("No database name / dsn found anywhere");