a7c1496c7a8f64ecbdd95f24c4467e4f21d7c43e
[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   /**
170    * Destructor for the SQLite connection.
171    *
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.
175    */
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.
180         try {
181           $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [':type' => 'table', ':pattern' => 'sqlite_%'])->fetchField();
182
183           // We can prune the database file if it doesn't have any tables.
184           if ($count == 0) {
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);
189           }
190         }
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.
194         }
195       }
196     }
197   }
198
199   /**
200    * Gets all the attached databases.
201    *
202    * @return array
203    *   An array of attached database names.
204    *
205    * @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
206    */
207   public function getAttachedDatabases() {
208     return $this->attachedDatabases;
209   }
210
211   /**
212    * SQLite compatibility implementation for the IF() SQL function.
213    */
214   public static function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
215     return $condition ? $expr1 : $expr2;
216   }
217
218   /**
219    * SQLite compatibility implementation for the GREATEST() SQL function.
220    */
221   public static function sqlFunctionGreatest() {
222     $args = func_get_args();
223     foreach ($args as $v) {
224       if (!isset($v)) {
225         unset($args);
226       }
227     }
228     if (count($args)) {
229       return max($args);
230     }
231     else {
232       return NULL;
233     }
234   }
235
236   /**
237    * SQLite compatibility implementation for the CONCAT() SQL function.
238    */
239   public static function sqlFunctionConcat() {
240     $args = func_get_args();
241     return implode('', $args);
242   }
243
244   /**
245    * SQLite compatibility implementation for the CONCAT_WS() SQL function.
246    *
247    * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
248    */
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)) {
254       return NULL;
255     }
256     // Skip any NULL values after the separator argument.
257     $args = array_filter($args, function ($value) {
258       return !is_null($value);
259     });
260     return implode($separator, $args);
261   }
262
263   /**
264    * SQLite compatibility implementation for the SUBSTRING() SQL function.
265    */
266   public static function sqlFunctionSubstring($string, $from, $length) {
267     return substr($string, $from - 1, $length);
268   }
269
270   /**
271    * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
272    */
273   public static function sqlFunctionSubstringIndex($string, $delimiter, $count) {
274     // If string is empty, simply return an empty string.
275     if (empty($string)) {
276       return '';
277     }
278     $end = 0;
279     for ($i = 0; $i < $count; $i++) {
280       $end = strpos($string, $delimiter, $end + 1);
281       if ($end === FALSE) {
282         $end = strlen($string);
283       }
284     }
285     return substr($string, 0, $end);
286   }
287
288   /**
289    * SQLite compatibility implementation for the RAND() SQL function.
290    */
291   public static function sqlFunctionRand($seed = NULL) {
292     if (isset($seed)) {
293       mt_srand($seed);
294     }
295     return mt_rand() / mt_getrandmax();
296   }
297
298   /**
299    * SQLite compatibility implementation for the REGEXP SQL operator.
300    *
301    * The REGEXP operator is natively known, but not implemented by default.
302    *
303    * @see http://www.sqlite.org/lang_expr.html#regexp
304    */
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);
311   }
312
313   /**
314    * SQLite compatibility implementation for the LIKE BINARY SQL operator.
315    *
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.
319    *
320    * @see https://sqlite.org/pragma.html#pragma_case_sensitive_like
321    * @see https://sqlite.org/lang_expr.html#like
322    */
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
326     // matching.
327     $pattern = str_replace(['%', '_'], ['.*?', '.'], preg_quote($pattern, '/'));
328     return preg_match('/^' . $pattern . '$/', $subject);
329   }
330
331   /**
332    * {@inheritdoc}
333    */
334   public function prepare($statement, array $driver_options = []) {
335     return new Statement($this->connection, $this, $statement, $driver_options);
336   }
337
338   /**
339    * {@inheritdoc}
340    */
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
345     // re-run the query.
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);
350     }
351
352     parent::handleQueryException($e, $query, $args, $options);
353   }
354
355   public function queryRange($query, $from, $count, array $args = [], array $options = []) {
356     return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
357   }
358
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);
366
367     $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
368     return $tablename;
369   }
370
371   public function driver() {
372     return 'sqlite';
373   }
374
375   public function databaseType() {
376     return 'sqlite';
377   }
378
379   /**
380    * Overrides \Drupal\Core\Database\Connection::createDatabase().
381    *
382    * @param string $database
383    *   The name of the database to create.
384    *
385    * @throws \Drupal\Core\Database\DatabaseNotFoundException
386    */
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());
392     }
393   }
394
395   public function mapConditionOperator($operator) {
396     return isset(static::$sqliteConditionOperatorMap[$operator]) ? static::$sqliteConditionOperatorMap[$operator] : NULL;
397   }
398
399   /**
400    * {@inheritdoc}
401    */
402   public function prepareQuery($query) {
403     return $this->prepare($this->prefixTables($query));
404   }
405
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]);
419     if (!$affected) {
420       $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', [
421         ':existing_id' => $existing_id,
422       ]);
423     }
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();
427   }
428
429   /**
430    * {@inheritdoc}
431    */
432   public function getFullQualifiedTableName($table) {
433     $prefix = $this->tablePrefix($table);
434
435     // Don't include the SQLite database file name as part of the table name.
436     return $prefix . $table;
437   }
438
439 }