database.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. /**
  3. * @file
  4. * Database interface code for SQLite embedded database engine.
  5. */
  6. /**
  7. * @addtogroup database
  8. * @{
  9. */
  10. include_once DRUPAL_ROOT . '/includes/database/prefetch.inc';
  11. /**
  12. * Specific SQLite implementation of DatabaseConnection.
  13. */
  14. class DatabaseConnection_sqlite extends DatabaseConnection {
  15. /**
  16. * Whether this database connection supports savepoints.
  17. *
  18. * Version of sqlite lower then 3.6.8 can't use savepoints.
  19. * See http://www.sqlite.org/releaselog/3_6_8.html
  20. *
  21. * @var boolean
  22. */
  23. protected $savepointSupport = FALSE;
  24. /**
  25. * Whether or not the active transaction (if any) will be rolled back.
  26. *
  27. * @var boolean
  28. */
  29. protected $willRollback;
  30. /**
  31. * All databases attached to the current database. This is used to allow
  32. * prefixes to be safely handled without locking the table
  33. *
  34. * @var array
  35. */
  36. protected $attachedDatabases = array();
  37. /**
  38. * Whether or not a table has been dropped this request: the destructor will
  39. * only try to get rid of unnecessary databases if there is potential of them
  40. * being empty.
  41. *
  42. * This variable is set to public because DatabaseSchema_sqlite needs to
  43. * access it. However, it should not be manually set.
  44. *
  45. * @var boolean
  46. */
  47. var $tableDropped = FALSE;
  48. public function __construct(array $connection_options = array()) {
  49. // We don't need a specific PDOStatement class here, we simulate it below.
  50. $this->statementClass = NULL;
  51. // This driver defaults to transaction support, except if explicitly passed FALSE.
  52. $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
  53. $this->connectionOptions = $connection_options;
  54. // Allow PDO options to be overridden.
  55. $connection_options += array(
  56. 'pdo' => array(),
  57. );
  58. $connection_options['pdo'] += array(
  59. // Convert numeric values to strings when fetching.
  60. PDO::ATTR_STRINGIFY_FETCHES => TRUE,
  61. );
  62. parent::__construct('sqlite:' . $connection_options['database'], '', '', $connection_options['pdo']);
  63. // Attach one database for each registered prefix.
  64. $prefixes = $this->prefixes;
  65. foreach ($prefixes as $table => &$prefix) {
  66. // Empty prefix means query the main database -- no need to attach anything.
  67. if (!empty($prefix)) {
  68. // Only attach the database once.
  69. if (!isset($this->attachedDatabases[$prefix])) {
  70. $this->attachedDatabases[$prefix] = $prefix;
  71. $this->query('ATTACH DATABASE :database AS :prefix', array(':database' => $connection_options['database'] . '-' . $prefix, ':prefix' => $prefix));
  72. }
  73. // Add a ., so queries become prefix.table, which is proper syntax for
  74. // querying an attached database.
  75. $prefix .= '.';
  76. }
  77. }
  78. // Regenerate the prefixes replacement table.
  79. $this->setPrefix($prefixes);
  80. // Detect support for SAVEPOINT.
  81. $version = $this->query('SELECT sqlite_version()')->fetchField();
  82. $this->savepointSupport = (version_compare($version, '3.6.8') >= 0);
  83. // Create functions needed by SQLite.
  84. $this->sqliteCreateFunction('if', array($this, 'sqlFunctionIf'));
  85. $this->sqliteCreateFunction('greatest', array($this, 'sqlFunctionGreatest'));
  86. $this->sqliteCreateFunction('pow', 'pow', 2);
  87. $this->sqliteCreateFunction('length', 'strlen', 1);
  88. $this->sqliteCreateFunction('md5', 'md5', 1);
  89. $this->sqliteCreateFunction('concat', array($this, 'sqlFunctionConcat'));
  90. $this->sqliteCreateFunction('substring', array($this, 'sqlFunctionSubstring'), 3);
  91. $this->sqliteCreateFunction('substring_index', array($this, 'sqlFunctionSubstringIndex'), 3);
  92. $this->sqliteCreateFunction('rand', array($this, 'sqlFunctionRand'));
  93. // Execute sqlite init_commands.
  94. if (isset($connection_options['init_commands'])) {
  95. $this->exec(implode('; ', $connection_options['init_commands']));
  96. }
  97. }
  98. /**
  99. * Destructor for the SQLite connection.
  100. *
  101. * We prune empty databases on destruct, but only if tables have been
  102. * dropped. This is especially needed when running the test suite, which
  103. * creates and destroy databases several times in a row.
  104. */
  105. public function __destruct() {
  106. if ($this->tableDropped && !empty($this->attachedDatabases)) {
  107. foreach ($this->attachedDatabases as $prefix) {
  108. // Check if the database is now empty, ignore the internal SQLite tables.
  109. try {
  110. $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', array(':type' => 'table', ':pattern' => 'sqlite_%'))->fetchField();
  111. // We can prune the database file if it doesn't have any tables.
  112. if ($count == 0) {
  113. // Detach the database.
  114. $this->query('DETACH DATABASE :schema', array(':schema' => $prefix));
  115. // Destroy the database file.
  116. unlink($this->connectionOptions['database'] . '-' . $prefix);
  117. }
  118. }
  119. catch (Exception $e) {
  120. // Ignore the exception and continue. There is nothing we can do here
  121. // to report the error or fail safe.
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * SQLite compatibility implementation for the IF() SQL function.
  128. */
  129. public function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
  130. return $condition ? $expr1 : $expr2;
  131. }
  132. /**
  133. * SQLite compatibility implementation for the GREATEST() SQL function.
  134. */
  135. public function sqlFunctionGreatest() {
  136. $args = func_get_args();
  137. foreach ($args as $k => $v) {
  138. if (!isset($v)) {
  139. unset($args);
  140. }
  141. }
  142. if (count($args)) {
  143. return max($args);
  144. }
  145. else {
  146. return NULL;
  147. }
  148. }
  149. /**
  150. * SQLite compatibility implementation for the CONCAT() SQL function.
  151. */
  152. public function sqlFunctionConcat() {
  153. $args = func_get_args();
  154. return implode('', $args);
  155. }
  156. /**
  157. * SQLite compatibility implementation for the SUBSTRING() SQL function.
  158. */
  159. public function sqlFunctionSubstring($string, $from, $length) {
  160. return substr($string, $from - 1, $length);
  161. }
  162. /**
  163. * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
  164. */
  165. public function sqlFunctionSubstringIndex($string, $delimiter, $count) {
  166. // If string is empty, simply return an empty string.
  167. if (empty($string)) {
  168. return '';
  169. }
  170. $end = 0;
  171. for ($i = 0; $i < $count; $i++) {
  172. $end = strpos($string, $delimiter, $end + 1);
  173. if ($end === FALSE) {
  174. $end = strlen($string);
  175. }
  176. }
  177. return substr($string, 0, $end);
  178. }
  179. /**
  180. * SQLite compatibility implementation for the RAND() SQL function.
  181. */
  182. public function sqlFunctionRand($seed = NULL) {
  183. if (isset($seed)) {
  184. mt_srand($seed);
  185. }
  186. return mt_rand() / mt_getrandmax();
  187. }
  188. /**
  189. * SQLite-specific implementation of DatabaseConnection::prepare().
  190. *
  191. * We don't use prepared statements at all at this stage. We just create
  192. * a DatabaseStatement_sqlite object, that will create a PDOStatement
  193. * using the semi-private PDOPrepare() method below.
  194. */
  195. public function prepare($query, $options = array()) {
  196. return new DatabaseStatement_sqlite($this, $query, $options);
  197. }
  198. /**
  199. * NEVER CALL THIS FUNCTION: YOU MIGHT DEADLOCK YOUR PHP PROCESS.
  200. *
  201. * This is a wrapper around the parent PDO::prepare method. However, as
  202. * the PDO SQLite driver only closes SELECT statements when the PDOStatement
  203. * destructor is called and SQLite does not allow data change (INSERT,
  204. * UPDATE etc) on a table which has open SELECT statements, you should never
  205. * call this function and keep a PDOStatement object alive as that can lead
  206. * to a deadlock. This really, really should be private, but as
  207. * DatabaseStatement_sqlite needs to call it, we have no other choice but to
  208. * expose this function to the world.
  209. */
  210. public function PDOPrepare($query, array $options = array()) {
  211. return parent::prepare($query, $options);
  212. }
  213. public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
  214. return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
  215. }
  216. public function queryTemporary($query, array $args = array(), array $options = array()) {
  217. // Generate a new temporary table name and protect it from prefixing.
  218. // SQLite requires that temporary tables to be non-qualified.
  219. $tablename = $this->generateTemporaryTableName();
  220. $prefixes = $this->prefixes;
  221. $prefixes[$tablename] = '';
  222. $this->setPrefix($prefixes);
  223. $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
  224. return $tablename;
  225. }
  226. public function driver() {
  227. return 'sqlite';
  228. }
  229. public function databaseType() {
  230. return 'sqlite';
  231. }
  232. public function mapConditionOperator($operator) {
  233. // We don't want to override any of the defaults.
  234. static $specials = array(
  235. 'LIKE' => array('postfix' => " ESCAPE '\\'"),
  236. 'NOT LIKE' => array('postfix' => " ESCAPE '\\'"),
  237. );
  238. return isset($specials[$operator]) ? $specials[$operator] : NULL;
  239. }
  240. public function prepareQuery($query) {
  241. return $this->prepare($this->prefixTables($query));
  242. }
  243. public function nextId($existing_id = 0) {
  244. $transaction = $this->startTransaction();
  245. // We can safely use literal queries here instead of the slower query
  246. // builder because if a given database breaks here then it can simply
  247. // override nextId. However, this is unlikely as we deal with short strings
  248. // and integers and no known databases require special handling for those
  249. // simple cases. If another transaction wants to write the same row, it will
  250. // wait until this transaction commits.
  251. $stmt = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', array(
  252. ':existing_id' => $existing_id,
  253. ));
  254. if (!$stmt->rowCount()) {
  255. $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', array(
  256. ':existing_id' => $existing_id,
  257. ));
  258. }
  259. // The transaction gets committed when the transaction object gets destroyed
  260. // because it gets out of scope.
  261. return $this->query('SELECT value FROM {sequences}')->fetchField();
  262. }
  263. public function rollback($savepoint_name = 'drupal_transaction') {
  264. if ($this->savepointSupport) {
  265. return parent::rollBack($savepoint_name);
  266. }
  267. if (!$this->inTransaction()) {
  268. throw new DatabaseTransactionNoActiveException();
  269. }
  270. // A previous rollback to an earlier savepoint may mean that the savepoint
  271. // in question has already been rolled back.
  272. if (!in_array($savepoint_name, $this->transactionLayers)) {
  273. return;
  274. }
  275. // We need to find the point we're rolling back to, all other savepoints
  276. // before are no longer needed.
  277. while ($savepoint = array_pop($this->transactionLayers)) {
  278. if ($savepoint == $savepoint_name) {
  279. // Mark whole stack of transactions as needed roll back.
  280. $this->willRollback = TRUE;
  281. // If it is the last the transaction in the stack, then it is not a
  282. // savepoint, it is the transaction itself so we will need to roll back
  283. // the transaction rather than a savepoint.
  284. if (empty($this->transactionLayers)) {
  285. break;
  286. }
  287. return;
  288. }
  289. }
  290. if ($this->supportsTransactions()) {
  291. PDO::rollBack();
  292. }
  293. }
  294. public function pushTransaction($name) {
  295. if ($this->savepointSupport) {
  296. return parent::pushTransaction($name);
  297. }
  298. if (!$this->supportsTransactions()) {
  299. return;
  300. }
  301. if (isset($this->transactionLayers[$name])) {
  302. throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
  303. }
  304. if (!$this->inTransaction()) {
  305. PDO::beginTransaction();
  306. }
  307. $this->transactionLayers[$name] = $name;
  308. }
  309. public function popTransaction($name) {
  310. if ($this->savepointSupport) {
  311. return parent::popTransaction($name);
  312. }
  313. if (!$this->supportsTransactions()) {
  314. return;
  315. }
  316. if (!$this->inTransaction()) {
  317. throw new DatabaseTransactionNoActiveException();
  318. }
  319. // Commit everything since SAVEPOINT $name.
  320. while($savepoint = array_pop($this->transactionLayers)) {
  321. if ($savepoint != $name) continue;
  322. // If there are no more layers left then we should commit or rollback.
  323. if (empty($this->transactionLayers)) {
  324. // If there was any rollback() we should roll back whole transaction.
  325. if ($this->willRollback) {
  326. $this->willRollback = FALSE;
  327. PDO::rollBack();
  328. }
  329. elseif (!PDO::commit()) {
  330. throw new DatabaseTransactionCommitFailedException();
  331. }
  332. }
  333. else {
  334. break;
  335. }
  336. }
  337. }
  338. public function utf8mb4IsActive() {
  339. return TRUE;
  340. }
  341. public function utf8mb4IsSupported() {
  342. return TRUE;
  343. }
  344. }
  345. /**
  346. * Specific SQLite implementation of DatabaseConnection.
  347. *
  348. * See DatabaseConnection_sqlite::PDOPrepare() for reasons why we must prefetch
  349. * the data instead of using PDOStatement.
  350. *
  351. * @see DatabaseConnection_sqlite::PDOPrepare()
  352. */
  353. class DatabaseStatement_sqlite extends DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
  354. /**
  355. * SQLite specific implementation of getStatement().
  356. *
  357. * The PDO SQLite layer doesn't replace numeric placeholders in queries
  358. * correctly, and this makes numeric expressions (such as COUNT(*) >= :count)
  359. * fail. We replace numeric placeholders in the query ourselves to work
  360. * around this bug.
  361. *
  362. * See http://bugs.php.net/bug.php?id=45259 for more details.
  363. */
  364. protected function getStatement($query, &$args = array()) {
  365. if (count($args)) {
  366. // Check if $args is a simple numeric array.
  367. if (range(0, count($args) - 1) === array_keys($args)) {
  368. // In that case, we have unnamed placeholders.
  369. $count = 0;
  370. $new_args = array();
  371. foreach ($args as $value) {
  372. if (is_float($value) || is_int($value)) {
  373. if (is_float($value)) {
  374. // Force the conversion to float so as not to loose precision
  375. // in the automatic cast.
  376. $value = sprintf('%F', $value);
  377. }
  378. $query = substr_replace($query, $value, strpos($query, '?'), 1);
  379. }
  380. else {
  381. $placeholder = ':db_statement_placeholder_' . $count++;
  382. $query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
  383. $new_args[$placeholder] = $value;
  384. }
  385. }
  386. $args = $new_args;
  387. }
  388. else {
  389. // Else, this is using named placeholders.
  390. foreach ($args as $placeholder => $value) {
  391. if (is_float($value) || is_int($value)) {
  392. if (is_float($value)) {
  393. // Force the conversion to float so as not to loose precision
  394. // in the automatic cast.
  395. $value = sprintf('%F', $value);
  396. }
  397. // We will remove this placeholder from the query as PDO throws an
  398. // exception if the number of placeholders in the query and the
  399. // arguments does not match.
  400. unset($args[$placeholder]);
  401. // PDO allows placeholders to not be prefixed by a colon. See
  402. // http://marc.info/?l=php-internals&m=111234321827149&w=2 for
  403. // more.
  404. if ($placeholder[0] != ':') {
  405. $placeholder = ":$placeholder";
  406. }
  407. // When replacing the placeholders, make sure we search for the
  408. // exact placeholder. For example, if searching for
  409. // ':db_placeholder_1', do not replace ':db_placeholder_11'.
  410. $query = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $query);
  411. }
  412. }
  413. }
  414. }
  415. return $this->dbh->PDOPrepare($query);
  416. }
  417. public function execute($args = array(), $options = array()) {
  418. try {
  419. $return = parent::execute($args, $options);
  420. }
  421. catch (PDOException $e) {
  422. if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
  423. // The schema has changed. SQLite specifies that we must resend the query.
  424. $return = parent::execute($args, $options);
  425. }
  426. else {
  427. // Rethrow the exception.
  428. throw $e;
  429. }
  430. }
  431. // In some weird cases, SQLite will prefix some column names by the name
  432. // of the table. We post-process the data, by renaming the column names
  433. // using the same convention as MySQL and PostgreSQL.
  434. $rename_columns = array();
  435. foreach ($this->columnNames as $k => $column) {
  436. // In some SQLite versions, SELECT DISTINCT(field) will return "(field)"
  437. // instead of "field".
  438. if (preg_match("/^\((.*)\)$/", $column, $matches)) {
  439. $rename_columns[$column] = $matches[1];
  440. $this->columnNames[$k] = $matches[1];
  441. $column = $matches[1];
  442. }
  443. // Remove "table." prefixes.
  444. if (preg_match("/^.*\.(.*)$/", $column, $matches)) {
  445. $rename_columns[$column] = $matches[1];
  446. $this->columnNames[$k] = $matches[1];
  447. }
  448. }
  449. if ($rename_columns) {
  450. // DatabaseStatementPrefetch already extracted the first row,
  451. // put it back into the result set.
  452. if (isset($this->currentRow)) {
  453. $this->data[0] = &$this->currentRow;
  454. }
  455. // Then rename all the columns across the result set.
  456. foreach ($this->data as $k => $row) {
  457. foreach ($rename_columns as $old_column => $new_column) {
  458. $this->data[$k][$new_column] = $this->data[$k][$old_column];
  459. unset($this->data[$k][$old_column]);
  460. }
  461. }
  462. // Finally, extract the first row again.
  463. $this->currentRow = $this->data[0];
  464. unset($this->data[0]);
  465. }
  466. return $return;
  467. }
  468. }
  469. /**
  470. * @} End of "addtogroup database".
  471. */