PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/phpBB/phpbb/db/driver/sqlite3.php

http://github.com/phpbb/phpbb
PHP | 430 lines | 262 code | 62 blank | 106 comment | 52 complexity | 52acc2ec65a0ecc8e645e0f86bdb3885 MD5 | raw file
Possible License(s): GPL-3.0, AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. namespace phpbb\db\driver;
  14. /**
  15. * SQLite3 Database Abstraction Layer
  16. * Minimum Requirement: 3.6.15+
  17. */
  18. class sqlite3 extends \phpbb\db\driver\driver
  19. {
  20. /**
  21. * @var string Stores errors during connection setup in case the driver is not available
  22. */
  23. protected $connect_error = '';
  24. /**
  25. * @var \SQLite3 The SQLite3 database object to operate against
  26. */
  27. protected $dbo = null;
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
  32. {
  33. $this->persistency = false;
  34. $this->user = $sqluser;
  35. $this->server = $sqlserver . (($port) ? ':' . $port : '');
  36. $this->dbname = $database;
  37. if (!class_exists('SQLite3', false))
  38. {
  39. $this->connect_error = 'SQLite3 not found, is the extension installed?';
  40. return $this->sql_error('');
  41. }
  42. try
  43. {
  44. $this->dbo = new \SQLite3($this->server, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
  45. $this->dbo->busyTimeout(60000);
  46. $this->db_connect_id = true;
  47. }
  48. catch (\Exception $e)
  49. {
  50. $this->connect_error = $e->getMessage();
  51. return array('message' => $this->connect_error);
  52. }
  53. return true;
  54. }
  55. /**
  56. * {@inheritDoc}
  57. */
  58. public function sql_server_info($raw = false, $use_cache = true)
  59. {
  60. global $cache;
  61. if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('sqlite_version')) === false)
  62. {
  63. $version = \SQLite3::version();
  64. $this->sql_server_version = $version['versionString'];
  65. if (!empty($cache) && $use_cache)
  66. {
  67. $cache->put('sqlite_version', $this->sql_server_version);
  68. }
  69. }
  70. return ($raw) ? $this->sql_server_version : 'SQLite ' . $this->sql_server_version;
  71. }
  72. /**
  73. * SQL Transaction
  74. *
  75. * @param string $status Should be one of the following strings:
  76. * begin, commit, rollback
  77. * @return bool Success/failure of the transaction query
  78. */
  79. protected function _sql_transaction($status = 'begin')
  80. {
  81. switch ($status)
  82. {
  83. case 'begin':
  84. return $this->dbo->exec('BEGIN IMMEDIATE');
  85. break;
  86. case 'commit':
  87. return $this->dbo->exec('COMMIT');
  88. break;
  89. case 'rollback':
  90. return @$this->dbo->exec('ROLLBACK');
  91. break;
  92. }
  93. return true;
  94. }
  95. /**
  96. * {@inheritDoc}
  97. */
  98. public function sql_query($query = '', $cache_ttl = 0)
  99. {
  100. if ($query != '')
  101. {
  102. global $cache;
  103. if ($this->debug_sql_explain)
  104. {
  105. $this->sql_report('start', $query);
  106. }
  107. else if ($this->debug_load_time)
  108. {
  109. $this->curtime = microtime(true);
  110. }
  111. $this->last_query_text = $query;
  112. $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false;
  113. $this->sql_add_num_queries($this->query_result);
  114. if ($this->query_result === false)
  115. {
  116. if ($this->transaction === true && strpos($query, 'INSERT') === 0)
  117. {
  118. $query = preg_replace('/^INSERT INTO/', 'INSERT OR ROLLBACK INTO', $query);
  119. }
  120. if (($this->query_result = @$this->dbo->query($query)) === false)
  121. {
  122. // Try to recover a lost database connection
  123. if ($this->dbo && !@$this->dbo->lastErrorMsg())
  124. {
  125. if ($this->sql_connect($this->server, $this->user, '', $this->dbname))
  126. {
  127. $this->query_result = @$this->dbo->query($query);
  128. }
  129. }
  130. if ($this->query_result === false)
  131. {
  132. $this->sql_error($query);
  133. }
  134. }
  135. if ($this->debug_sql_explain)
  136. {
  137. $this->sql_report('stop', $query);
  138. }
  139. else if ($this->debug_load_time)
  140. {
  141. $this->sql_time += microtime(true) - $this->curtime;
  142. }
  143. if (!$this->query_result)
  144. {
  145. return false;
  146. }
  147. if ($cache && $cache_ttl)
  148. {
  149. $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl);
  150. }
  151. }
  152. else if ($this->debug_sql_explain)
  153. {
  154. $this->sql_report('fromcache', $query);
  155. }
  156. }
  157. else
  158. {
  159. return false;
  160. }
  161. return $this->query_result;
  162. }
  163. /**
  164. * Build LIMIT query
  165. *
  166. * @param string $query The SQL query to execute
  167. * @param int $total The number of rows to select
  168. * @param int $offset
  169. * @param int $cache_ttl Either 0 to avoid caching or
  170. * the time in seconds which the result shall be kept in cache
  171. * @return mixed Buffered, seekable result handle, false on error
  172. */
  173. protected function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
  174. {
  175. $this->query_result = false;
  176. // if $total is set to 0 we do not want to limit the number of rows
  177. if ($total == 0)
  178. {
  179. $total = -1;
  180. }
  181. $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total);
  182. return $this->sql_query($query, $cache_ttl);
  183. }
  184. /**
  185. * {@inheritDoc}
  186. */
  187. public function sql_affectedrows()
  188. {
  189. return ($this->db_connect_id) ? $this->dbo->changes() : false;
  190. }
  191. /**
  192. * {@inheritDoc}
  193. */
  194. public function sql_fetchrow($query_id = false)
  195. {
  196. global $cache;
  197. if ($query_id === false)
  198. {
  199. /** @var \SQLite3Result $query_id */
  200. $query_id = $this->query_result;
  201. }
  202. if ($cache && !is_object($query_id) && $cache->sql_exists($query_id))
  203. {
  204. return $cache->sql_fetchrow($query_id);
  205. }
  206. return is_object($query_id) ? @$query_id->fetchArray(SQLITE3_ASSOC) : false;
  207. }
  208. /**
  209. * {@inheritDoc}
  210. */
  211. public function sql_nextid()
  212. {
  213. return ($this->db_connect_id) ? $this->dbo->lastInsertRowID() : false;
  214. }
  215. /**
  216. * {@inheritDoc}
  217. */
  218. public function sql_freeresult($query_id = false)
  219. {
  220. global $cache;
  221. if ($query_id === false)
  222. {
  223. $query_id = $this->query_result;
  224. }
  225. if ($cache && !is_object($query_id) && $cache->sql_exists($query_id))
  226. {
  227. return $cache->sql_freeresult($query_id);
  228. }
  229. if ($query_id)
  230. {
  231. return @$query_id->finalize();
  232. }
  233. }
  234. /**
  235. * {@inheritDoc}
  236. */
  237. public function sql_escape($msg)
  238. {
  239. return \SQLite3::escapeString($msg);
  240. }
  241. /**
  242. * {@inheritDoc}
  243. *
  244. * For SQLite an underscore is an unknown character.
  245. */
  246. public function sql_like_expression($expression)
  247. {
  248. // Unlike LIKE, GLOB is unfortunately case sensitive.
  249. // We only catch * and ? here, not the character map possible on file globbing.
  250. $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression);
  251. $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression);
  252. $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression);
  253. return 'GLOB \'' . $this->sql_escape($expression) . '\'';
  254. }
  255. /**
  256. * {@inheritDoc}
  257. *
  258. * For SQLite an underscore is an unknown character.
  259. */
  260. public function sql_not_like_expression($expression)
  261. {
  262. // Unlike NOT LIKE, NOT GLOB is unfortunately case sensitive
  263. // We only catch * and ? here, not the character map possible on file globbing.
  264. $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression);
  265. $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression);
  266. $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression);
  267. return 'NOT GLOB \'' . $this->sql_escape($expression) . '\'';
  268. }
  269. /**
  270. * return sql error array
  271. *
  272. * @return array
  273. */
  274. protected function _sql_error()
  275. {
  276. if (class_exists('SQLite3', false) && isset($this->dbo))
  277. {
  278. $error = array(
  279. 'message' => $this->dbo->lastErrorMsg(),
  280. 'code' => $this->dbo->lastErrorCode(),
  281. );
  282. }
  283. else
  284. {
  285. $error = array(
  286. 'message' => $this->connect_error,
  287. 'code' => '',
  288. );
  289. }
  290. return $error;
  291. }
  292. /**
  293. * Build db-specific query data
  294. *
  295. * @param string $stage Available stages: FROM, WHERE
  296. * @param mixed $data A string containing the CROSS JOIN query or an array of WHERE clauses
  297. *
  298. * @return string The db-specific query fragment
  299. */
  300. protected function _sql_custom_build($stage, $data)
  301. {
  302. return $data;
  303. }
  304. /**
  305. * Close sql connection
  306. *
  307. * @return bool False if failure
  308. */
  309. protected function _sql_close()
  310. {
  311. return $this->dbo->close();
  312. }
  313. /**
  314. * Build db-specific report
  315. *
  316. * @param string $mode Available modes: display, start, stop,
  317. * add_select_row, fromcache, record_fromcache
  318. * @param string $query The Query that should be explained
  319. * @return mixed Either a full HTML page, boolean or null
  320. */
  321. protected function _sql_report($mode, $query = '')
  322. {
  323. switch ($mode)
  324. {
  325. case 'start':
  326. $explain_query = $query;
  327. if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
  328. {
  329. $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
  330. }
  331. else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
  332. {
  333. $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
  334. }
  335. if (preg_match('/^SELECT/', $explain_query))
  336. {
  337. $html_table = false;
  338. if ($result = $this->dbo->query("EXPLAIN QUERY PLAN $explain_query"))
  339. {
  340. while ($row = $result->fetchArray(SQLITE3_ASSOC))
  341. {
  342. $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
  343. }
  344. }
  345. if ($html_table)
  346. {
  347. $this->html_hold .= '</table>';
  348. }
  349. }
  350. break;
  351. case 'fromcache':
  352. $endtime = explode(' ', microtime());
  353. $endtime = $endtime[0] + $endtime[1];
  354. $result = $this->dbo->query($query);
  355. if ($result)
  356. {
  357. while ($void = $result->fetchArray(SQLITE3_ASSOC))
  358. {
  359. // Take the time spent on parsing rows into account
  360. }
  361. }
  362. $splittime = explode(' ', microtime());
  363. $splittime = $splittime[0] + $splittime[1];
  364. $this->sql_report('record_fromcache', $query, $endtime, $splittime);
  365. break;
  366. }
  367. }
  368. }