Memcached_DataObject.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. if (empty($key)) {
  565. doom("\$keyは空です。", __FILE__, __LINE__);
  566. }
  567. if ($type == 'U') {
  568. if (empty($this->$key)) {
  569. continue;
  570. }
  571. $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
  572. } elseif (in_array($type, ['K', 'N'])) {
  573. $pkey[] = $key;
  574. $pval[] = self::valueString($this->$key);
  575. } else {
  576. // Low level exception. No need for i18n as discussed with Brion.
  577. throw new Exception("Unknown key type $key => $type for " . $this->tableName());
  578. }
  579. }
  580. if (count($pkey) > 0) {
  581. doom("配列\$pkeyの中に、誰もいませんよ。", __FILE__, __LINE__);
  582. }
  583. // XXX: should work for both compound and scalar pkeys
  584. $pvals = implode(',', $pval);
  585. $pkeys = implode(',', $pkey);
  586. $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
  587. return $ckeys;
  588. }
  589. public static function multicache($cls, array $kv)
  590. {
  591. ksort($kv);
  592. $c = self::memcache();
  593. if (!$c) {
  594. return false;
  595. } else {
  596. return $c->get(self::multicacheKey($cls, $kv));
  597. }
  598. }
  599. public static function multicacheKey($cls, array $kv)
  600. {
  601. ksort($kv);
  602. $pkeys = implode(',', array_keys($kv));
  603. $pvals = implode(',', array_values($kv));
  604. return self::cacheKey($cls, $pkeys, $pvals);
  605. }
  606. public function getSearchEngine($table)
  607. {
  608. require_once INSTALLDIR . '/lib/search/search_engines.php';
  609. if (Event::handle('GetSearchEngine', [$this, $table, &$search_engine])) {
  610. $type = common_config('search', 'type');
  611. if ($type === 'like') {
  612. $search_engine = new SQLLikeSearch($this, $table);
  613. } elseif ($type === 'fulltext') {
  614. switch (common_config('db', 'type')) {
  615. case 'pgsql':
  616. $search_engine = new PostgreSQLSearch($this, $table);
  617. break;
  618. case 'mysql':
  619. $search_engine = new MySQLSearch($this, $table);
  620. break;
  621. default:
  622. throw new ServerException('Unknown DB type selected.');
  623. }
  624. } else {
  625. // Low level exception. No need for i18n as discussed with Brion.
  626. throw new ServerException('Unknown search type: ' . $type);
  627. }
  628. }
  629. return $search_engine;
  630. }
  631. public static function cachedQuery($cls, $qry, $expiry = 3600)
  632. {
  633. $c = self::memcache();
  634. if (!$c) {
  635. $inst = new $cls();
  636. $inst->query($qry);
  637. return $inst;
  638. }
  639. $key_part = Cache::keyize($cls).':'.md5($qry);
  640. $ckey = Cache::key($key_part);
  641. $stored = $c->get($ckey);
  642. if ($stored !== false) {
  643. return new ArrayWrapper($stored);
  644. }
  645. $inst = new $cls();
  646. $inst->query($qry);
  647. $cached = array();
  648. while ($inst->fetch()) {
  649. $cached[] = clone($inst);
  650. }
  651. $inst->free();
  652. $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
  653. return new ArrayWrapper($cached);
  654. }
  655. /**
  656. * sends query to database - this is the private one that must work
  657. * - internal functions use this rather than $this->query()
  658. *
  659. * Overridden to do logging.
  660. *
  661. * @param string $string
  662. * @access private
  663. * @return mixed none or PEAR_Error
  664. */
  665. public function _query($string)
  666. {
  667. if (common_config('db', 'annotate_queries')) {
  668. $string = $this->annotateQuery($string);
  669. }
  670. $start = hrtime(true);
  671. $fail = false;
  672. $result = null;
  673. if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
  674. common_perf_counter('query', $string);
  675. try {
  676. $result = parent::_query($string);
  677. } catch (Exception $e) {
  678. $fail = $e;
  679. }
  680. Event::handle('EndDBQuery', array($this, $string, &$result));
  681. }
  682. $delta = (hrtime(true) - $start) / 1000000000;
  683. $limit = common_config('db', 'log_slow_queries');
  684. if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
  685. $clean = $this->sanitizeQuery($string);
  686. if ($fail) {
  687. $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
  688. } else {
  689. $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
  690. }
  691. common_log(LOG_DEBUG, $msg);
  692. }
  693. if ($fail) {
  694. throw $fail;
  695. }
  696. return $result;
  697. }
  698. /**
  699. * Find the first caller in the stack trace that's not a
  700. * low-level database function and add a comment to the
  701. * query string. This should then be visible in process lists
  702. * and slow query logs, to help identify problem areas.
  703. *
  704. * Also marks whether this was a web GET/POST or which daemon
  705. * was running it.
  706. *
  707. * @param string $string SQL query string
  708. * @return string SQL query string, with a comment in it
  709. */
  710. public function annotateQuery($string)
  711. {
  712. $ignore = array('annotateQuery',
  713. '_query',
  714. 'query',
  715. 'get',
  716. 'insert',
  717. 'delete',
  718. 'update',
  719. 'find');
  720. $ignoreStatic = array('getKV',
  721. 'getClassKV',
  722. 'pkeyGet',
  723. 'pkeyGetClass',
  724. 'cachedQuery');
  725. $here = get_class($this); // if we get confused
  726. $bt = debug_backtrace();
  727. // Find the first caller that's not us?
  728. foreach ($bt as $frame) {
  729. $func = $frame['function'];
  730. if (isset($frame['type']) && $frame['type'] == '::') {
  731. if (in_array($func, $ignoreStatic)) {
  732. continue;
  733. }
  734. $here = $frame['class'] . '::' . $func;
  735. break;
  736. } elseif (isset($frame['type']) && $frame['type'] === '->') {
  737. if ($frame['object'] === $this && in_array($func, $ignore)) {
  738. continue;
  739. }
  740. if (in_array($func, $ignoreStatic)) {
  741. continue; // @todo FIXME: This shouldn't be needed?
  742. }
  743. $here = get_class($frame['object']) . '->' . $func;
  744. break;
  745. }
  746. $here = $func;
  747. break;
  748. }
  749. if (php_sapi_name() == 'cli') {
  750. $context = basename($_SERVER['PHP_SELF']);
  751. } else {
  752. $context = $_SERVER['REQUEST_METHOD'];
  753. }
  754. // Slip the comment in after the first command,
  755. // or DB_DataObject gets confused about handling inserts and such.
  756. $parts = explode(' ', $string, 2);
  757. $parts[0] .= " /* $context $here */";
  758. return implode(' ', $parts);
  759. }
  760. // Sanitize a query for logging
  761. // @fixme don't trim spaces in string literals
  762. public function sanitizeQuery($string)
  763. {
  764. $string = preg_replace('/\s+/', ' ', $string);
  765. $string = trim($string);
  766. return $string;
  767. }
  768. public function _connect()
  769. {
  770. global $_DB_DATAOBJECT, $_PEAR;
  771. $sum = $this->_getDbDsnMD5();
  772. if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
  773. !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
  774. $exists = true;
  775. } else {
  776. $exists = false;
  777. }
  778. // @fixme horrible evil hack!
  779. //
  780. // In multisite configuration we don't want to keep around a separate
  781. // connection for every database; we could end up with thousands of
  782. // connections open per thread. In an ideal world we might keep
  783. // a connection per server and select different databases, but that'd
  784. // be reliant on having the same db username/pass as well.
  785. //
  786. // MySQL connections are cheap enough we're going to try just
  787. // closing out the old connection and reopening when we encounter
  788. // a new DSN.
  789. //
  790. // WARNING WARNING if we end up actually using multiple DBs at a time
  791. // we'll need some fancier logic here.
  792. if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
  793. foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
  794. if ($_PEAR->isError($conn)) {
  795. common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
  796. } elseif (!empty($conn)) {
  797. $conn->disconnect();
  798. }
  799. unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
  800. }
  801. }
  802. $result = parent::_connect();
  803. if ($result && !$exists) {
  804. // Required to make timestamp values usefully comparable.
  805. if (common_config('db', 'type') !== 'mysql') {
  806. parent::_query("SET TIME ZONE INTERVAL '+00:00' HOUR TO MINUTE");
  807. } else {
  808. parent::_query("SET time_zone = '+0:00'");
  809. }
  810. }
  811. return $result;
  812. }
  813. // XXX: largely cadged from DB_DataObject
  814. public function _getDbDsnMD5()
  815. {
  816. if ($this->_database_dsn_md5) {
  817. return $this->_database_dsn_md5;
  818. }
  819. $dsn = $this->_getDbDsn();
  820. if (is_string($dsn)) {
  821. $sum = md5($dsn);
  822. } else {
  823. /// support array based dsn's
  824. $sum = md5(serialize($dsn));
  825. }
  826. return $sum;
  827. }
  828. public function _getDbDsn()
  829. {
  830. global $_DB_DATAOBJECT;
  831. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  832. self::_loadConfig();
  833. }
  834. $options = &$_DB_DATAOBJECT['CONFIG'];
  835. // if the databse dsn dis defined in the object..
  836. $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
  837. if (!$dsn) {
  838. if (!$this->_database) {
  839. $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
  840. }
  841. if ($this->_database && !empty($options["database_{$this->_database}"])) {
  842. $dsn = $options["database_{$this->_database}"];
  843. } elseif (!empty($options['database'])) {
  844. $dsn = $options['database'];
  845. }
  846. }
  847. if (!$dsn) {
  848. // TRANS: Exception thrown when database name or Data Source Name could not be found.
  849. throw new Exception(_('No database name or DSN found anywhere.'));
  850. }
  851. return $dsn;
  852. }
  853. public static function blow()
  854. {
  855. $c = self::memcache();
  856. if (empty($c)) {
  857. return false;
  858. }
  859. $args = func_get_args();
  860. $format = array_shift($args);
  861. $keyPart = vsprintf($format, $args);
  862. $cacheKey = Cache::key($keyPart);
  863. return $c->delete($cacheKey);
  864. }
  865. public function raiseError($message, $type = null, $behavior = null)
  866. {
  867. $id = get_class($this);
  868. if (!empty($this->id)) {
  869. $id .= ':' . $this->id;
  870. }
  871. if ($message instanceof PEAR_Error) {
  872. $message = $message->getMessage();
  873. }
  874. // Low level exception. No need for i18n as discussed with Brion.
  875. throw new ServerException("[$id] DB_DataObject error [$type]: $message");
  876. }
  877. public static function cacheGet($keyPart)
  878. {
  879. $c = self::memcache();
  880. if (empty($c)) {
  881. return false;
  882. }
  883. $cacheKey = Cache::key($keyPart);
  884. return $c->get($cacheKey);
  885. }
  886. public static function cacheSet($keyPart, $value, $flag = null, $expiry = null)
  887. {
  888. $c = self::memcache();
  889. if (empty($c)) {
  890. return false;
  891. }
  892. $cacheKey = Cache::key($keyPart);
  893. return $c->set($cacheKey, $value, $flag, $expiry);
  894. }
  895. public static function valueString($v)
  896. {
  897. $vstr = null;
  898. if (is_object($v) && $v instanceof DB_DataObject_Cast) {
  899. switch ($v->type) {
  900. case 'date':
  901. $vstr = "{$v->year} - {$v->month} - {$v->day}";
  902. break;
  903. case 'sql':
  904. if (strcasecmp($v->value, 'NULL') == 0) {
  905. // Very selectively handling NULLs.
  906. $vstr = '';
  907. break;
  908. }
  909. // no break
  910. case 'blob':
  911. case 'string':
  912. case 'datetime':
  913. case 'time':
  914. // Low level exception. No need for i18n as discussed with Brion.
  915. throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  916. break;
  917. default:
  918. // Low level exception. No need for i18n as discussed with Brion.
  919. throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  920. break;
  921. }
  922. } else {
  923. $vstr = strval($v);
  924. }
  925. return $vstr;
  926. }
  927. }