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']));
169 * Destructor for the SQLite connection.
171 * We prune empty databases on destruct, but only if tables have been
172 * dropped. This is especially needed when running the test suite, which
173 * creates and destroy databases several times in a row.
175 public function __destruct() {
176 if ($this->tableDropped && !empty($this->attachedDatabases)) {
177 foreach ($this->attachedDatabases as $prefix) {
178 // Check if the database is now empty, ignore the internal SQLite tables.
180 $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [':type' => 'table', ':pattern' => 'sqlite_%'])->fetchField();
182 // We can prune the database file if it doesn't have any tables.
184 // Detaching the database fails at this point, but no other queries
185 // are executed after the connection is destructed so we can simply
186 // remove the database file.
187 unlink($this->connectionOptions['database'] . '-' . $prefix);
190 catch (\Exception $e) {
191 // Ignore the exception and continue. There is nothing we can do here
192 // to report the error or fail safe.
199 * Gets all the attached databases.
202 * An array of attached database names.
204 * @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
206 public function getAttachedDatabases() {
207 return $this->attachedDatabases;
211 * SQLite compatibility implementation for the IF() SQL function.
213 public static function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
214 return $condition ? $expr1 : $expr2;
218 * SQLite compatibility implementation for the GREATEST() SQL function.
220 public static function sqlFunctionGreatest() {
221 $args = func_get_args();
222 foreach ($args as $v) {
236 * SQLite compatibility implementation for the CONCAT() SQL function.
238 public static function sqlFunctionConcat() {
239 $args = func_get_args();
240 return implode('', $args);
244 * SQLite compatibility implementation for the CONCAT_WS() SQL function.
246 * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
248 public static function sqlFunctionConcatWs() {
249 $args = func_get_args();
250 $separator = array_shift($args);
251 // If the separator is NULL, the result is NULL.
252 if ($separator === FALSE || is_null($separator)) {
255 // Skip any NULL values after the separator argument.
256 $args = array_filter($args, function ($value) {
257 return !is_null($value);
259 return implode($separator, $args);
263 * SQLite compatibility implementation for the SUBSTRING() SQL function.
265 public static function sqlFunctionSubstring($string, $from, $length) {
266 return substr($string, $from - 1, $length);
270 * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
272 public static function sqlFunctionSubstringIndex($string, $delimiter, $count) {
273 // If string is empty, simply return an empty string.
274 if (empty($string)) {
278 for ($i = 0; $i < $count; $i++) {
279 $end = strpos($string, $delimiter, $end + 1);
280 if ($end === FALSE) {
281 $end = strlen($string);
284 return substr($string, 0, $end);
288 * SQLite compatibility implementation for the RAND() SQL function.
290 public static function sqlFunctionRand($seed = NULL) {
294 return mt_rand() / mt_getrandmax();
298 * SQLite compatibility implementation for the REGEXP SQL operator.
300 * The REGEXP operator is natively known, but not implemented by default.
302 * @see http://www.sqlite.org/lang_expr.html#regexp
304 public static function sqlFunctionRegexp($pattern, $subject) {
305 // preg_quote() cannot be used here, since $pattern may contain reserved
306 // regular expression characters already (such as ^, $, etc). Therefore,
307 // use a rare character as PCRE delimiter.
308 $pattern = '#' . addcslashes($pattern, '#') . '#i';
309 return preg_match($pattern, $subject);
313 * SQLite compatibility implementation for the LIKE BINARY SQL operator.
315 * SQLite supports case-sensitive LIKE operations through the
316 * 'case_sensitive_like' PRAGMA statement, but only for ASCII characters, so
317 * we have to provide our own implementation with UTF-8 support.
319 * @see https://sqlite.org/pragma.html#pragma_case_sensitive_like
320 * @see https://sqlite.org/lang_expr.html#like
322 public static function sqlFunctionLikeBinary($pattern, $subject) {
323 // Replace the SQL LIKE wildcard meta-characters with the equivalent regular
324 // expression meta-characters and escape the delimiter that will be used for
326 $pattern = str_replace(['%', '_'], ['.*?', '.'], preg_quote($pattern, '/'));
327 return preg_match('/^' . $pattern . '$/', $subject);
333 public function prepare($statement, array $driver_options = []) {
334 return new Statement($this->connection, $this, $statement, $driver_options);
340 protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
341 // The database schema might be changed by another process in between the
342 // time that the statement was prepared and the time the statement was run
343 // (e.g. usually happens when running tests). In this case, we need to
345 // @see http://www.sqlite.org/faq.html#q15
346 // @see http://www.sqlite.org/rescode.html#schema
347 if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
348 return $this->query($query, $args, $options);
351 parent::handleQueryException($e, $query, $args, $options);
354 public function queryRange($query, $from, $count, array $args = [], array $options = []) {
355 return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
358 public function queryTemporary($query, array $args = [], array $options = []) {
359 // Generate a new temporary table name and protect it from prefixing.
360 // SQLite requires that temporary tables to be non-qualified.
361 $tablename = $this->generateTemporaryTableName();
362 $prefixes = $this->prefixes;
363 $prefixes[$tablename] = '';
364 $this->setPrefix($prefixes);
366 $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
370 public function driver() {
374 public function databaseType() {
379 * Overrides \Drupal\Core\Database\Connection::createDatabase().
381 * @param string $database
382 * The name of the database to create.
384 * @throws \Drupal\Core\Database\DatabaseNotFoundException
386 public function createDatabase($database) {
387 // Verify the database is writable.
388 $db_directory = new \SplFileInfo(dirname($database));
389 if (!$db_directory->isDir() && !drupal_mkdir($db_directory->getPathName(), 0755, TRUE)) {
390 throw new DatabaseNotFoundException('Unable to create database directory ' . $db_directory->getPathName());
394 public function mapConditionOperator($operator) {
395 return isset(static::$sqliteConditionOperatorMap[$operator]) ? static::$sqliteConditionOperatorMap[$operator] : NULL;
401 public function prepareQuery($query) {
402 return $this->prepare($this->prefixTables($query));
405 public function nextId($existing_id = 0) {
406 $this->startTransaction();
407 // We can safely use literal queries here instead of the slower query
408 // builder because if a given database breaks here then it can simply
409 // override nextId. However, this is unlikely as we deal with short strings
410 // and integers and no known databases require special handling for those
411 // simple cases. If another transaction wants to write the same row, it will
412 // wait until this transaction commits. Also, the return value needs to be
413 // set to RETURN_AFFECTED as if it were a real update() query otherwise it
414 // is not possible to get the row count properly.
415 $affected = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', [
416 ':existing_id' => $existing_id,
417 ], ['return' => Database::RETURN_AFFECTED]);
419 $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', [
420 ':existing_id' => $existing_id,
423 // The transaction gets committed when the transaction object gets destroyed
424 // because it gets out of scope.
425 return $this->query('SELECT value FROM {sequences}')->fetchField();
431 public function getFullQualifiedTableName($table) {
432 $prefix = $this->tablePrefix($table);
434 // Don't include the SQLite database file name as part of the table name.
435 return $prefix . $table;
441 public static function createConnectionOptionsFromUrl($url, $root) {
442 $database = parent::createConnectionOptionsFromUrl($url, $root);
444 // A SQLite database path with two leading slashes indicates a system path.
445 // Otherwise the path is relative to the Drupal root.
446 $url_components = parse_url($url);
447 if ($url_components['path'][0] === '/') {
448 $url_components['path'] = substr($url_components['path'], 1);
450 if ($url_components['path'][0] === '/') {
451 $database['database'] = $url_components['path'];
454 $database['database'] = $root . '/' . $url_components['path'];
457 // User credentials and system port are irrelevant for SQLite.
459 $database['username'],
460 $database['password'],
470 public static function createUrlFromConnectionOptions(array $connection_options) {
471 if (!isset($connection_options['driver'], $connection_options['database'])) {
472 throw new \InvalidArgumentException("As a minimum, the connection options array must contain at least the 'driver' and 'database' keys");
475 $db_url = 'sqlite://localhost/' . $connection_options['database'];
477 if (isset($connection_options['prefix']['default']) && $connection_options['prefix']['default'] !== NULL && $connection_options['prefix']['default'] !== '') {
478 $db_url .= '#' . $connection_options['prefix']['default'];