createTable method
Implementation
Future<void> createTable(ISQLiteItem item) async {
final db = await getOpenDatabase();
final tableName = item.getTableName();
final primaryKey = item.getPrimaryKeyName();
final map = item.toMap();
final exists = await tableExists(tableName);
if (!exists) {
// Table doesn't exist; create with full schema
final columns = <String>[];
map.forEach((key, value) {
if (key == primaryKey) {
columns.add('$key INTEGER PRIMARY KEY AUTOINCREMENT');
} else {
columns.add('$key ${_getSQLiteType(value)}');
}
});
final createTableSQL =
'CREATE TABLE IF NOT EXISTS $tableName (${columns.join(', ')});';
print('[CREATE] Executing SQL: $createTableSQL');
await db.execute(createTableSQL);
} else {
// Table exists, check for missing columns
final existingColumns = await tableColumns(tableName, db: db);
for (final entry in map.entries) {
if (!existingColumns.contains(entry.key)) {
final sqlType = _getSQLiteType(entry.value);
final alterSQL =
'ALTER TABLE $tableName ADD COLUMN ${entry.key} $sqlType';
print('[ALTER] Executing SQL: $alterSQL');
await db.execute(alterSQL);
}
}
print('[INFO] Existing columns in $tableName: $existingColumns');
}
}