alterTable method Null safety

void alterTable(
  1. String tableName,
  2. void modify(
    1. SchemaTable targetTable
    )
)

Alters a table in schema.

Implementation

void alterTable(
  String tableName,
  void Function(SchemaTable targetTable) modify,
) {
  final existingTable = schema!.tableForName(tableName);
  if (existingTable == null) {
    throw SchemaException("Table $tableName does not exist.");
  }

  final newTable = SchemaTable.from(existingTable);
  modify(newTable);
  schema!.replaceTable(existingTable, newTable);

  final shouldAddUnique = existingTable.uniqueColumnSet == null &&
      newTable.uniqueColumnSet != null;
  final shouldRemoveUnique = existingTable.uniqueColumnSet != null &&
      newTable.uniqueColumnSet == null;

  final innerCommands = <String>[];
  if (shouldAddUnique) {
    if (store != null) {
      commands.addAll(store!.addTableUniqueColumnSet(newTable));
    } else {
      innerCommands.add(
        "t.uniqueColumnSet = [${newTable.uniqueColumnSet!.map((s) => '"$s"').join(',')}]",
      );
    }
  } else if (shouldRemoveUnique) {
    if (store != null) {
      commands.addAll(store!.deleteTableUniqueColumnSet(newTable));
    } else {
      innerCommands.add("t.uniqueColumnSet = null");
    }
  } else {
    final haveSameLength = existingTable.uniqueColumnSet!.length ==
        newTable.uniqueColumnSet!.length;
    final haveSameKeys = existingTable.uniqueColumnSet!
        .every((s) => newTable.uniqueColumnSet!.contains(s));

    if (!haveSameKeys || !haveSameLength) {
      if (store != null) {
        commands.addAll(store!.deleteTableUniqueColumnSet(newTable));
        commands.addAll(store!.addTableUniqueColumnSet(newTable));
      } else {
        innerCommands.add(
          "t.uniqueColumnSet = [${newTable.uniqueColumnSet!.map((s) => '"$s"').join(',')}]",
        );
      }
    }
  }

  if (store == null && innerCommands.isNotEmpty) {
    commands.add(
      'database.alterTable("$tableName", (t) {${innerCommands.join(";")};});',
    );
  }
}