database.inc

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

Database interface code for SQLite embedded database engine.

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. * @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(preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' . $tablename . ' AS SELECT', $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. }
  339. /**
  340. * Specific SQLite implementation of DatabaseConnection.
  341. *
  342. * See DatabaseConnection_sqlite::PDOPrepare() for reasons why we must prefetch
  343. * the data instead of using PDOStatement.
  344. *
  345. * @see DatabaseConnection_sqlite::PDOPrepare()
  346. */
  347. class DatabaseStatement_sqlite extends DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
  348. /**
  349. * SQLite specific implementation of getStatement().
  350. *
  351. * The PDO SQLite layer doesn't replace numeric placeholders in queries
  352. * correctly, and this makes numeric expressions (such as COUNT(*) >= :count)
  353. * fail. We replace numeric placeholders in the query ourselves to work
  354. * around this bug.
  355. *
  356. * See http://bugs.php.net/bug.php?id=45259 for more details.
  357. */
  358. protected function getStatement($query, &$args = array()) {
  359. if (count($args)) {
  360. // Check if $args is a simple numeric array.
  361. if (range(0, count($args) - 1) === array_keys($args)) {
  362. // In that case, we have unnamed placeholders.
  363. $count = 0;
  364. $new_args = array();
  365. foreach ($args as $value) {
  366. if (is_float($value) || is_int($value)) {
  367. if (is_float($value)) {
  368. // Force the conversion to float so as not to loose precision
  369. // in the automatic cast.
  370. $value = sprintf('%F', $value);
  371. }
  372. $query = substr_replace($query, $value, strpos($query, '?'), 1);
  373. }
  374. else {
  375. $placeholder = ':db_statement_placeholder_' . $count++;
  376. $query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
  377. $new_args[$placeholder] = $value;
  378. }
  379. }
  380. $args = $new_args;
  381. }
  382. else {
  383. // Else, this is using named placeholders.
  384. foreach ($args as $placeholder => $value) {
  385. if (is_float($value) || is_int($value)) {
  386. if (is_float($value)) {
  387. // Force the conversion to float so as not to loose precision
  388. // in the automatic cast.
  389. $value = sprintf('%F', $value);
  390. }
  391. // We will remove this placeholder from the query as PDO throws an
  392. // exception if the number of placeholders in the query and the
  393. // arguments does not match.
  394. unset($args[$placeholder]);
  395. // PDO allows placeholders to not be prefixed by a colon. See
  396. // http://marc.info/?l=php-internals&m=111234321827149&w=2 for
  397. // more.
  398. if ($placeholder[0] != ':') {
  399. $placeholder = ":$placeholder";
  400. }
  401. // When replacing the placeholders, make sure we search for the
  402. // exact placeholder. For example, if searching for
  403. // ':db_placeholder_1', do not replace ':db_placeholder_11'.
  404. $query = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $query);
  405. }
  406. }
  407. }
  408. }
  409. return $this->dbh->PDOPrepare($query);
  410. }
  411. public function execute($args = array(), $options = array()) {
  412. try {
  413. $return = parent::execute($args, $options);
  414. }
  415. catch (PDOException $e) {
  416. if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
  417. // The schema has changed. SQLite specifies that we must resend the query.
  418. $return = parent::execute($args, $options);
  419. }
  420. else {
  421. // Rethrow the exception.
  422. throw $e;
  423. }
  424. }
  425. // In some weird cases, SQLite will prefix some column names by the name
  426. // of the table. We post-process the data, by renaming the column names
  427. // using the same convention as MySQL and PostgreSQL.
  428. $rename_columns = array();
  429. foreach ($this->columnNames as $k => $column) {
  430. // In some SQLite versions, SELECT DISTINCT(field) will return "(field)"
  431. // instead of "field".
  432. if (preg_match("/^\((.*)\)$/", $column, $matches)) {
  433. $rename_columns[$column] = $matches[1];
  434. $this->columnNames[$k] = $matches[1];
  435. $column = $matches[1];
  436. }
  437. // Remove "table." prefixes.
  438. if (preg_match("/^.*\.(.*)$/", $column, $matches)) {
  439. $rename_columns[$column] = $matches[1];
  440. $this->columnNames[$k] = $matches[1];
  441. }
  442. }
  443. if ($rename_columns) {
  444. // DatabaseStatementPrefetch already extracted the first row,
  445. // put it back into the result set.
  446. if (isset($this->currentRow)) {
  447. $this->data[0] = &$this->currentRow;
  448. }
  449. // Then rename all the columns across the result set.
  450. foreach ($this->data as $k => $row) {
  451. foreach ($rename_columns as $old_column => $new_column) {
  452. $this->data[$k][$new_column] = $this->data[$k][$old_column];
  453. unset($this->data[$k][$old_column]);
  454. }
  455. }
  456. // Finally, extract the first row again.
  457. $this->currentRow = $this->data[0];
  458. unset($this->data[0]);
  459. }
  460. return $return;
  461. }
  462. }
  463. /**
  464. * @} End of "addtogroup database".
  465. */

Classes

Namesort descending Description
DatabaseConnection_sqlite Specific SQLite implementation of DatabaseConnection.
DatabaseStatement_sqlite Specific SQLite implementation of DatabaseConnection.