protected Schema::alterTable($table, $old_schema, $new_schema, array $mapping = array())
Create a table with a new schema containing the old content.
As SQLite does not support ALTER TABLE (with a few exceptions) it is necessary to create a new table and copy over the old content.
$table: Name of the table to be altered.
$old_schema: The old schema array for the table.
$new_schema: The new schema array for the table.
$mapping: An optional mapping between the fields of the old specification and the fields of the new specification. An associative array, whose keys are the fields of the new table, and values can take two possible forms:
protected function alterTable($table, $old_schema, $new_schema, array $mapping = array()) { $i = 0; do { $new_table = $table . '_' . $i++; } while ($this->tableExists($new_table)); $this->createTable($new_table, $new_schema); // Build a SQL query to migrate the data from the old table to the new. $select = $this->connection->select($table); // Complete the mapping. $possible_keys = array_keys($new_schema['fields']); $mapping += array_combine($possible_keys, $possible_keys); // Now add the fields. foreach ($mapping as $field_alias => $field_source) { // Just ignore this field (ie. use it's default value). if (!isset($field_source)) { continue; } if (is_array($field_source)) { $select->addExpression($field_source['expression'], $field_alias, $field_source['arguments']); } else { $select->addField($table, $field_source, $field_alias); } } // Execute the data migration query. $this->connection->insert($new_table) ->from($select) ->execute(); $old_count = $this->connection->query('SELECT COUNT(*) FROM {' . $table . '}')->fetchField(); $new_count = $this->connection->query('SELECT COUNT(*) FROM {' . $new_table . '}')->fetchField(); if ($old_count == $new_count) { $this->dropTable($table); $this->renameTable($new_table, $table); } }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Driver!sqlite!Schema.php/function/Schema::alterTable/8.1.x