addColumn method
Helper to add column (skips if exists)
If nullable is false, defaultValue is required to avoid errors
when adding a NOT NULL column to a table with existing rows.
Implementation
Future<void> addColumn({
required String table,
required String column,
required String type,
bool nullable = true,
String? defaultValue,
}) async {
// Validate: NOT NULL columns require a default value
if (!nullable && defaultValue == null) {
throw ArgumentError(
'Cannot add NOT NULL column "$column" without a default value. '
'Existing rows would have no value for this column.',
);
}
final exists = await _columnExists(table, column);
if (exists) return;
final nullableStr = nullable ? '' : ' NOT NULL';
final defaultStr = defaultValue != null
? ' DEFAULT ${defaultValue.isEmpty ? "''" : defaultValue}'
: "''";
final sql =
'ALTER TABLE $table ADD COLUMN IF NOT EXISTS $column $type$nullableStr$defaultStr;';
print(sql);
await connection.execute(sql);
}