Skip navigation
Help

database.inc

  1. drupal
    1. 6 drupal/includes/database.inc
    2. 7 drupal/includes/database/database.inc
    3. 7 drupal/includes/database/mysql/database.inc
    4. 7 drupal/includes/database/sqlite/database.inc
    5. 7 drupal/includes/database/pgsql/database.inc

Database interface code for SQLite embedded database engine.

Classes

NameDescription
DatabaseConnection_sqliteSpecific SQLite implementation of DatabaseConnection.
DatabaseStatement_sqliteSpecific SQLite implementation of DatabaseConnection.

File

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