Memcached_DataObject.php 32 KB

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