Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / sqlite / Schema.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\sqlite;
4
5 use Drupal\Core\Database\SchemaObjectExistsException;
6 use Drupal\Core\Database\SchemaObjectDoesNotExistException;
7 use Drupal\Core\Database\Schema as DatabaseSchema;
8
9 /**
10  * @ingroup schemaapi
11  * @{
12  */
13
14 /**
15  * SQLite implementation of \Drupal\Core\Database\Schema.
16  */
17 class Schema extends DatabaseSchema {
18
19   /**
20    * Override DatabaseSchema::$defaultSchema
21    *
22    * @var string
23    */
24   protected $defaultSchema = 'main';
25
26   /**
27    * {@inheritdoc}
28    */
29   public function tableExists($table) {
30     $info = $this->getPrefixInfo($table);
31
32     // Don't use {} around sqlite_master table.
33     return (bool) $this->connection->query('SELECT 1 FROM ' . $info['schema'] . '.sqlite_master WHERE type = :type AND name = :name', [':type' => 'table', ':name' => $info['table']])->fetchField();
34   }
35
36   /**
37    * {@inheritdoc}
38    */
39   public function fieldExists($table, $column) {
40     $schema = $this->introspectSchema($table);
41     return !empty($schema['fields'][$column]);
42   }
43
44   /**
45    * Generate SQL to create a new table from a Drupal schema definition.
46    *
47    * @param $name
48    *   The name of the table to create.
49    * @param $table
50    *   A Schema API table definition array.
51    * @return
52    *   An array of SQL statements to create the table.
53    */
54   public function createTableSql($name, $table) {
55     if (!empty($table['primary key']) && is_array($table['primary key'])) {
56       $this->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
57     }
58
59     $sql = [];
60     $sql[] = "CREATE TABLE {" . $name . "} (\n" . $this->createColumnsSql($name, $table) . "\n)\n";
61     return array_merge($sql, $this->createIndexSql($name, $table));
62   }
63
64   /**
65    * Build the SQL expression for indexes.
66    */
67   protected function createIndexSql($tablename, $schema) {
68     $sql = [];
69     $info = $this->getPrefixInfo($tablename);
70     if (!empty($schema['unique keys'])) {
71       foreach ($schema['unique keys'] as $key => $fields) {
72         $sql[] = 'CREATE UNIQUE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . ")\n";
73       }
74     }
75     if (!empty($schema['indexes'])) {
76       foreach ($schema['indexes'] as $key => $fields) {
77         $sql[] = 'CREATE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . ")\n";
78       }
79     }
80     return $sql;
81   }
82
83   /**
84    * Build the SQL expression for creating columns.
85    */
86   protected function createColumnsSql($tablename, $schema) {
87     $sql_array = [];
88
89     // Add the SQL statement for each field.
90     foreach ($schema['fields'] as $name => $field) {
91       if (isset($field['type']) && $field['type'] == 'serial') {
92         if (isset($schema['primary key']) && ($key = array_search($name, $schema['primary key'])) !== FALSE) {
93           unset($schema['primary key'][$key]);
94         }
95       }
96       $sql_array[] = $this->createFieldSql($name, $this->processField($field));
97     }
98
99     // Process keys.
100     if (!empty($schema['primary key'])) {
101       $sql_array[] = " PRIMARY KEY (" . $this->createKeySql($schema['primary key']) . ")";
102     }
103
104     return implode(", \n", $sql_array);
105   }
106
107   /**
108    * Build the SQL expression for keys.
109    */
110   protected function createKeySql($fields) {
111     $return = [];
112     foreach ($fields as $field) {
113       if (is_array($field)) {
114         $return[] = $field[0];
115       }
116       else {
117         $return[] = $field;
118       }
119     }
120     return implode(', ', $return);
121   }
122
123   /**
124    * Set database-engine specific properties for a field.
125    *
126    * @param $field
127    *   A field description array, as specified in the schema documentation.
128    */
129   protected function processField($field) {
130     if (!isset($field['size'])) {
131       $field['size'] = 'normal';
132     }
133
134     // Set the correct database-engine specific datatype.
135     // In case one is already provided, force it to uppercase.
136     if (isset($field['sqlite_type'])) {
137       $field['sqlite_type'] = mb_strtoupper($field['sqlite_type']);
138     }
139     else {
140       $map = $this->getFieldTypeMap();
141       $field['sqlite_type'] = $map[$field['type'] . ':' . $field['size']];
142
143       // Numeric fields with a specified scale have to be stored as floats.
144       if ($field['sqlite_type'] === 'NUMERIC' && isset($field['scale'])) {
145         $field['sqlite_type'] = 'FLOAT';
146       }
147     }
148
149     if (isset($field['type']) && $field['type'] == 'serial') {
150       $field['auto_increment'] = TRUE;
151     }
152
153     return $field;
154   }
155
156   /**
157    * Create an SQL string for a field to be used in table creation or alteration.
158    *
159    * Before passing a field out of a schema definition into this function it has
160    * to be processed by db_processField().
161    *
162    * @param $name
163    *   Name of the field.
164    * @param $spec
165    *   The field specification, as per the schema data structure format.
166    */
167   protected function createFieldSql($name, $spec) {
168     if (!empty($spec['auto_increment'])) {
169       $sql = $name . " INTEGER PRIMARY KEY AUTOINCREMENT";
170       if (!empty($spec['unsigned'])) {
171         $sql .= ' CHECK (' . $name . '>= 0)';
172       }
173     }
174     else {
175       $sql = $name . ' ' . $spec['sqlite_type'];
176
177       if (in_array($spec['sqlite_type'], ['VARCHAR', 'TEXT'])) {
178         if (isset($spec['length'])) {
179           $sql .= '(' . $spec['length'] . ')';
180         }
181
182         if (isset($spec['binary']) && $spec['binary'] === FALSE) {
183           $sql .= ' COLLATE NOCASE_UTF8';
184         }
185       }
186
187       if (isset($spec['not null'])) {
188         if ($spec['not null']) {
189           $sql .= ' NOT NULL';
190         }
191         else {
192           $sql .= ' NULL';
193         }
194       }
195
196       if (!empty($spec['unsigned'])) {
197         $sql .= ' CHECK (' . $name . '>= 0)';
198       }
199
200       if (isset($spec['default'])) {
201         if (is_string($spec['default'])) {
202           $spec['default'] = $this->connection->quote($spec['default']);
203         }
204         $sql .= ' DEFAULT ' . $spec['default'];
205       }
206
207       if (empty($spec['not null']) && !isset($spec['default'])) {
208         $sql .= ' DEFAULT NULL';
209       }
210     }
211     return $sql;
212   }
213
214   /**
215    * {@inheritdoc}
216    */
217   public function getFieldTypeMap() {
218     // Put :normal last so it gets preserved by array_flip. This makes
219     // it much easier for modules (such as schema.module) to map
220     // database types back into schema types.
221     // $map does not use drupal_static as its value never changes.
222     static $map = [
223       'varchar_ascii:normal' => 'VARCHAR',
224
225       'varchar:normal'  => 'VARCHAR',
226       'char:normal'     => 'CHAR',
227
228       'text:tiny'       => 'TEXT',
229       'text:small'      => 'TEXT',
230       'text:medium'     => 'TEXT',
231       'text:big'        => 'TEXT',
232       'text:normal'     => 'TEXT',
233
234       'serial:tiny'     => 'INTEGER',
235       'serial:small'    => 'INTEGER',
236       'serial:medium'   => 'INTEGER',
237       'serial:big'      => 'INTEGER',
238       'serial:normal'   => 'INTEGER',
239
240       'int:tiny'        => 'INTEGER',
241       'int:small'       => 'INTEGER',
242       'int:medium'      => 'INTEGER',
243       'int:big'         => 'INTEGER',
244       'int:normal'      => 'INTEGER',
245
246       'float:tiny'      => 'FLOAT',
247       'float:small'     => 'FLOAT',
248       'float:medium'    => 'FLOAT',
249       'float:big'       => 'FLOAT',
250       'float:normal'    => 'FLOAT',
251
252       'numeric:normal'  => 'NUMERIC',
253
254       'blob:big'        => 'BLOB',
255       'blob:normal'     => 'BLOB',
256     ];
257     return $map;
258   }
259
260   /**
261    * {@inheritdoc}
262    */
263   public function renameTable($table, $new_name) {
264     if (!$this->tableExists($table)) {
265       throw new SchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", ['@table' => $table, '@table_new' => $new_name]));
266     }
267     if ($this->tableExists($new_name)) {
268       throw new SchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", ['@table' => $table, '@table_new' => $new_name]));
269     }
270
271     $schema = $this->introspectSchema($table);
272
273     // SQLite doesn't allow you to rename tables outside of the current
274     // database. So the syntax '... RENAME TO database.table' would fail.
275     // So we must determine the full table name here rather than surrounding
276     // the table with curly braces in case the db_prefix contains a reference
277     // to a database outside of our existing database.
278     $info = $this->getPrefixInfo($new_name);
279     $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $info['table']);
280
281     // Drop the indexes, there is no RENAME INDEX command in SQLite.
282     if (!empty($schema['unique keys'])) {
283       foreach ($schema['unique keys'] as $key => $fields) {
284         $this->dropIndex($table, $key);
285       }
286     }
287     if (!empty($schema['indexes'])) {
288       foreach ($schema['indexes'] as $index => $fields) {
289         $this->dropIndex($table, $index);
290       }
291     }
292
293     // Recreate the indexes.
294     $statements = $this->createIndexSql($new_name, $schema);
295     foreach ($statements as $statement) {
296       $this->connection->query($statement);
297     }
298   }
299
300   /**
301    * {@inheritdoc}
302    */
303   public function dropTable($table) {
304     if (!$this->tableExists($table)) {
305       return FALSE;
306     }
307     $this->connection->tableDropped = TRUE;
308     $this->connection->query('DROP TABLE {' . $table . '}');
309     return TRUE;
310   }
311
312   /**
313    * {@inheritdoc}
314    */
315   public function addField($table, $field, $specification, $keys_new = []) {
316     if (!$this->tableExists($table)) {
317       throw new SchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", ['@field' => $field, '@table' => $table]));
318     }
319     if ($this->fieldExists($table, $field)) {
320       throw new SchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", ['@field' => $field, '@table' => $table]));
321     }
322     if (isset($keys_new['primary key']) && in_array($field, $keys_new['primary key'], TRUE)) {
323       $this->ensureNotNullPrimaryKey($keys_new['primary key'], [$field => $specification]);
324     }
325
326     // SQLite doesn't have a full-featured ALTER TABLE statement. It only
327     // supports adding new fields to a table, in some simple cases. In most
328     // cases, we have to create a new table and copy the data over.
329     if (empty($keys_new) && (empty($specification['not null']) || isset($specification['default']))) {
330       // When we don't have to create new keys and we are not creating a
331       // NOT NULL column without a default value, we can use the quicker version.
332       $query = 'ALTER TABLE {' . $table . '} ADD ' . $this->createFieldSql($field, $this->processField($specification));
333       $this->connection->query($query);
334
335       // Apply the initial value if set.
336       if (isset($specification['initial_from_field'])) {
337         if (isset($specification['initial'])) {
338           $expression = 'COALESCE(' . $specification['initial_from_field'] . ', :default_initial_value)';
339           $arguments = [':default_initial_value' => $specification['initial']];
340         }
341         else {
342           $expression = $specification['initial_from_field'];
343           $arguments = [];
344         }
345         $this->connection->update($table)
346           ->expression($field, $expression, $arguments)
347           ->execute();
348       }
349       elseif (isset($specification['initial'])) {
350         $this->connection->update($table)
351           ->fields([$field => $specification['initial']])
352           ->execute();
353       }
354     }
355     else {
356       // We cannot add the field directly. Use the slower table alteration
357       // method, starting from the old schema.
358       $old_schema = $this->introspectSchema($table);
359       $new_schema = $old_schema;
360
361       // Add the new field.
362       $new_schema['fields'][$field] = $specification;
363
364       // Build the mapping between the old fields and the new fields.
365       $mapping = [];
366       if (isset($specification['initial_from_field'])) {
367         // If we have a initial value, copy it over.
368         if (isset($specification['initial'])) {
369           $expression = 'COALESCE(' . $specification['initial_from_field'] . ', :default_initial_value)';
370           $arguments = [':default_initial_value' => $specification['initial']];
371         }
372         else {
373           $expression = $specification['initial_from_field'];
374           $arguments = [];
375         }
376         $mapping[$field] = [
377           'expression' => $expression,
378           'arguments' => $arguments,
379         ];
380       }
381       elseif (isset($specification['initial'])) {
382         // If we have a initial value, copy it over.
383         $mapping[$field] = [
384           'expression' => ':newfieldinitial',
385           'arguments' => [':newfieldinitial' => $specification['initial']],
386         ];
387       }
388       else {
389         // Else use the default of the field.
390         $mapping[$field] = NULL;
391       }
392
393       // Add the new indexes.
394       $new_schema = array_merge($new_schema, $keys_new);
395
396       $this->alterTable($table, $old_schema, $new_schema, $mapping);
397     }
398   }
399
400   /**
401    * Create a table with a new schema containing the old content.
402    *
403    * As SQLite does not support ALTER TABLE (with a few exceptions) it is
404    * necessary to create a new table and copy over the old content.
405    *
406    * @param $table
407    *   Name of the table to be altered.
408    * @param $old_schema
409    *   The old schema array for the table.
410    * @param $new_schema
411    *   The new schema array for the table.
412    * @param $mapping
413    *   An optional mapping between the fields of the old specification and the
414    *   fields of the new specification. An associative array, whose keys are
415    *   the fields of the new table, and values can take two possible forms:
416    *     - a simple string, which is interpreted as the name of a field of the
417    *       old table,
418    *     - an associative array with two keys 'expression' and 'arguments',
419    *       that will be used as an expression field.
420    */
421   protected function alterTable($table, $old_schema, $new_schema, array $mapping = []) {
422     $i = 0;
423     do {
424       $new_table = $table . '_' . $i++;
425     } while ($this->tableExists($new_table));
426
427     $this->createTable($new_table, $new_schema);
428
429     // Build a SQL query to migrate the data from the old table to the new.
430     $select = $this->connection->select($table);
431
432     // Complete the mapping.
433     $possible_keys = array_keys($new_schema['fields']);
434     $mapping += array_combine($possible_keys, $possible_keys);
435
436     // Now add the fields.
437     foreach ($mapping as $field_alias => $field_source) {
438       // Just ignore this field (ie. use its default value).
439       if (!isset($field_source)) {
440         continue;
441       }
442
443       if (is_array($field_source)) {
444         $select->addExpression($field_source['expression'], $field_alias, $field_source['arguments']);
445       }
446       else {
447         $select->addField($table, $field_source, $field_alias);
448       }
449     }
450
451     // Execute the data migration query.
452     $this->connection->insert($new_table)
453       ->from($select)
454       ->execute();
455
456     $old_count = $this->connection->query('SELECT COUNT(*) FROM {' . $table . '}')->fetchField();
457     $new_count = $this->connection->query('SELECT COUNT(*) FROM {' . $new_table . '}')->fetchField();
458     if ($old_count == $new_count) {
459       $this->dropTable($table);
460       $this->renameTable($new_table, $table);
461     }
462   }
463
464   /**
465    * Find out the schema of a table.
466    *
467    * This function uses introspection methods provided by the database to
468    * create a schema array. This is useful, for example, during update when
469    * the old schema is not available.
470    *
471    * @param $table
472    *   Name of the table.
473    *
474    * @return
475    *   An array representing the schema.
476    *
477    * @throws \Exception
478    *   If a column of the table could not be parsed.
479    */
480   protected function introspectSchema($table) {
481     $mapped_fields = array_flip($this->getFieldTypeMap());
482     $schema = [
483       'fields' => [],
484       'primary key' => [],
485       'unique keys' => [],
486       'indexes' => [],
487     ];
488
489     $info = $this->getPrefixInfo($table);
490     $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.table_info(' . $info['table'] . ')');
491     foreach ($result as $row) {
492       if (preg_match('/^([^(]+)\((.*)\)$/', $row->type, $matches)) {
493         $type = $matches[1];
494         $length = $matches[2];
495       }
496       else {
497         $type = $row->type;
498         $length = NULL;
499       }
500       if (isset($mapped_fields[$type])) {
501         list($type, $size) = explode(':', $mapped_fields[$type]);
502         $schema['fields'][$row->name] = [
503           'type' => $type,
504           'size' => $size,
505           'not null' => !empty($row->notnull) || $row->pk !== "0",
506           'default' => trim($row->dflt_value, "'"),
507         ];
508         if ($length) {
509           $schema['fields'][$row->name]['length'] = $length;
510         }
511         // $row->pk contains a number that reflects the primary key order. We
512         // use that as the key and sort (by key) below to return the primary key
513         // in the same order that it is stored in.
514         if ($row->pk) {
515           $schema['primary key'][$row->pk] = $row->name;
516         }
517       }
518       else {
519         throw new \Exception("Unable to parse the column type " . $row->type);
520       }
521     }
522     ksort($schema['primary key']);
523     // Re-key the array because $row->pk starts counting at 1.
524     $schema['primary key'] = array_values($schema['primary key']);
525
526     $indexes = [];
527     $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_list(' . $info['table'] . ')');
528     foreach ($result as $row) {
529       if (strpos($row->name, 'sqlite_autoindex_') !== 0) {
530         $indexes[] = [
531           'schema_key' => $row->unique ? 'unique keys' : 'indexes',
532           'name' => $row->name,
533         ];
534       }
535     }
536     foreach ($indexes as $index) {
537       $name = $index['name'];
538       // Get index name without prefix.
539       $index_name = substr($name, strlen($info['table']) + 1);
540       $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $name . ')');
541       foreach ($result as $row) {
542         $schema[$index['schema_key']][$index_name][] = $row->name;
543       }
544     }
545     return $schema;
546   }
547
548   /**
549    * {@inheritdoc}
550    */
551   public function dropField($table, $field) {
552     if (!$this->fieldExists($table, $field)) {
553       return FALSE;
554     }
555
556     $old_schema = $this->introspectSchema($table);
557     $new_schema = $old_schema;
558
559     unset($new_schema['fields'][$field]);
560
561     // Drop the primary key if the field to drop is part of it. This is
562     // consistent with the behavior on PostgreSQL.
563     // @see \Drupal\Core\Database\Driver\mysql\Schema::dropField()
564     if (isset($new_schema['primary key']) && in_array($field, $new_schema['primary key'], TRUE)) {
565       unset($new_schema['primary key']);
566     }
567
568     // Handle possible index changes.
569     foreach ($new_schema['indexes'] as $index => $fields) {
570       foreach ($fields as $key => $field_name) {
571         if ($field_name == $field) {
572           unset($new_schema['indexes'][$index][$key]);
573         }
574       }
575       // If this index has no more fields then remove it.
576       if (empty($new_schema['indexes'][$index])) {
577         unset($new_schema['indexes'][$index]);
578       }
579     }
580     $this->alterTable($table, $old_schema, $new_schema);
581     return TRUE;
582   }
583
584   /**
585    * {@inheritdoc}
586    */
587   public function changeField($table, $field, $field_new, $spec, $keys_new = []) {
588     if (!$this->fieldExists($table, $field)) {
589       throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", ['@table' => $table, '@name' => $field]));
590     }
591     if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
592       throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", ['@table' => $table, '@name' => $field, '@name_new' => $field_new]));
593     }
594     if (isset($keys_new['primary key']) && in_array($field_new, $keys_new['primary key'], TRUE)) {
595       $this->ensureNotNullPrimaryKey($keys_new['primary key'], [$field_new => $spec]);
596     }
597
598     $old_schema = $this->introspectSchema($table);
599     $new_schema = $old_schema;
600
601     // Map the old field to the new field.
602     if ($field != $field_new) {
603       $mapping[$field_new] = $field;
604     }
605     else {
606       $mapping = [];
607     }
608
609     // Remove the previous definition and swap in the new one.
610     unset($new_schema['fields'][$field]);
611     $new_schema['fields'][$field_new] = $spec;
612
613     // Map the former indexes to the new column name.
614     $new_schema['primary key'] = $this->mapKeyDefinition($new_schema['primary key'], $mapping);
615     foreach (['unique keys', 'indexes'] as $k) {
616       foreach ($new_schema[$k] as &$key_definition) {
617         $key_definition = $this->mapKeyDefinition($key_definition, $mapping);
618       }
619     }
620
621     // Add in the keys from $keys_new.
622     if (isset($keys_new['primary key'])) {
623       $new_schema['primary key'] = $keys_new['primary key'];
624     }
625     foreach (['unique keys', 'indexes'] as $k) {
626       if (!empty($keys_new[$k])) {
627         $new_schema[$k] = $keys_new[$k] + $new_schema[$k];
628       }
629     }
630
631     $this->alterTable($table, $old_schema, $new_schema, $mapping);
632   }
633
634   /**
635    * Utility method: rename columns in an index definition according to a new mapping.
636    *
637    * @param $key_definition
638    *   The key definition.
639    * @param $mapping
640    *   The new mapping.
641    */
642   protected function mapKeyDefinition(array $key_definition, array $mapping) {
643     foreach ($key_definition as &$field) {
644       // The key definition can be an array($field, $length).
645       if (is_array($field)) {
646         $field = &$field[0];
647       }
648
649       $mapped_field = array_search($field, $mapping, TRUE);
650       if ($mapped_field !== FALSE) {
651         $field = $mapped_field;
652       }
653     }
654     return $key_definition;
655   }
656
657   /**
658    * {@inheritdoc}
659    */
660   public function addIndex($table, $name, $fields, array $spec) {
661     if (!$this->tableExists($table)) {
662       throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
663     }
664     if ($this->indexExists($table, $name)) {
665       throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", ['@table' => $table, '@name' => $name]));
666     }
667
668     $schema['indexes'][$name] = $fields;
669     $statements = $this->createIndexSql($table, $schema);
670     foreach ($statements as $statement) {
671       $this->connection->query($statement);
672     }
673   }
674
675   /**
676    * {@inheritdoc}
677    */
678   public function indexExists($table, $name) {
679     $info = $this->getPrefixInfo($table);
680
681     return $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $info['table'] . '_' . $name . ')')->fetchField() != '';
682   }
683
684   /**
685    * {@inheritdoc}
686    */
687   public function dropIndex($table, $name) {
688     if (!$this->indexExists($table, $name)) {
689       return FALSE;
690     }
691
692     $info = $this->getPrefixInfo($table);
693
694     $this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name);
695     return TRUE;
696   }
697
698   /**
699    * {@inheritdoc}
700    */
701   public function addUniqueKey($table, $name, $fields) {
702     if (!$this->tableExists($table)) {
703       throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
704     }
705     if ($this->indexExists($table, $name)) {
706       throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", ['@table' => $table, '@name' => $name]));
707     }
708
709     $schema['unique keys'][$name] = $fields;
710     $statements = $this->createIndexSql($table, $schema);
711     foreach ($statements as $statement) {
712       $this->connection->query($statement);
713     }
714   }
715
716   /**
717    * {@inheritdoc}
718    */
719   public function dropUniqueKey($table, $name) {
720     if (!$this->indexExists($table, $name)) {
721       return FALSE;
722     }
723
724     $info = $this->getPrefixInfo($table);
725
726     $this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name);
727     return TRUE;
728   }
729
730   /**
731    * {@inheritdoc}
732    */
733   public function addPrimaryKey($table, $fields) {
734     if (!$this->tableExists($table)) {
735       throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", ['@table' => $table]));
736     }
737
738     $old_schema = $this->introspectSchema($table);
739     $new_schema = $old_schema;
740
741     if (!empty($new_schema['primary key'])) {
742       throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
743     }
744
745     $new_schema['primary key'] = $fields;
746     $this->ensureNotNullPrimaryKey($new_schema['primary key'], $new_schema['fields']);
747     $this->alterTable($table, $old_schema, $new_schema);
748   }
749
750   /**
751    * {@inheritdoc}
752    */
753   public function dropPrimaryKey($table) {
754     $old_schema = $this->introspectSchema($table);
755     $new_schema = $old_schema;
756
757     if (empty($new_schema['primary key'])) {
758       return FALSE;
759     }
760
761     unset($new_schema['primary key']);
762     $this->alterTable($table, $old_schema, $new_schema);
763     return TRUE;
764   }
765
766   /**
767    * {@inheritdoc}
768    */
769   protected function findPrimaryKeyColumns($table) {
770     if (!$this->tableExists($table)) {
771       return FALSE;
772     }
773     $schema = $this->introspectSchema($table);
774     return $schema['primary key'];
775   }
776
777   /**
778    * {@inheritdoc}
779    */
780   public function fieldSetDefault($table, $field, $default) {
781     if (!$this->fieldExists($table, $field)) {
782       throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
783     }
784
785     $old_schema = $this->introspectSchema($table);
786     $new_schema = $old_schema;
787
788     $new_schema['fields'][$field]['default'] = $default;
789     $this->alterTable($table, $old_schema, $new_schema);
790   }
791
792   /**
793    * {@inheritdoc}
794    */
795   public function fieldSetNoDefault($table, $field) {
796     if (!$this->fieldExists($table, $field)) {
797       throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
798     }
799
800     $old_schema = $this->introspectSchema($table);
801     $new_schema = $old_schema;
802
803     unset($new_schema['fields'][$field]['default']);
804     $this->alterTable($table, $old_schema, $new_schema);
805   }
806
807   /**
808    * {@inheritdoc}
809    */
810   public function findTables($table_expression) {
811     $tables = [];
812
813     // The SQLite implementation doesn't need to use the same filtering strategy
814     // as the parent one because individually prefixed tables live in their own
815     // schema (database), which means that neither the main database nor any
816     // attached one will contain a prefixed table name, so we just need to loop
817     // over all known schemas and filter by the user-supplied table expression.
818     $attached_dbs = $this->connection->getAttachedDatabases();
819     foreach ($attached_dbs as $schema) {
820       // Can't use query placeholders for the schema because the query would
821       // have to be :prefixsqlite_master, which does not work. We also need to
822       // ignore the internal SQLite tables.
823       $result = $this->connection->query("SELECT name FROM " . $schema . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [
824         ':type' => 'table',
825         ':table_name' => $table_expression,
826         ':pattern' => 'sqlite_%',
827       ]);
828       $tables += $result->fetchAllKeyed(0, 0);
829     }
830
831     return $tables;
832   }
833
834 }