Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / sqlite / Connection.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\sqlite;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\DatabaseNotFoundException;
7 use Drupal\Core\Database\Connection as DatabaseConnection;
8
9 /**
10  * SQLite implementation of \Drupal\Core\Database\Connection.
11  */
12 class Connection extends DatabaseConnection {
13
14   /**
15    * Error code for "Unable to open database file" error.
16    */
17   const DATABASE_NOT_FOUND = 14;
18
19   /**
20    * Whether or not the active transaction (if any) will be rolled back.
21    *
22    * @var bool
23    */
24   protected $willRollback;
25
26   /**
27    * A map of condition operators to SQLite operators.
28    *
29    * We don't want to override any of the defaults.
30    */
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'],
36   ];
37
38   /**
39    * All databases attached to the current database. This is used to allow
40    * prefixes to be safely handled without locking the table
41    *
42    * @var array
43    */
44   protected $attachedDatabases = [];
45
46   /**
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
49    * being empty.
50    *
51    * This variable is set to public because Schema needs to
52    * access it. However, it should not be manually set.
53    *
54    * @var bool
55    */
56   public $tableDropped = FALSE;
57
58   /**
59    * Constructs a \Drupal\Core\Database\Driver\sqlite\Connection object.
60    */
61   public function __construct(\PDO $connection, array $connection_options) {
62     // We don't need a specific PDOStatement class here, we simulate it in
63     // static::prepare().
64     $this->statementClass = NULL;
65
66     parent::__construct($connection, $connection_options);
67
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;
70
71     $this->connectionOptions = $connection_options;
72
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]);
86           }
87           else {
88             $this->query('ATTACH DATABASE :database AS :prefix', [':database' => $connection_options['database'] . '-' . $prefix, ':prefix' => $prefix]);
89           }
90         }
91
92         // Add a ., so queries become prefix.table, which is proper syntax for
93         // querying an attached database.
94         $prefix .= '.';
95       }
96     }
97     // Regenerate the prefixes replacement table.
98     $this->setPrefix($prefixes);
99   }
100
101   /**
102    * {@inheritdoc}
103    */
104   public static function open(array &$connection_options = []) {
105     // Allow PDO options to be overridden.
106     $connection_options += [
107       'pdo' => [],
108     ];
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,
113     ];
114
115     try {
116       $pdo = new \PDO('sqlite:' . $connection_options['database'], '', '', $connection_options['pdo']);
117     }
118     catch (\PDOException $e) {
119       if ($e->getCode() == static::DATABASE_NOT_FOUND) {
120         throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
121       }
122       // SQLite doesn't have a distinct error code for access denied, so don't
123       // deal with that case.
124       throw $e;
125     }
126
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']);
140
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']);
146
147     // Create a user-space case-insensitive collation with UTF-8 support.
148     $pdo->sqliteCreateCollation('NOCASE_UTF8', ['Drupal\Component\Utility\Unicode', 'strcasecmp']);
149
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' => [],
155     ];
156     $connection_options['init_commands'] += [
157       'wal' => "PRAGMA journal_mode=WAL",
158     ];
159
160     // Execute sqlite init_commands.
161     if (isset($connection_options['init_commands'])) {
162       $pdo->exec(implode('; ', $connection_options['init_commands']));
163     }
164
165     return $pdo;
166   }
167
168   /**
169    * Destructor for the SQLite connection.
170    *
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.
174    */
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.
179         try {
180           $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [':type' => 'table', ':pattern' => 'sqlite_%'])->fetchField();
181
182           // We can prune the database file if it doesn't have any tables.
183           if ($count == 0) {
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);
188           }
189         }
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.
193         }
194       }
195     }
196   }
197
198   /**
199    * Gets all the attached databases.
200    *
201    * @return array
202    *   An array of attached database names.
203    *
204    * @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
205    */
206   public function getAttachedDatabases() {
207     return $this->attachedDatabases;
208   }
209
210   /**
211    * SQLite compatibility implementation for the IF() SQL function.
212    */
213   public static function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
214     return $condition ? $expr1 : $expr2;
215   }
216
217   /**
218    * SQLite compatibility implementation for the GREATEST() SQL function.
219    */
220   public static function sqlFunctionGreatest() {
221     $args = func_get_args();
222     foreach ($args as $v) {
223       if (!isset($v)) {
224         unset($args);
225       }
226     }
227     if (count($args)) {
228       return max($args);
229     }
230     else {
231       return NULL;
232     }
233   }
234
235   /**
236    * SQLite compatibility implementation for the CONCAT() SQL function.
237    */
238   public static function sqlFunctionConcat() {
239     $args = func_get_args();
240     return implode('', $args);
241   }
242
243   /**
244    * SQLite compatibility implementation for the CONCAT_WS() SQL function.
245    *
246    * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
247    */
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)) {
253       return NULL;
254     }
255     // Skip any NULL values after the separator argument.
256     $args = array_filter($args, function ($value) {
257       return !is_null($value);
258     });
259     return implode($separator, $args);
260   }
261
262   /**
263    * SQLite compatibility implementation for the SUBSTRING() SQL function.
264    */
265   public static function sqlFunctionSubstring($string, $from, $length) {
266     return substr($string, $from - 1, $length);
267   }
268
269   /**
270    * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
271    */
272   public static function sqlFunctionSubstringIndex($string, $delimiter, $count) {
273     // If string is empty, simply return an empty string.
274     if (empty($string)) {
275       return '';
276     }
277     $end = 0;
278     for ($i = 0; $i < $count; $i++) {
279       $end = strpos($string, $delimiter, $end + 1);
280       if ($end === FALSE) {
281         $end = strlen($string);
282       }
283     }
284     return substr($string, 0, $end);
285   }
286
287   /**
288    * SQLite compatibility implementation for the RAND() SQL function.
289    */
290   public static function sqlFunctionRand($seed = NULL) {
291     if (isset($seed)) {
292       mt_srand($seed);
293     }
294     return mt_rand() / mt_getrandmax();
295   }
296
297   /**
298    * SQLite compatibility implementation for the REGEXP SQL operator.
299    *
300    * The REGEXP operator is natively known, but not implemented by default.
301    *
302    * @see http://www.sqlite.org/lang_expr.html#regexp
303    */
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);
310   }
311
312   /**
313    * SQLite compatibility implementation for the LIKE BINARY SQL operator.
314    *
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.
318    *
319    * @see https://sqlite.org/pragma.html#pragma_case_sensitive_like
320    * @see https://sqlite.org/lang_expr.html#like
321    */
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
325     // matching.
326     $pattern = str_replace(['%', '_'], ['.*?', '.'], preg_quote($pattern, '/'));
327     return preg_match('/^' . $pattern . '$/', $subject);
328   }
329
330   /**
331    * {@inheritdoc}
332    */
333   public function prepare($statement, array $driver_options = []) {
334     return new Statement($this->connection, $this, $statement, $driver_options);
335   }
336
337   /**
338    * {@inheritdoc}
339    */
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
344     // re-run the query.
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);
349     }
350
351     parent::handleQueryException($e, $query, $args, $options);
352   }
353
354   public function queryRange($query, $from, $count, array $args = [], array $options = []) {
355     return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
356   }
357
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);
365
366     $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
367     return $tablename;
368   }
369
370   public function driver() {
371     return 'sqlite';
372   }
373
374   public function databaseType() {
375     return 'sqlite';
376   }
377
378   /**
379    * Overrides \Drupal\Core\Database\Connection::createDatabase().
380    *
381    * @param string $database
382    *   The name of the database to create.
383    *
384    * @throws \Drupal\Core\Database\DatabaseNotFoundException
385    */
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());
391     }
392   }
393
394   public function mapConditionOperator($operator) {
395     return isset(static::$sqliteConditionOperatorMap[$operator]) ? static::$sqliteConditionOperatorMap[$operator] : NULL;
396   }
397
398   /**
399    * {@inheritdoc}
400    */
401   public function prepareQuery($query) {
402     return $this->prepare($this->prefixTables($query));
403   }
404
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]);
418     if (!$affected) {
419       $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', [
420         ':existing_id' => $existing_id,
421       ]);
422     }
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();
426   }
427
428   /**
429    * {@inheritdoc}
430    */
431   public function getFullQualifiedTableName($table) {
432     $prefix = $this->tablePrefix($table);
433
434     // Don't include the SQLite database file name as part of the table name.
435     return $prefix . $table;
436   }
437
438   /**
439    * {@inheritdoc}
440    */
441   public static function createConnectionOptionsFromUrl($url, $root) {
442     $database = parent::createConnectionOptionsFromUrl($url, $root);
443
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);
449     }
450     if ($url_components['path'][0] === '/') {
451       $database['database'] = $url_components['path'];
452     }
453     else {
454       $database['database'] = $root . '/' . $url_components['path'];
455     }
456
457     // User credentials and system port are irrelevant for SQLite.
458     unset(
459       $database['username'],
460       $database['password'],
461       $database['port']
462     );
463
464     return $database;
465   }
466
467   /**
468    * {@inheritdoc}
469    */
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");
473     }
474
475     $db_url = 'sqlite://localhost/' . $connection_options['database'];
476
477     if (isset($connection_options['prefix']['default']) && $connection_options['prefix']['default'] !== NULL && $connection_options['prefix']['default'] !== '') {
478       $db_url .= '#' . $connection_options['prefix']['default'];
479     }
480
481     return $db_url;
482   }
483
484 }