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 * Wrapper for DB_DataObject's static lookup using memcached
42 * as backing instead of an in-process cache array.
44 * @param string $cls classname of object type to load
45 * @param mixed $k key field name, or value for primary key
46 * @param mixed $v key field value, or leave out for primary key lookup
47 * @return mixed Memcached_DataObject subtype or false
49 function &staticGet($cls, $k, $v=null)
59 $i = Memcached_DataObject::getcached($cls, $k, $v);
63 $i = DB_DataObject::factory($cls);
67 $result = $i->get($k, $v);
77 function &pkeyGet($cls, $kv)
79 $i = Memcached_DataObject::multicache($cls, $kv);
84 foreach ($kv as $k => $v) {
98 $result = parent::insert();
102 function update($orig=null)
104 if (is_object($orig) && $orig instanceof Memcached_DataObject) {
105 $orig->decache(); # might be different keys
107 $result = parent::update($orig);
116 $this->decache(); # while we still have the values!
117 return parent::delete();
120 static function memcache() {
121 return common_memcache();
124 static function cacheKey($cls, $k, $v) {
125 if (is_object($cls) || is_object($k) || is_object($v)) {
126 $e = new Exception();
127 common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
128 str_replace("\n", " ", $e->getTraceAsString()));
130 return common_cache_key(strtolower($cls).':'.$k.':'.$v);
133 static function getcached($cls, $k, $v) {
134 $c = Memcached_DataObject::memcache();
138 return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
144 global $_DB_DATAOBJECT;
145 if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
146 $this->databaseStructure();
149 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
154 $c = $this->memcache();
160 $keys = $this->_allCacheKeys();
162 foreach ($keys as $key) {
163 $c->set($key, $this);
169 $c = $this->memcache();
175 $keys = $this->_allCacheKeys();
177 foreach ($keys as $key) {
178 $c->delete($key, $this);
182 function _allCacheKeys()
186 $types = $this->keyTypes();
192 foreach ($types as $key => $type) {
194 assert(!empty($key));
197 if (empty($this->$key)) {
200 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
201 } else if ($type == 'K' || $type == 'N') {
203 $pval[] = $this->$key;
205 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
209 assert(count($pkey) > 0);
211 // XXX: should work for both compound and scalar pkeys
212 $pvals = implode(',', $pval);
213 $pkeys = implode(',', $pkey);
215 $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
220 function multicache($cls, $kv)
223 $c = Memcached_DataObject::memcache();
227 $pkeys = implode(',', array_keys($kv));
228 $pvals = implode(',', array_values($kv));
229 return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
233 function getSearchEngine($table)
235 require_once INSTALLDIR.'/lib/search_engines.php';
236 static $search_engine;
237 if (!isset($search_engine)) {
238 if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
239 if ('mysql' === common_config('db', 'type')) {
240 $type = common_config('search', 'type');
241 if ($type == 'like') {
242 $search_engine = new MySQLLikeSearch($this, $table);
243 } else if ($type == 'fulltext') {
244 $search_engine = new MySQLSearch($this, $table);
246 throw new ServerException('Unknown search type: ' . $type);
249 $search_engine = new PGSearch($this, $table);
253 return $search_engine;
256 static function cachedQuery($cls, $qry, $expiry=3600)
258 $c = Memcached_DataObject::memcache();
264 $key_part = common_keyize($cls).':'.md5($qry);
265 $ckey = common_cache_key($key_part);
266 $stored = $c->get($ckey);
268 return new ArrayWrapper($stored);
274 while ($inst->fetch()) {
275 $cached[] = clone($inst);
278 $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
279 return new ArrayWrapper($cached);
282 // We overload so that 'SET NAMES "utf8"' is called for
287 global $_DB_DATAOBJECT;
289 $sum = $this->_getDbDsnMD5();
291 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
292 !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
298 $result = parent::_connect();
300 if ($result && !$exists) {
301 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
302 if (common_config('db', 'type') == 'mysql' &&
303 common_config('db', 'utf8')) {
304 $conn = $DB->connection;
306 if ($DB instanceof DB_mysqli) {
307 mysqli_set_charset($conn, 'utf8');
308 } else if ($DB instanceof DB_mysql) {
309 mysql_set_charset('utf8', $conn);
318 // XXX: largely cadged from DB_DataObject
320 function _getDbDsnMD5()
322 if ($this->_database_dsn_md5) {
323 return $this->_database_dsn_md5;
326 $dsn = $this->_getDbDsn();
328 if (is_string($dsn)) {
331 /// support array based dsn's
332 $sum = md5(serialize($dsn));
340 global $_DB_DATAOBJECT;
342 if (empty($_DB_DATAOBJECT['CONFIG'])) {
343 DB_DataObject::_loadConfig();
346 $options = &$_DB_DATAOBJECT['CONFIG'];
348 // if the databse dsn dis defined in the object..
350 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
354 if (!$this->_database) {
355 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
358 if ($this->_database && !empty($options["database_{$this->_database}"])) {
359 $dsn = $options["database_{$this->_database}"];
360 } else if (!empty($options['database'])) {
361 $dsn = $options['database'];
366 throw new Exception("No database name / dsn found anywhere");