a14a83f07787b75847ed17d6b14121339a712526
[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
128     // Create functions needed by SQLite.
129     $pdo->sqliteCreateFunction('if', [__CLASS__, 'sqlFunctionIf']);
130     $pdo->sqliteCreateFunction('greatest', [__CLASS__, 'sqlFunctionGreatest']);
131     $pdo->sqliteCreateFunction('pow', 'pow', 2);
132     $pdo->sqliteCreateFunction('exp', 'exp', 1);
133     $pdo->sqliteCreateFunction('length', 'strlen', 1);
134     $pdo->sqliteCreateFunction('md5', 'md5', 1);
135     $pdo->sqliteCreateFunction('concat', [__CLASS__, 'sqlFunctionConcat']);
136     $pdo->sqliteCreateFunction('concat_ws', [__CLASS__, 'sqlFunctionConcatWs']);
137     $pdo->sqliteCreateFunction('substring', [__CLASS__, 'sqlFunctionSubstring'], 3);
138     $pdo->sqliteCreateFunction('substring_index', [__CLASS__, 'sqlFunctionSubstringIndex'], 3);
139     $pdo->sqliteCreateFunction('rand', [__CLASS__, 'sqlFunctionRand']);
140     $pdo->sqliteCreateFunction('regexp', [__CLASS__, 'sqlFunctionRegexp']);
141
142     // SQLite does not support the LIKE BINARY operator, so we overload the
143     // non-standard GLOB operator for case-sensitive matching. Another option
144     // would have been to override another non-standard operator, MATCH, but
145     // that does not support the NOT keyword prefix.
146     $pdo->sqliteCreateFunction('glob', [__CLASS__, 'sqlFunctionLikeBinary']);
147
148     // Create a user-space case-insensitive collation with UTF-8 support.
149     $pdo->sqliteCreateCollation('NOCASE_UTF8', ['Drupal\Component\Utility\Unicode', 'strcasecmp']);
150
151     // Set SQLite init_commands if not already defined. Enable the Write-Ahead
152     // Logging (WAL) for SQLite. See https://www.drupal.org/node/2348137 and
153     // https://www.sqlite.org/wal.html.
154     $connection_options += [
155       'init_commands' => [],
156     ];
157     $connection_options['init_commands'] += [
158       'wal' => "PRAGMA journal_mode=WAL",
159     ];
160
161     // Execute sqlite init_commands.
162     if (isset($connection_options['init_commands'])) {
163       $pdo->exec(implode('; ', $connection_options['init_commands']));
164     }
165
166     return $pdo;
167   }
168
169
170   /**
171    * Destructor for the SQLite connection.
172    *
173    * We prune empty databases on destruct, but only if tables have been
174    * dropped. This is especially needed when running the test suite, which
175    * creates and destroy databases several times in a row.
176    */
177   public function __destruct() {
178     if ($this->tableDropped && !empty($this->attachedDatabases)) {
179       foreach ($this->attachedDatabases as $prefix) {
180         // Check if the database is now empty, ignore the internal SQLite tables.
181         try {
182           $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', [':type' => 'table', ':pattern' => 'sqlite_%'])->fetchField();
183
184           // We can prune the database file if it doesn't have any tables.
185           if ($count == 0) {
186             // Detaching the database fails at this point, but no other queries
187             // are executed after the connection is destructed so we can simply
188             // remove the database file.
189             unlink($this->connectionOptions['database'] . '-' . $prefix);
190           }
191         }
192         catch (\Exception $e) {
193           // Ignore the exception and continue. There is nothing we can do here
194           // to report the error or fail safe.
195         }
196       }
197     }
198   }
199
200   /**
201    * Gets all the attached databases.
202    *
203    * @return array
204    *   An array of attached database names.
205    *
206    * @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
207    */
208   public function getAttachedDatabases() {
209     return $this->attachedDatabases;
210   }
211
212   /**
213    * SQLite compatibility implementation for the IF() SQL function.
214    */
215   public static function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
216     return $condition ? $expr1 : $expr2;
217   }
218
219   /**
220    * SQLite compatibility implementation for the GREATEST() SQL function.
221    */
222   public static function sqlFunctionGreatest() {
223     $args = func_get_args();
224     foreach ($args as $v) {
225       if (!isset($v)) {
226         unset($args);
227       }
228     }
229     if (count($args)) {
230       return max($args);
231     }
232     else {
233       return NULL;
234     }
235   }
236
237   /**
238    * SQLite compatibility implementation for the CONCAT() SQL function.
239    */
240   public static function sqlFunctionConcat() {
241     $args = func_get_args();
242     return implode('', $args);
243   }
244
245   /**
246    * SQLite compatibility implementation for the CONCAT_WS() SQL function.
247    *
248    * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
249    */
250   public static function sqlFunctionConcatWs() {
251     $args = func_get_args();
252     $separator = array_shift($args);
253     // If the separator is NULL, the result is NULL.
254     if ($separator === FALSE || is_null($separator)) {
255       return NULL;
256     }
257     // Skip any NULL values after the separator argument.
258     $args = array_filter($args, function ($value) {
259       return !is_null($value);
260     });
261     return implode($separator, $args);
262   }
263
264   /**
265    * SQLite compatibility implementation for the SUBSTRING() SQL function.
266    */
267   public static function sqlFunctionSubstring($string, $from, $length) {
268     return substr($string, $from - 1, $length);
269   }
270
271   /**
272    * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
273    */
274   public static function sqlFunctionSubstringIndex($string, $delimiter, $count) {
275     // If string is empty, simply return an empty string.
276     if (empty($string)) {
277       return '';
278     }
279     $end = 0;
280     for ($i = 0; $i < $count; $i++) {
281       $end = strpos($string, $delimiter, $end + 1);
282       if ($end === FALSE) {
283         $end = strlen($string);
284       }
285     }
286     return substr($string, 0, $end);
287   }
288
289   /**
290    * SQLite compatibility implementation for the RAND() SQL function.
291    */
292   public static function sqlFunctionRand($seed = NULL) {
293     if (isset($seed)) {
294       mt_srand($seed);
295     }
296     return mt_rand() / mt_getrandmax();
297   }
298
299   /**
300    * SQLite compatibility implementation for the REGEXP SQL operator.
301    *
302    * The REGEXP operator is natively known, but not implemented by default.
303    *
304    * @see http://www.sqlite.org/lang_expr.html#regexp
305    */
306   public static function sqlFunctionRegexp($pattern, $subject) {
307     // preg_quote() cannot be used here, since $pattern may contain reserved
308     // regular expression characters already (such as ^, $, etc). Therefore,
309     // use a rare character as PCRE delimiter.
310     $pattern = '#' . addcslashes($pattern, '#') . '#i';
311     return preg_match($pattern, $subject);
312   }
313
314   /**
315    * SQLite compatibility implementation for the LIKE BINARY SQL operator.
316    *
317    * SQLite supports case-sensitive LIKE operations through the
318    * 'case_sensitive_like' PRAGMA statement, but only for ASCII characters, so
319    * we have to provide our own implementation with UTF-8 support.
320    *
321    * @see https://sqlite.org/pragma.html#pragma_case_sensitive_like
322    * @see https://sqlite.org/lang_expr.html#like
323    */
324   public static function sqlFunctionLikeBinary($pattern, $subject) {
325     // Replace the SQL LIKE wildcard meta-characters with the equivalent regular
326     // expression meta-characters and escape the delimiter that will be used for
327     // matching.
328     $pattern = str_replace(['%', '_'], ['.*?', '.'], preg_quote($pattern, '/'));
329     return preg_match('/^' . $pattern . '$/', $subject);
330   }
331
332   /**
333    * {@inheritdoc}
334    */
335   public function prepare($statement, array $driver_options = []) {
336     return new Statement($this->connection, $this, $statement, $driver_options);
337   }
338
339   /**
340    * {@inheritdoc}
341    */
342   protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
343     // The database schema might be changed by another process in between the
344     // time that the statement was prepared and the time the statement was run
345     // (e.g. usually happens when running tests). In this case, we need to
346     // re-run the query.
347     // @see http://www.sqlite.org/faq.html#q15
348     // @see http://www.sqlite.org/rescode.html#schema
349     if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
350       return $this->query($query, $args, $options);
351     }
352
353     parent::handleQueryException($e, $query, $args, $options);
354   }
355
356   public function queryRange($query, $from, $count, array $args = [], array $options = []) {
357     return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
358   }
359
360   public function queryTemporary($query, array $args = [], array $options = []) {
361     // Generate a new temporary table name and protect it from prefixing.
362     // SQLite requires that temporary tables to be non-qualified.
363     $tablename = $this->generateTemporaryTableName();
364     $prefixes = $this->prefixes;
365     $prefixes[$tablename] = '';
366     $this->setPrefix($prefixes);
367
368     $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
369     return $tablename;
370   }
371
372   public function driver() {
373     return 'sqlite';
374   }
375
376   public function databaseType() {
377     return 'sqlite';
378   }
379
380   /**
381    * Overrides \Drupal\Core\Database\Connection::createDatabase().
382    *
383    * @param string $database
384    *   The name of the database to create.
385    *
386    * @throws \Drupal\Core\Database\DatabaseNotFoundException
387    */
388   public function createDatabase($database) {
389     // Verify the database is writable.
390     $db_directory = new \SplFileInfo(dirname($database));
391     if (!$db_directory->isDir() && !drupal_mkdir($db_directory->getPathName(), 0755, TRUE)) {
392       throw new DatabaseNotFoundException('Unable to create database directory ' . $db_directory->getPathName());
393     }
394   }
395
396   public function mapConditionOperator($operator) {
397     return isset(static::$sqliteConditionOperatorMap[$operator]) ? static::$sqliteConditionOperatorMap[$operator] : NULL;
398   }
399
400   /**
401    * {@inheritdoc}
402    */
403   public function prepareQuery($query) {
404     return $this->prepare($this->prefixTables($query));
405   }
406
407   public function nextId($existing_id = 0) {
408     $this->startTransaction();
409     // We can safely use literal queries here instead of the slower query
410     // builder because if a given database breaks here then it can simply
411     // override nextId. However, this is unlikely as we deal with short strings
412     // and integers and no known databases require special handling for those
413     // simple cases. If another transaction wants to write the same row, it will
414     // wait until this transaction commits. Also, the return value needs to be
415     // set to RETURN_AFFECTED as if it were a real update() query otherwise it
416     // is not possible to get the row count properly.
417     $affected = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', [
418       ':existing_id' => $existing_id,
419     ], ['return' => Database::RETURN_AFFECTED]);
420     if (!$affected) {
421       $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', [
422         ':existing_id' => $existing_id,
423       ]);
424     }
425     // The transaction gets committed when the transaction object gets destroyed
426     // because it gets out of scope.
427     return $this->query('SELECT value FROM {sequences}')->fetchField();
428   }
429
430   /**
431    * {@inheritdoc}
432    */
433   public function getFullQualifiedTableName($table) {
434     $prefix = $this->tablePrefix($table);
435
436     // Don't include the SQLite database file name as part of the table name.
437     return $prefix . $table;
438   }
439
440 }