]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
return false from Memcached_DataObject::staticGet() on not found, like DB_DataObject
[quix0rs-gnu-social.git] / classes / Memcached_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23
24 class Memcached_DataObject extends DB_DataObject
25 {
26     function &staticGet($cls, $k, $v=null)
27     {
28         if (is_null($v)) {
29             $v = $k;
30             # XXX: HACK!
31             $i = new $cls;
32             $keys = $i->keys();
33             $k = $keys[0];
34             unset($i);
35         }
36         $i = Memcached_DataObject::getcached($cls, $k, $v);
37         if ($i) {
38             return $i;
39         } else {
40             $i = DB_DataObject::factory($cls);
41             if (empty($i)) {
42                 return false;
43             }
44             $result = $i->get($k, $v);
45             if ($result) {
46                 $i->encache();
47                 return $i;
48             } else {
49                 return false;
50             }
51         }
52     }
53
54     function &pkeyGet($cls, $kv)
55     {
56         $i = Memcached_DataObject::multicache($cls, $kv);
57         if ($i) {
58             return $i;
59         } else {
60             $i = new $cls();
61             foreach ($kv as $k => $v) {
62                 $i->$k = $v;
63             }
64             if ($i->find(true)) {
65                 $i->encache();
66             } else {
67                 $i = null;
68             }
69             return $i;
70         }
71     }
72
73     function insert()
74     {
75         $result = parent::insert();
76         return $result;
77     }
78
79     function update($orig=null)
80     {
81         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
82             $orig->decache(); # might be different keys
83         }
84         $result = parent::update($orig);
85         if ($result) {
86             $this->encache();
87         }
88         return $result;
89     }
90
91     function delete()
92     {
93         $this->decache(); # while we still have the values!
94         return parent::delete();
95     }
96
97     static function memcache() {
98         return common_memcache();
99     }
100
101     static function cacheKey($cls, $k, $v) {
102         if (is_object($cls) || is_object($k) || is_object($v)) {
103             $e = new Exception();
104             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
105                 str_replace("\n", " ", $e->getTraceAsString()));
106         }
107         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
108     }
109
110     static function getcached($cls, $k, $v) {
111         $c = Memcached_DataObject::memcache();
112         if (!$c) {
113             return false;
114         } else {
115             return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
116         }
117     }
118
119     function keyTypes()
120     {
121         global $_DB_DATAOBJECT;
122         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
123             $this->databaseStructure();
124
125         }
126         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
127     }
128
129     function encache()
130     {
131         $c = $this->memcache();
132         if (!$c) {
133             return false;
134         } else {
135             $pkey = array();
136             $pval = array();
137             $types = $this->keyTypes();
138             ksort($types);
139             foreach ($types as $key => $type) {
140                 if ($type == 'K') {
141                     $pkey[] = $key;
142                     $pval[] = $this->$key;
143                 } else {
144                     $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
145                 }
146             }
147             # XXX: should work for both compound and scalar pkeys
148             $pvals = implode(',', $pval);
149             $pkeys = implode(',', $pkey);
150             $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
151         }
152     }
153
154     function decache()
155     {
156         $c = $this->memcache();
157         if (!$c) {
158             return false;
159         } else {
160             $pkey = array();
161             $pval = array();
162             $types = $this->keyTypes();
163             ksort($types);
164             foreach ($types as $key => $type) {
165                 if ($type == 'K') {
166                     $pkey[] = $key;
167                     $pval[] = $this->$key;
168                 } else {
169                     $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
170                 }
171             }
172             # should work for both compound and scalar pkeys
173             # XXX: comma works for now but may not be safe separator for future keys
174             $pvals = implode(',', $pval);
175             $pkeys = implode(',', $pkey);
176             $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
177         }
178     }
179
180     function multicache($cls, $kv)
181     {
182         ksort($kv);
183         $c = Memcached_DataObject::memcache();
184         if (!$c) {
185             return false;
186         } else {
187             $pkeys = implode(',', array_keys($kv));
188             $pvals = implode(',', array_values($kv));
189             return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
190         }
191     }
192
193     function getSearchEngine($table)
194     {
195         require_once INSTALLDIR.'/lib/search_engines.php';
196         static $search_engine;
197         if (!isset($search_engine)) {
198             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
199                 if ('mysql' === common_config('db', 'type')) {
200                     $type = common_config('search', 'type');
201                     if ($type == 'like') {
202                         $search_engine = new MySQLLikeSearch($this, $table);
203                     } else if ($type == 'fulltext') {
204                         $search_engine = new MySQLSearch($this, $table);
205                     } else {
206                         throw new ServerException('Unknown search type: ' . $type);
207                     }
208                 } else {
209                     $search_engine = new PGSearch($this, $table);
210                 }
211             }
212         }
213         return $search_engine;
214     }
215
216     static function cachedQuery($cls, $qry, $expiry=3600)
217     {
218         $c = Memcached_DataObject::memcache();
219         if (!$c) {
220             $inst = new $cls();
221             $inst->query($qry);
222             return $inst;
223         }
224         $key_part = common_keyize($cls).':'.md5($qry);
225         $ckey = common_cache_key($key_part);
226         $stored = $c->get($ckey);
227         if ($stored) {
228             return new ArrayWrapper($stored);
229         }
230
231         $inst = new $cls();
232         $inst->query($qry);
233         $cached = array();
234         while ($inst->fetch()) {
235             $cached[] = clone($inst);
236         }
237         $inst->free();
238         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
239         return new ArrayWrapper($cached);
240     }
241
242     // We overload so that 'SET NAMES "utf8"' is called for
243     // each connection
244
245     function _connect()
246     {
247         global $_DB_DATAOBJECT;
248
249         $sum = $this->_getDbDsnMD5();
250
251         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
252             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
253             $exists = true;
254         } else {
255             $exists = false;
256        }
257
258         $result = parent::_connect();
259
260         if ($result && !$exists) {
261             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
262             if (common_config('db', 'type') == 'mysql' &&
263                 common_config('db', 'utf8')) {
264                 $conn = $DB->connection;
265                 if (!empty($conn)) {
266                     if ($DB instanceof DB_mysqli) {
267                         mysqli_set_charset($conn, 'utf8');
268                     } else if ($DB instanceof DB_mysql) {
269                         mysql_set_charset('utf8', $conn);
270                     }
271                 }
272             }
273         }
274
275         return $result;
276     }
277
278     // XXX: largely cadged from DB_DataObject
279
280     function _getDbDsnMD5()
281     {
282         if ($this->_database_dsn_md5) {
283             return $this->_database_dsn_md5;
284         }
285
286         $dsn = $this->_getDbDsn();
287
288         if (is_string($dsn)) {
289             $sum = md5($dsn);
290         } else {
291             /// support array based dsn's
292             $sum = md5(serialize($dsn));
293         }
294
295         return $sum;
296     }
297
298     function _getDbDsn()
299     {
300         global $_DB_DATAOBJECT;
301
302         if (empty($_DB_DATAOBJECT['CONFIG'])) {
303             DB_DataObject::_loadConfig();
304         }
305
306         $options = &$_DB_DATAOBJECT['CONFIG'];
307
308         // if the databse dsn dis defined in the object..
309
310         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
311
312         if (!$dsn) {
313
314             if (!$this->_database) {
315                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
316             }
317
318             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
319                 $dsn = $options["database_{$this->_database}"];
320             } else if (!empty($options['database'])) {
321                 $dsn = $options['database'];
322             }
323         }
324
325         if (!$dsn) {
326             throw new Exception("No database name / dsn found anywhere");
327         }
328
329         return $dsn;
330     }
331 }