table method

Future<void> table(
  1. String table,
  2. void callback(
    1. Blueprint
    )
)

Modifies an existing table's structure.

This is your go-to method for altering tables. Inside the callback, you can add new columns, rename existing ones, drop indexes, or change column types. It intelligently sequences the operations (dropping constraints before columns, etc.) to ensure the changes are applied smoothly.

Implementation

Future<void> table(String table, void Function(Blueprint) callback) async {
  final blueprint = Blueprint(table);
  callback(blueprint);

  final grammar = _adapter.grammar;
  final commands = <String>[];

  // Drop Constraints (Foreign Keys & Indexes)
  if (blueprint.dropForeigns.isNotEmpty) {
    commands.addAll(grammar.compileDropForeign(blueprint));
  }

  if (blueprint.commands
      .where(
        (c) =>
            c.type.startsWith('dropIndex') ||
            c.type.startsWith('dropUnique') ||
            c.type.startsWith('dropPrimary'),
      )
      .isNotEmpty) {
    commands.addAll(grammar.compileDropIndex(blueprint));
  }

  // Drop Columns
  if (blueprint.commands.where((c) => c.type == 'dropColumn').isNotEmpty) {
    commands.addAll(grammar.compileDropColumn(blueprint));
  }

  // Add Columns
  if (blueprint.columns.where((c) => !c.isChange).isNotEmpty) {
    commands.addAll(grammar.compileAdd(blueprint));
  }

  // Change Columns
  if (blueprint.columns.where((c) => c.isChange).isNotEmpty) {
    commands.addAll(grammar.compileChange(blueprint));
  }

  // Rename Columns
  if (blueprint.commands.where((c) => c.type == 'renameColumn').isNotEmpty) {
    commands.addAll(grammar.compileRenameColumn(blueprint));
  }

  // Add Indexes
  if (blueprint.commands
      .where(
        (c) =>
            c.type == 'index' ||
            c.type == 'unique' ||
            c.type == 'fulltext' ||
            c.type == 'spatial',
      )
      .isNotEmpty) {
    commands.addAll(grammar.compileIndexes(blueprint));
  }

  for (final sql in commands) {
    await _adapter.execute(table, sql);
  }
}