3 namespace Drupal\Core\Database\Driver\sqlite;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\DatabaseNotFoundException;
7 use Drupal\Core\Database\Connection as DatabaseConnection;
10 * SQLite implementation of \Drupal\Core\Database\Connection.
12 class Connection extends DatabaseConnection {
15 * Error code for "Unable to open database file" error.
17 const DATABASE_NOT_FOUND = 14;
20 * Whether or not the active transaction (if any) will be rolled back.
24 protected $willRollback;
27 * A map of condition operators to SQLite operators.
29 * We don't want to override any of the defaults.
31 protected static $sqliteConditionOperatorMap = [
32 'LIKE' => ['postfix' => " ESCAPE '\\'"],
33 'NOT LIKE' => ['postfix' => " ESCAPE '\\'"],
34 'LIKE BINARY' => ['postfix' => " ESCAPE '\\'", 'operator' => 'GLOB'],
35 'NOT LIKE BINARY' => ['postfix' => " ESCAPE '\\'", 'operator' => 'NOT GLOB'],
39 * All databases attached to the current database. This is used to allow
40 * prefixes to be safely handled without locking the table
44 protected $attachedDatabases = [];
47 * Whether or not a table has been dropped this request: the destructor will
48 * only try to get rid of unnecessary databases if there is potential of them
51 * This variable is set to public because Schema needs to
52 * access it. However, it should not be manually set.
56 public $tableDropped = FALSE;
59 * Constructs a \Drupal\Core\Database\Driver\sqlite\Connection object.
61 public function __construct(\PDO $connection, array $connection_options) {
62 // We don't need a specific PDOStatement class here, we simulate it in
64 $this->statementClass = NULL;
66 parent::__construct($connection, $connection_options);
68 // This driver defaults to transaction support, except if explicitly passed FALSE.
69 $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
71 $this->connectionOptions = $connection_options;
73 // Attach one database for each registered prefix.
74 $prefixes = $this->prefixes;
75 foreach ($prefixes as &$prefix) {
76 // Empty prefix means query the main database -- no need to attach anything.
77 if (!empty($prefix)) {
78 // Only attach the database once.
79 if (!isset($this->attachedDatabases[$prefix])) {
80 $this->attachedDatabases[$prefix] = $prefix;
81 if ($connection_options['database'] === ':memory:') {
82 // In memory database use ':memory:' as database name. According to
83 // http://www.sqlite.org/inmemorydb.html it will open a unique
84 // database so attaching it twice is not a problem.
85 $this->query('ATTACH DATABASE :database AS :prefix', [':database' => $connection_options['database'], ':prefix' => $prefix]);
88 $this->query('ATTACH DATABASE :database AS :prefix', [':database' => $connection_options['database'] . '-' . $prefix, ':prefix' => $prefix]);
92 // Add a ., so queries become prefix.table, which is proper syntax for
93 // querying an attached database.
97 // Regenerate the prefixes replacement table.
98 $this->setPrefix($prefixes);
104 public static function open(array &$connection_options = []) {
105 // Allow PDO options to be overridden.
106 $connection_options += [
109 $connection_options['pdo'] += [
110 \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
111 // Convert numeric values to strings when fetching.
112 \PDO::ATTR_STRINGIFY_FETCHES => TRUE,
116 $pdo = new \PDO('sqlite:' . $connection_options['database'], '', '', $connection_options['pdo']);
118 catch (\PDOException $e) {
119 if ($e->getCode() == static::DATABASE_NOT_FOUND) {
120 throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
122 // SQLite doesn't have a distinct error code for access denied, so don't
123 // deal with that case.
127 // Create functions needed by SQLite.
128 $pdo->sqliteCreateFunction('if', [__CLASS__, 'sqlFunctionIf']);
129 $pdo->sqliteCreateFunction('greatest', [__CLASS__, 'sqlFunctionGreatest']);
130 $pdo->sqliteCreateFunction('pow', 'pow', 2);
131 $pdo->sqliteCreateFunction('exp', 'exp', 1);
132 $pdo->sqliteCreateFunction('length', 'strlen', 1);
133 $pdo->sqliteCreateFunction('md5', 'md5', 1);
134 $pdo->sqliteCreateFunction('concat', [__CLASS__, 'sqlFunctionConcat']);
135 $pdo->sqliteCreateFunction('concat_ws', [__CLASS__, 'sqlFunctionConcatWs']);
136 $pdo->sqliteCreateFunction('substring', [__CLASS__, 'sqlFunctionSubstring'], 3);
137 $pdo->sqliteCreateFunction('substring_index', [__CLASS__, 'sqlFunctionSubstringIndex'], 3);
138 $pdo->sqliteCreateFunction('rand', [__CLASS__, 'sqlFunctionRand']);
139 $pdo->sqliteCreateFunction('regexp', [__CLASS__, 'sqlFunctionRegexp']);
141 // SQLite does not support the LIKE BINARY operator, so we overload the
142 // non-standard GLOB operator for case-sensitive matching. Another option
143 // would have been to override another non-standard operator, MATCH, but
144 // that does not support the NOT keyword prefix.
145 $pdo->sqliteCreateFunction('glob', [__CLASS__, 'sqlFunctionLikeBinary']);
147 // Create a user-space case-insensitive collation with UTF-8 support.
148 $pdo->sqliteCreateCollation('NOCASE_UTF8', ['Drupal\Component\Utility\Unicode', 'strcasecmp']);
150 // Set SQLite init_commands if not already defined. Enable the Write-Ahead
151 // Logging (WAL) for SQLite. See https://www.drupal.org/node/2348137 and
152 // https://www.sqlite.org/wal.html.
153 $connection_options += [
154 'init_commands' => [],
156 $connection_options['init_commands'] += [
157 'wal' => "PRAGMA journal_mode=WAL",
160 // Execute sqlite init_commands.
161 if (isset($connection_options['init_commands'])) {
162 $pdo->exec(implode('; ', $connection_options['init_commands']));
170 * Destructor for the SQLite connection.
172 * We prune empty databases on destruct, but only if tables have been
173 * dropped. This is especially needed when running the test suite, which
174 * creates and destroy databases several times in a row.
176 public function __destruct() {
177 if ($this->tableDropped && !empty($this->attachedDatabases)) {
178 foreach ($this->attachedDatabases as $prefix) {
179 // Check if the database is now empty, ignore the internal SQLite tables.
181 $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [':type' => 'table', ':pattern' => 'sqlite_%'])->fetchField();
183 // We can prune the database file if it doesn't have any tables.
185 // Detaching the database fails at this point, but no other queries
186 // are executed after the connection is destructed so we can simply
187 // remove the database file.
188 unlink($this->connectionOptions['database'] . '-' . $prefix);
191 catch (\Exception $e) {
192 // Ignore the exception and continue. There is nothing we can do here
193 // to report the error or fail safe.
200 * Gets all the attached databases.
203 * An array of attached database names.
205 * @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
207 public function getAttachedDatabases() {
208 return $this->attachedDatabases;
212 * SQLite compatibility implementation for the IF() SQL function.
214 public static function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
215 return $condition ? $expr1 : $expr2;
219 * SQLite compatibility implementation for the GREATEST() SQL function.
221 public static function sqlFunctionGreatest() {
222 $args = func_get_args();
223 foreach ($args as $v) {
237 * SQLite compatibility implementation for the CONCAT() SQL function.
239 public static function sqlFunctionConcat() {
240 $args = func_get_args();
241 return implode('', $args);
245 * SQLite compatibility implementation for the CONCAT_WS() SQL function.
247 * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
249 public static function sqlFunctionConcatWs() {
250 $args = func_get_args();
251 $separator = array_shift($args);
252 // If the separator is NULL, the result is NULL.
253 if ($separator === FALSE || is_null($separator)) {
256 // Skip any NULL values after the separator argument.
257 $args = array_filter($args, function ($value) {
258 return !is_null($value);
260 return implode($separator, $args);
264 * SQLite compatibility implementation for the SUBSTRING() SQL function.
266 public static function sqlFunctionSubstring($string, $from, $length) {
267 return substr($string, $from - 1, $length);
271 * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
273 public static function sqlFunctionSubstringIndex($string, $delimiter, $count) {
274 // If string is empty, simply return an empty string.
275 if (empty($string)) {
279 for ($i = 0; $i < $count; $i++) {
280 $end = strpos($string, $delimiter, $end + 1);
281 if ($end === FALSE) {
282 $end = strlen($string);
285 return substr($string, 0, $end);
289 * SQLite compatibility implementation for the RAND() SQL function.
291 public static function sqlFunctionRand($seed = NULL) {
295 return mt_rand() / mt_getrandmax();
299 * SQLite compatibility implementation for the REGEXP SQL operator.
301 * The REGEXP operator is natively known, but not implemented by default.
303 * @see http://www.sqlite.org/lang_expr.html#regexp
305 public static function sqlFunctionRegexp($pattern, $subject) {
306 // preg_quote() cannot be used here, since $pattern may contain reserved
307 // regular expression characters already (such as ^, $, etc). Therefore,
308 // use a rare character as PCRE delimiter.
309 $pattern = '#' . addcslashes($pattern, '#') . '#i';
310 return preg_match($pattern, $subject);
314 * SQLite compatibility implementation for the LIKE BINARY SQL operator.
316 * SQLite supports case-sensitive LIKE operations through the
317 * 'case_sensitive_like' PRAGMA statement, but only for ASCII characters, so
318 * we have to provide our own implementation with UTF-8 support.
320 * @see https://sqlite.org/pragma.html#pragma_case_sensitive_like
321 * @see https://sqlite.org/lang_expr.html#like
323 public static function sqlFunctionLikeBinary($pattern, $subject) {
324 // Replace the SQL LIKE wildcard meta-characters with the equivalent regular
325 // expression meta-characters and escape the delimiter that will be used for
327 $pattern = str_replace(['%', '_'], ['.*?', '.'], preg_quote($pattern, '/'));
328 return preg_match('/^' . $pattern . '$/', $subject);
334 public function prepare($statement, array $driver_options = []) {
335 return new Statement($this->connection, $this, $statement, $driver_options);
341 protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
342 // The database schema might be changed by another process in between the
343 // time that the statement was prepared and the time the statement was run
344 // (e.g. usually happens when running tests). In this case, we need to
346 // @see http://www.sqlite.org/faq.html#q15
347 // @see http://www.sqlite.org/rescode.html#schema
348 if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
349 return $this->query($query, $args, $options);
352 parent::handleQueryException($e, $query, $args, $options);
355 public function queryRange($query, $from, $count, array $args = [], array $options = []) {
356 return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
359 public function queryTemporary($query, array $args = [], array $options = []) {
360 // Generate a new temporary table name and protect it from prefixing.
361 // SQLite requires that temporary tables to be non-qualified.
362 $tablename = $this->generateTemporaryTableName();
363 $prefixes = $this->prefixes;
364 $prefixes[$tablename] = '';
365 $this->setPrefix($prefixes);
367 $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
371 public function driver() {
375 public function databaseType() {
380 * Overrides \Drupal\Core\Database\Connection::createDatabase().
382 * @param string $database
383 * The name of the database to create.
385 * @throws \Drupal\Core\Database\DatabaseNotFoundException
387 public function createDatabase($database) {
388 // Verify the database is writable.
389 $db_directory = new \SplFileInfo(dirname($database));
390 if (!$db_directory->isDir() && !drupal_mkdir($db_directory->getPathName(), 0755, TRUE)) {
391 throw new DatabaseNotFoundException('Unable to create database directory ' . $db_directory->getPathName());
395 public function mapConditionOperator($operator) {
396 return isset(static::$sqliteConditionOperatorMap[$operator]) ? static::$sqliteConditionOperatorMap[$operator] : NULL;
402 public function prepareQuery($query) {
403 return $this->prepare($this->prefixTables($query));
406 public function nextId($existing_id = 0) {
407 $this->startTransaction();
408 // We can safely use literal queries here instead of the slower query
409 // builder because if a given database breaks here then it can simply
410 // override nextId. However, this is unlikely as we deal with short strings
411 // and integers and no known databases require special handling for those
412 // simple cases. If another transaction wants to write the same row, it will
413 // wait until this transaction commits. Also, the return value needs to be
414 // set to RETURN_AFFECTED as if it were a real update() query otherwise it
415 // is not possible to get the row count properly.
416 $affected = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', [
417 ':existing_id' => $existing_id,
418 ], ['return' => Database::RETURN_AFFECTED]);
420 $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', [
421 ':existing_id' => $existing_id,
424 // The transaction gets committed when the transaction object gets destroyed
425 // because it gets out of scope.
426 return $this->query('SELECT value FROM {sequences}')->fetchField();
432 public function getFullQualifiedTableName($table) {
433 $prefix = $this->tablePrefix($table);
435 // Don't include the SQLite database file name as part of the table name.
436 return $prefix . $table;