compile method
Compiles the ALTER TABLE statements of the table, indented by
indent, which may be compiled again, as those of MySQL and MariaDB.
PostgreSQL takes RENAME COLUMN and RENAME TO only as statements of
their own, and DROP COLUMN is one too, so the clauses between them are
one statement each, and those after a RENAME TO are of the new name.
The columns added are clauses in the order they are declared, and a
clause of a column added before it in its statement starts another, as
the column does not exist before the statement.
Implementation
void compile(StringBuffer buf, int indent) {
var table = tableName;
var clauses = <String>[];
// The columns added with a standard index, whose CREATE INDEX follows the
// ALTER TABLE that adds them.
var indexed = <String>[];
void alter(Iterable<String> clauses) {
if (clauses.isEmpty) return;
buf.writeln(
'${' ' * indent}ALTER TABLE ${sql.quotePostgresTableName(table)}',
);
buf.write(clauses.map((c) => '${' ' * (indent + 1)}$c').join(',\n'));
buf.writeln(';');
for (var name in indexed) {
buf.writeln(
'${' ' * indent}'
'${compileCreateIndex(columnIndexName(table, name), table, [name])}',
);
}
indexed.clear();
}
for (var entry in _stack) {
switch (entry) {
case _Statement():
alter(clauses);
clauses = [];
alter([entry.clause]);
table = entry.newTableName ?? table;
case _Break():
alter(clauses);
clauses = [];
case _CreateIndex(:var name, :var columns, :var unique):
// After the clauses before it, of the table as it is named then.
alter(clauses);
clauses = [];
buf.writeln(
'${' ' * indent}'
'${compileCreateIndex(name, table, columns, unique: unique)}',
);
case _DropIndex(:var name):
// After the clauses before it, of the table as it is named then.
alter(clauses);
clauses = [];
buf.writeln(_compileDropIndexOrConstraint(table, name));
case _AddedColumn(:var name):
var column = _columns[name]!;
clauses.add(
'ADD COLUMN ${sql.quotePostgresIdentifier(name)} '
'${PostgresGenerator.compileColumn(column)}',
);
if (column.indexType == IndexType.standardIndex) indexed.add(name);
default:
clauses.add(entry as String);
}
}
alter(clauses);
}