Schema.php 27 KB

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