Memcached_DataObject.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * @copyright 2008, 2009 StatusNet, Inc.
  18. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  19. */
  20. defined('GNUSOCIAL') || die();
  21. class Memcached_DataObject extends Safe_DataObject
  22. {
  23. /**
  24. * Wrapper for DB_DataObject's static lookup using memcached
  25. * as backing instead of an in-process cache array.
  26. *
  27. * @param string $cls classname of object type to load
  28. * @param mixed $k key field name, or value for primary key
  29. * @param mixed $v key field value, or leave out for primary key lookup
  30. * @return mixed Memcached_DataObject subtype or false
  31. */
  32. public static function getClassKV($cls, $k, $v = null)
  33. {
  34. if (is_null($v)) {
  35. $v = $k;
  36. $keys = static::pkeyCols();
  37. if (count($keys) > 1) {
  38. // FIXME: maybe call pkeyGetClass() ourselves?
  39. throw new Exception('Use pkeyGetClass() for compound primary keys');
  40. }
  41. $k = $keys[0];
  42. }
  43. $i = self::getcached($cls, $k, $v);
  44. if ($i === false) { // false == cache miss
  45. $i = new $cls;
  46. $result = $i->get($k, $v);
  47. if ($result) {
  48. // Hit!
  49. $i->encache();
  50. } else {
  51. // save the fact that no such row exists
  52. $c = self::memcache();
  53. if (!empty($c)) {
  54. $ck = self::cachekey($cls, $k, $v);
  55. $c->set($ck, null);
  56. }
  57. $i = false;
  58. }
  59. }
  60. return $i;
  61. }
  62. /**
  63. * Get multiple items from the database by key
  64. *
  65. * @param string $cls Class to fetch
  66. * @param string $keyCol name of column for key
  67. * @param array $keyVals key values to fetch
  68. * @param bool $skipNulls return only non-null results
  69. * @param bool $preserve return the same tuples as input
  70. * @return object An object with tuples to be fetched, in order
  71. */
  72. public static function multiGetClass(
  73. string $cls,
  74. string $keyCol,
  75. array $keyVals,
  76. bool $skipNulls,
  77. bool $preserve
  78. ): object {
  79. $obj = new $cls();
  80. // Do not select anything extra
  81. $obj->selectAdd();
  82. $obj->selectAdd($obj->escapedTableName() . '.*');
  83. // A PHP-compatible datatype to check against
  84. $col_type = $obj->columnType($keyCol);
  85. // The code below assumes one of the two results
  86. if (!in_array($col_type, ['int', 'string'])) {
  87. throw new ServerException(
  88. 'Cannot do multiGet on anything but integer or string columns'
  89. );
  90. }
  91. // Actually need to know if MariaDB or Oracle MySQL this time
  92. $db_type = common_config('db', 'type');
  93. if ($db_type === 'mysql') {
  94. $tmp_obj = new $cls();
  95. $tmp_obj->query('SELECT 0 /*M! + 1 */ AS is_mariadb;');
  96. if ($tmp_obj->fetch() && $tmp_obj->is_mariadb) {
  97. $db_type = 'mariadb';
  98. }
  99. }
  100. // Since we're inputting straight to a query: format and escape
  101. $vals_escaped = [];
  102. foreach (array_values($keyVals) as $i => $val) {
  103. if (is_null($val)) {
  104. $val_escaped = 'NULL';
  105. } elseif ($col_type === 'int') {
  106. $val_escaped = (string)(int) $val;
  107. } else {
  108. $val_escaped = "'{$obj->escape($val)}'";
  109. }
  110. if ($db_type !== 'mariadb') {
  111. $vals_escaped[] = $val_escaped;
  112. } else {
  113. // A completely different approach for MariaDB (see below)
  114. $vals_escaped[] = "({$val_escaped},{$i})";
  115. }
  116. }
  117. // One way to guarantee that there is no name collision
  118. $join_tablename = common_database_tablename(
  119. $obj->tableName() . '_vals'
  120. );
  121. $join_keyword = ($preserve ? 'RIGHT' : 'INNER') . ' JOIN';
  122. $vals_cast_type = ($col_type === 'int') ? 'INTEGER' : 'TEXT';
  123. // A lot of magic to ensure we get an ordered reply with the same exact
  124. // values as on input.
  125. switch ($db_type) {
  126. case 'pgsql':
  127. // Explicit casting is done to cast empty arrays
  128. $obj->_join = "\n" . sprintf(
  129. <<<END
  130. {$join_keyword} unnest(
  131. CAST(ARRAY[%s] AS {$vals_cast_type}[])
  132. ) WITH ORDINALITY
  133. AS {$join_tablename} ({$keyCol}, {$keyCol}_pos)
  134. USING ({$keyCol})
  135. END,
  136. implode(',', $vals_escaped)
  137. );
  138. break;
  139. case 'mariadb':
  140. // Delivers an empty set
  141. if (count($vals_escaped) == 0) {
  142. $vals_escaped[] = '(NULL,0) LIMIT 0';
  143. }
  144. // MariaDB doesn't support JSON_TABLE, but Oracle MySQL does,
  145. // which doesn't support VALUES without a ROW keyword though.
  146. $obj->_join = "\n" . sprintf(
  147. <<<END
  148. {$join_keyword} (
  149. WITH t1 ({$keyCol}, {$keyCol}_pos) AS (VALUES %s)
  150. SELECT * FROM t1
  151. ) AS {$join_tablename} USING ({$keyCol})
  152. END,
  153. implode(',', $vals_escaped)
  154. );
  155. break;
  156. case 'mysql':
  157. default:
  158. $obj->_join = "\n" . sprintf(
  159. <<<END
  160. {$join_keyword} JSON_TABLE(
  161. JSON_ARRAY(%s), '$[*]' COLUMNS (
  162. {$keyCol} {$vals_cast_type} PATH '$',
  163. {$keyCol}_pos FOR ORDINALITY
  164. )
  165. ) AS {$join_tablename} USING ({$keyCol})
  166. END,
  167. implode(',', $vals_escaped)
  168. );
  169. }
  170. // Filters both NULLs requested and non-matching NULLs
  171. if ($skipNulls) {
  172. $obj->whereAdd("{$obj->escapedTableName()}.{$keyCol} IS NOT NULL");
  173. }
  174. $obj->orderBy("{$join_tablename}.{$keyCol}_pos");
  175. $obj->find();
  176. return $obj;
  177. }
  178. /**
  179. * Get multiple items from the database by key
  180. *
  181. * @param string $cls Class to fetch
  182. * @param string $keyCol name of column for key
  183. * @param array $keyVals key values to fetch
  184. * @param boolean $otherCols Other columns to hold fixed
  185. *
  186. * @return array Array mapping $keyVals to objects, or null if not found
  187. */
  188. public static function pivotGetClass(
  189. $cls,
  190. $keyCol,
  191. array $keyVals,
  192. array $otherCols = []
  193. ) {
  194. if (is_array($keyCol)) {
  195. foreach ($keyVals as $keyVal) {
  196. if (!is_array($keyVal)) {
  197. throw new ServerException(
  198. 'keyVals passed to pivotGet must be an array of arrays '
  199. . 'if keyCol is an array'
  200. );
  201. }
  202. $result[implode(',', $keyVal)] = null;
  203. }
  204. } else {
  205. $result = array_fill_keys($keyVals, null);
  206. }
  207. $toFetch = array();
  208. foreach ($keyVals as $keyVal) {
  209. if (is_array($keyCol)) {
  210. $kv = array_combine($keyCol, $keyVal);
  211. } else {
  212. $kv = array($keyCol => $keyVal);
  213. }
  214. $kv = array_merge($otherCols, $kv);
  215. $i = self::multicache($cls, $kv);
  216. if ($i !== false) {
  217. if (is_array($keyCol)) {
  218. $result[implode(',', $keyVal)] = $i;
  219. } else {
  220. $result[$keyVal] = $i;
  221. }
  222. } elseif (!empty($keyVal)) {
  223. $toFetch[] = $keyVal;
  224. }
  225. }
  226. if (count($toFetch) > 0) {
  227. $i = new $cls;
  228. foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
  229. $i->$otherKeyCol = $otherKeyVal;
  230. }
  231. if (is_array($keyCol)) {
  232. $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
  233. } else {
  234. $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
  235. }
  236. if ($i->find()) {
  237. while ($i->fetch()) {
  238. $copy = clone($i);
  239. $copy->encache();
  240. if (is_array($keyCol)) {
  241. $vals = array();
  242. foreach ($keyCol as $k) {
  243. $vals[] = $i->$k;
  244. }
  245. $result[implode(',', $vals)] = $copy;
  246. } else {
  247. $result[$i->$keyCol] = $copy;
  248. }
  249. }
  250. }
  251. // Save state of DB misses
  252. foreach ($toFetch as $keyVal) {
  253. $r = null;
  254. if (is_array($keyCol)) {
  255. $r = $result[implode(',', $keyVal)];
  256. } else {
  257. $r = $result[$keyVal];
  258. }
  259. if (empty($r)) {
  260. if (is_array($keyCol)) {
  261. $kv = array_combine($keyCol, $keyVal);
  262. } else {
  263. $kv = array($keyCol => $keyVal);
  264. }
  265. $kv = array_merge($otherCols, $kv);
  266. // save the fact that no such row exists
  267. $c = self::memcache();
  268. if (!empty($c)) {
  269. $ck = self::multicacheKey($cls, $kv);
  270. $c->set($ck, null);
  271. }
  272. }
  273. }
  274. }
  275. return $result;
  276. }
  277. public static function _inMultiKey($i, $cols, $values)
  278. {
  279. $types = array();
  280. foreach ($cols as $col) {
  281. $types[$col] = $i->columnType($col);
  282. }
  283. $first = true;
  284. $query = '';
  285. foreach ($values as $value) {
  286. if ($first) {
  287. $query .= '( ';
  288. $first = false;
  289. } else {
  290. $query .= ' OR ';
  291. }
  292. $query .= '( ';
  293. $i = 0;
  294. $firstc = true;
  295. foreach ($cols as $col) {
  296. if (!$firstc) {
  297. $query .= ' AND ';
  298. } else {
  299. $firstc = false;
  300. }
  301. switch ($types[$col]) {
  302. case 'string':
  303. case 'datetime':
  304. $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
  305. break;
  306. default:
  307. $query .= sprintf("%s = %s", $col, $value[$i]);
  308. break;
  309. }
  310. }
  311. $query .= ') ';
  312. }
  313. if (!$first) {
  314. $query .= ' )';
  315. }
  316. return $query;
  317. }
  318. public static function pkeyColsClass($cls)
  319. {
  320. $i = new $cls;
  321. $types = $i->keyTypes();
  322. ksort($types);
  323. $pkey = array();
  324. foreach ($types as $key => $type) {
  325. if ($type == 'K' || $type == 'N') {
  326. $pkey[] = $key;
  327. }
  328. }
  329. return $pkey;
  330. }
  331. public static function listFindClass($cls, $keyCol, array $keyVals)
  332. {
  333. $i = new $cls;
  334. $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
  335. if (!$i->find()) {
  336. throw new NoResultException($i);
  337. }
  338. return $i;
  339. }
  340. public static function listGetClass($cls, $keyCol, array $keyVals)
  341. {
  342. $pkeyMap = array_fill_keys($keyVals, array());
  343. $result = array_fill_keys($keyVals, array());
  344. $pkeyCols = static::pkeyCols();
  345. $toFetch = array();
  346. $allPkeys = array();
  347. // We only cache keys -- not objects!
  348. foreach ($keyVals as $keyVal) {
  349. $l = self::cacheGet(sprintf('%s:list-ids:%s:%s', strtolower($cls), $keyCol, $keyVal));
  350. if ($l !== false) {
  351. $pkeyMap[$keyVal] = $l;
  352. foreach ($l as $pkey) {
  353. $allPkeys[] = $pkey;
  354. }
  355. } else {
  356. $toFetch[] = $keyVal;
  357. }
  358. }
  359. if (count($allPkeys) > 0) {
  360. $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
  361. foreach ($pkeyMap as $keyVal => $pkeyList) {
  362. foreach ($pkeyList as $pkeyVal) {
  363. $i = $keyResults[implode(',', $pkeyVal)];
  364. if (!empty($i)) {
  365. $result[$keyVal][] = $i;
  366. }
  367. }
  368. }
  369. }
  370. if (count($toFetch) > 0) {
  371. try {
  372. $i = self::listFindClass($cls, $keyCol, $toFetch);
  373. while ($i->fetch()) {
  374. $copy = clone($i);
  375. $copy->encache();
  376. $result[$i->$keyCol][] = $copy;
  377. $pkeyVal = array();
  378. foreach ($pkeyCols as $pkeyCol) {
  379. $pkeyVal[] = $i->$pkeyCol;
  380. }
  381. $pkeyMap[$i->$keyCol][] = $pkeyVal;
  382. }
  383. } catch (NoResultException $e) {
  384. // no results found for our keyVals, so we leave them as empty arrays
  385. }
  386. foreach ($toFetch as $keyVal) {
  387. self::cacheSet(
  388. sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
  389. $pkeyMap[$keyVal]
  390. );
  391. }
  392. }
  393. return $result;
  394. }
  395. public function escapedTableName()
  396. {
  397. return common_database_tablename($this->tableName());
  398. }
  399. public function columnType($columnName)
  400. {
  401. $keys = $this->table();
  402. if (!array_key_exists($columnName, $keys)) {
  403. throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
  404. }
  405. $def = $keys[$columnName];
  406. if ($def & DB_DATAOBJECT_INT) {
  407. return 'int';
  408. } else {
  409. return 'string';
  410. }
  411. }
  412. /**
  413. * @todo FIXME: Should this return false on lookup fail to match getKV?
  414. */
  415. public static function pkeyGetClass($cls, array $kv)
  416. {
  417. $i = self::multicache($cls, $kv);
  418. if ($i !== false) { // false == cache miss
  419. return $i;
  420. } else {
  421. $i = new $cls;
  422. foreach ($kv as $k => $v) {
  423. if (is_null($v)) {
  424. // XXX: possible SQL injection...? Don't
  425. // pass keys from the browser, eh.
  426. $i->whereAdd("$k is null");
  427. } else {
  428. $i->$k = $v;
  429. }
  430. }
  431. if ($i->find(true)) {
  432. $i->encache();
  433. } else {
  434. $i = null;
  435. $c = self::memcache();
  436. if (!empty($c)) {
  437. $ck = self::multicacheKey($cls, $kv);
  438. $c->set($ck, null);
  439. }
  440. }
  441. return $i;
  442. }
  443. }
  444. public function insert()
  445. {
  446. $result = parent::insert();
  447. if ($result !== false) {
  448. // In case of cached negative lookups
  449. $this->decache();
  450. }
  451. return $result;
  452. }
  453. public function update($dataObject = false)
  454. {
  455. if (is_object($dataObject) && $dataObject instanceof Memcached_DataObject) {
  456. $dataObject->decache(); // might be different keys
  457. }
  458. $result = parent::update($dataObject);
  459. if ($result !== false) {
  460. // Cannot encache yet, so decache instead
  461. $this->decache();
  462. }
  463. return $result;
  464. }
  465. public function delete($useWhere = false)
  466. {
  467. $this->decache(); # while we still have the values!
  468. return parent::delete($useWhere);
  469. }
  470. public static function memcache()
  471. {
  472. return Cache::instance();
  473. }
  474. public static function cacheKey($cls, $k, $v)
  475. {
  476. if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
  477. $e = new Exception();
  478. common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
  479. str_replace("\n", " ", $e->getTraceAsString()));
  480. }
  481. $vstr = self::valueString($v);
  482. return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
  483. }
  484. public static function getcached($cls, $k, $v)
  485. {
  486. $c = self::memcache();
  487. if (!$c) {
  488. return false;
  489. } else {
  490. $obj = $c->get(self::cacheKey($cls, $k, $v));
  491. if (0 == strcasecmp($cls, 'User')) {
  492. // Special case for User
  493. if (is_object($obj) && is_object($obj->id)) {
  494. common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
  495. $c->delete(self::cacheKey($cls, $k, $v));
  496. return false;
  497. }
  498. }
  499. return $obj;
  500. }
  501. }
  502. public function keyTypes()
  503. {
  504. // ini-based classes return number-indexed arrays. handbuilt
  505. // classes return column => keytype. Make this uniform.
  506. $keys = $this->keys();
  507. $keyskeys = array_keys($keys);
  508. if (is_string($keyskeys[0])) {
  509. return $keys;
  510. }
  511. global $_DB_DATAOBJECT;
  512. if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
  513. $this->databaseStructure();
  514. }
  515. return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"];
  516. }
  517. public function encache()
  518. {
  519. if ($this->N < 1) {
  520. // Caching breaks when it is too early.
  521. $e = new Exception();
  522. common_log(
  523. LOG_ERR,
  524. 'DataObject must be the result of a query (N>=1) before encache() '
  525. . str_replace("\n", ' ', $e->getTraceAsString())
  526. );
  527. return false;
  528. }
  529. $c = self::memcache();
  530. if (!$c) {
  531. return false;
  532. } elseif ($this->tableName() === 'user' && is_object($this->id)) {
  533. // Special case for User bug
  534. $e = new Exception();
  535. common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
  536. str_replace("\n", " ", $e->getTraceAsString()));
  537. return false;
  538. } else {
  539. $keys = $this->_allCacheKeys();
  540. foreach ($keys as $key) {
  541. $c->set($key, $this);
  542. }
  543. }
  544. }
  545. public function decache()
  546. {
  547. $c = self::memcache();
  548. if (!$c) {
  549. return false;
  550. }
  551. $keys = $this->_allCacheKeys();
  552. foreach ($keys as $key) {
  553. $c->delete($key, $this);
  554. }
  555. }
  556. public function _allCacheKeys()
  557. {
  558. $ckeys = array();
  559. $types = $this->keyTypes();
  560. ksort($types);
  561. $pkey = array();
  562. $pval = array();
  563. foreach ($types as $key => $type) {
  564. assert(!empty($key));
  565. if ($type == 'U') {
  566. if (empty($this->$key)) {
  567. continue;
  568. }
  569. $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
  570. } elseif (in_array($type, ['K', 'N'])) {
  571. $pkey[] = $key;
  572. $pval[] = self::valueString($this->$key);
  573. } else {
  574. // Low level exception. No need for i18n as discussed with Brion.
  575. throw new Exception("Unknown key type $key => $type for " . $this->tableName());
  576. }
  577. }
  578. assert(count($pkey) > 0);
  579. // XXX: should work for both compound and scalar pkeys
  580. $pvals = implode(',', $pval);
  581. $pkeys = implode(',', $pkey);
  582. $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
  583. return $ckeys;
  584. }
  585. public static function multicache($cls, array $kv)
  586. {
  587. ksort($kv);
  588. $c = self::memcache();
  589. if (!$c) {
  590. return false;
  591. } else {
  592. return $c->get(self::multicacheKey($cls, $kv));
  593. }
  594. }
  595. public static function multicacheKey($cls, array $kv)
  596. {
  597. ksort($kv);
  598. $pkeys = implode(',', array_keys($kv));
  599. $pvals = implode(',', array_values($kv));
  600. return self::cacheKey($cls, $pkeys, $pvals);
  601. }
  602. public function getSearchEngine($table)
  603. {
  604. require_once INSTALLDIR . '/lib/search/search_engines.php';
  605. if (Event::handle('GetSearchEngine', [$this, $table, &$search_engine])) {
  606. $type = common_config('search', 'type');
  607. if ($type === 'like') {
  608. $search_engine = new SQLLikeSearch($this, $table);
  609. } elseif ($type === 'fulltext') {
  610. switch (common_config('db', 'type')) {
  611. case 'pgsql':
  612. $search_engine = new PostgreSQLSearch($this, $table);
  613. break;
  614. case 'mysql':
  615. $search_engine = new MySQLSearch($this, $table);
  616. break;
  617. default:
  618. throw new ServerException('Unknown DB type selected.');
  619. }
  620. } else {
  621. // Low level exception. No need for i18n as discussed with Brion.
  622. throw new ServerException('Unknown search type: ' . $type);
  623. }
  624. }
  625. return $search_engine;
  626. }
  627. public static function cachedQuery($cls, $qry, $expiry = 3600)
  628. {
  629. $c = self::memcache();
  630. if (!$c) {
  631. $inst = new $cls();
  632. $inst->query($qry);
  633. return $inst;
  634. }
  635. $key_part = Cache::keyize($cls).':'.md5($qry);
  636. $ckey = Cache::key($key_part);
  637. $stored = $c->get($ckey);
  638. if ($stored !== false) {
  639. return new ArrayWrapper($stored);
  640. }
  641. $inst = new $cls();
  642. $inst->query($qry);
  643. $cached = array();
  644. while ($inst->fetch()) {
  645. $cached[] = clone($inst);
  646. }
  647. $inst->free();
  648. $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
  649. return new ArrayWrapper($cached);
  650. }
  651. /**
  652. * sends query to database - this is the private one that must work
  653. * - internal functions use this rather than $this->query()
  654. *
  655. * Overridden to do logging.
  656. *
  657. * @param string $string
  658. * @access private
  659. * @return mixed none or PEAR_Error
  660. */
  661. public function _query($string)
  662. {
  663. if (common_config('db', 'annotate_queries')) {
  664. $string = $this->annotateQuery($string);
  665. }
  666. $start = hrtime(true);
  667. $fail = false;
  668. $result = null;
  669. if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
  670. common_perf_counter('query', $string);
  671. try {
  672. $result = parent::_query($string);
  673. } catch (Exception $e) {
  674. $fail = $e;
  675. }
  676. Event::handle('EndDBQuery', array($this, $string, &$result));
  677. }
  678. $delta = (hrtime(true) - $start) / 1000000000;
  679. $limit = common_config('db', 'log_slow_queries');
  680. if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
  681. $clean = $this->sanitizeQuery($string);
  682. if ($fail) {
  683. $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
  684. } else {
  685. $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
  686. }
  687. common_log(LOG_DEBUG, $msg);
  688. }
  689. if ($fail) {
  690. throw $fail;
  691. }
  692. return $result;
  693. }
  694. /**
  695. * Find the first caller in the stack trace that's not a
  696. * low-level database function and add a comment to the
  697. * query string. This should then be visible in process lists
  698. * and slow query logs, to help identify problem areas.
  699. *
  700. * Also marks whether this was a web GET/POST or which daemon
  701. * was running it.
  702. *
  703. * @param string $string SQL query string
  704. * @return string SQL query string, with a comment in it
  705. */
  706. public function annotateQuery($string)
  707. {
  708. $ignore = array('annotateQuery',
  709. '_query',
  710. 'query',
  711. 'get',
  712. 'insert',
  713. 'delete',
  714. 'update',
  715. 'find');
  716. $ignoreStatic = array('getKV',
  717. 'getClassKV',
  718. 'pkeyGet',
  719. 'pkeyGetClass',
  720. 'cachedQuery');
  721. $here = get_class($this); // if we get confused
  722. $bt = debug_backtrace();
  723. // Find the first caller that's not us?
  724. foreach ($bt as $frame) {
  725. $func = $frame['function'];
  726. if (isset($frame['type']) && $frame['type'] == '::') {
  727. if (in_array($func, $ignoreStatic)) {
  728. continue;
  729. }
  730. $here = $frame['class'] . '::' . $func;
  731. break;
  732. } elseif (isset($frame['type']) && $frame['type'] === '->') {
  733. if ($frame['object'] === $this && in_array($func, $ignore)) {
  734. continue;
  735. }
  736. if (in_array($func, $ignoreStatic)) {
  737. continue; // @todo FIXME: This shouldn't be needed?
  738. }
  739. $here = get_class($frame['object']) . '->' . $func;
  740. break;
  741. }
  742. $here = $func;
  743. break;
  744. }
  745. if (php_sapi_name() == 'cli') {
  746. $context = basename($_SERVER['PHP_SELF']);
  747. } else {
  748. $context = $_SERVER['REQUEST_METHOD'];
  749. }
  750. // Slip the comment in after the first command,
  751. // or DB_DataObject gets confused about handling inserts and such.
  752. $parts = explode(' ', $string, 2);
  753. $parts[0] .= " /* $context $here */";
  754. return implode(' ', $parts);
  755. }
  756. // Sanitize a query for logging
  757. // @fixme don't trim spaces in string literals
  758. public function sanitizeQuery($string)
  759. {
  760. $string = preg_replace('/\s+/', ' ', $string);
  761. $string = trim($string);
  762. return $string;
  763. }
  764. public function _connect()
  765. {
  766. global $_DB_DATAOBJECT, $_PEAR;
  767. $sum = $this->_getDbDsnMD5();
  768. if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
  769. !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
  770. $exists = true;
  771. } else {
  772. $exists = false;
  773. }
  774. // @fixme horrible evil hack!
  775. //
  776. // In multisite configuration we don't want to keep around a separate
  777. // connection for every database; we could end up with thousands of
  778. // connections open per thread. In an ideal world we might keep
  779. // a connection per server and select different databases, but that'd
  780. // be reliant on having the same db username/pass as well.
  781. //
  782. // MySQL connections are cheap enough we're going to try just
  783. // closing out the old connection and reopening when we encounter
  784. // a new DSN.
  785. //
  786. // WARNING WARNING if we end up actually using multiple DBs at a time
  787. // we'll need some fancier logic here.
  788. if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
  789. foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
  790. if ($_PEAR->isError($conn)) {
  791. common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
  792. } elseif (!empty($conn)) {
  793. $conn->disconnect();
  794. }
  795. unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
  796. }
  797. }
  798. $result = parent::_connect();
  799. if ($result && !$exists) {
  800. // Required to make timestamp values usefully comparable.
  801. if (common_config('db', 'type') !== 'mysql') {
  802. parent::_query("SET TIME ZONE INTERVAL '+00:00' HOUR TO MINUTE");
  803. } else {
  804. parent::_query("SET time_zone = '+0:00'");
  805. }
  806. }
  807. return $result;
  808. }
  809. // XXX: largely cadged from DB_DataObject
  810. public function _getDbDsnMD5()
  811. {
  812. if ($this->_database_dsn_md5) {
  813. return $this->_database_dsn_md5;
  814. }
  815. $dsn = $this->_getDbDsn();
  816. if (is_string($dsn)) {
  817. $sum = md5($dsn);
  818. } else {
  819. /// support array based dsn's
  820. $sum = md5(serialize($dsn));
  821. }
  822. return $sum;
  823. }
  824. public function _getDbDsn()
  825. {
  826. global $_DB_DATAOBJECT;
  827. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  828. self::_loadConfig();
  829. }
  830. $options = &$_DB_DATAOBJECT['CONFIG'];
  831. // if the databse dsn dis defined in the object..
  832. $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
  833. if (!$dsn) {
  834. if (!$this->_database) {
  835. $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
  836. }
  837. if ($this->_database && !empty($options["database_{$this->_database}"])) {
  838. $dsn = $options["database_{$this->_database}"];
  839. } elseif (!empty($options['database'])) {
  840. $dsn = $options['database'];
  841. }
  842. }
  843. if (!$dsn) {
  844. // TRANS: Exception thrown when database name or Data Source Name could not be found.
  845. throw new Exception(_('No database name or DSN found anywhere.'));
  846. }
  847. return $dsn;
  848. }
  849. public static function blow()
  850. {
  851. $c = self::memcache();
  852. if (empty($c)) {
  853. return false;
  854. }
  855. $args = func_get_args();
  856. $format = array_shift($args);
  857. $keyPart = vsprintf($format, $args);
  858. $cacheKey = Cache::key($keyPart);
  859. return $c->delete($cacheKey);
  860. }
  861. public function raiseError($message, $type = null, $behavior = null)
  862. {
  863. $id = get_class($this);
  864. if (!empty($this->id)) {
  865. $id .= ':' . $this->id;
  866. }
  867. if ($message instanceof PEAR_Error) {
  868. $message = $message->getMessage();
  869. }
  870. // Low level exception. No need for i18n as discussed with Brion.
  871. throw new ServerException("[$id] DB_DataObject error [$type]: $message");
  872. }
  873. public static function cacheGet($keyPart)
  874. {
  875. $c = self::memcache();
  876. if (empty($c)) {
  877. return false;
  878. }
  879. $cacheKey = Cache::key($keyPart);
  880. return $c->get($cacheKey);
  881. }
  882. public static function cacheSet($keyPart, $value, $flag = null, $expiry = null)
  883. {
  884. $c = self::memcache();
  885. if (empty($c)) {
  886. return false;
  887. }
  888. $cacheKey = Cache::key($keyPart);
  889. return $c->set($cacheKey, $value, $flag, $expiry);
  890. }
  891. public static function valueString($v)
  892. {
  893. $vstr = null;
  894. if (is_object($v) && $v instanceof DB_DataObject_Cast) {
  895. switch ($v->type) {
  896. case 'date':
  897. $vstr = "{$v->year} - {$v->month} - {$v->day}";
  898. break;
  899. case 'sql':
  900. if (strcasecmp($v->value, 'NULL') == 0) {
  901. // Very selectively handling NULLs.
  902. $vstr = '';
  903. break;
  904. }
  905. // no break
  906. case 'blob':
  907. case 'string':
  908. case 'datetime':
  909. case 'time':
  910. // Low level exception. No need for i18n as discussed with Brion.
  911. throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  912. break;
  913. default:
  914. // Low level exception. No need for i18n as discussed with Brion.
  915. throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  916. break;
  917. }
  918. } else {
  919. $vstr = strval($v);
  920. }
  921. return $vstr;
  922. }
  923. }