-
I want to use a database with initial data and will add other tables,but I can't use other tables, this gives an error Is there any other way to import data? @DriftDatabase(tables: [Todos])
class AppDb extends _$AppDb {
AppDb() : super(_openConnection());
@override
int get schemaVersion => 1;
Future<int> addTodo(TodosCompanion entry) {
return into(todos).insert(entry);
}
}
// LazyDatabase _openConnection() {
// return LazyDatabase(() async {
// final dbFolder = await getApplicationDocumentsDirectory();
// final file = File(p.join(dbFolder.path, 'db.sqlite'));
// return NativeDatabase(file);
// });
// }
LazyDatabase _openConnection() {
return LazyDatabase(() async {
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(p.join(dbFolder.path, 'app.sqlite'));
if (!await file.exists()) {
final blob = await rootBundle.load('assets/db.sqlite');
final buffer = blob.buffer;
await file.writeAsBytes(buffer.asUint8List(blob.offsetInBytes, blob.lengthInBytes));
}
return NativeDatabase(file);
});
}
class Todos extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text()();
TextColumn get des => text()();
BoolColumn get finish => boolean().withDefault(const Constant(false))();
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
So I assume that your So, I would set the schema version in Then, you set the @override
MigrationStrategy get migration {
return MigrationStrategy(
onUpgrade: (Migrator m, int from, int to) async {
if (from < 2) {
// Probably coming from the asset, add missing tables
await m.createAll();
}
// perhaps other migrations to be added in the future
},
);
} |
Beta Was this translation helpful? Give feedback.
So I assume that your
assets/db.sqlite
does not contain all of the tables that you have defined in your database schema? The easiest way to fix that would be to just add them. If that is not possible, I'd reserve a low schema version number just for the asset so that this can be recognized by drift when opening the database.So, I would set the schema version in
assets/db.sqlite
to 1 (open it withsqlite3 assets/db.sqlite
and runpragma user_version = 1
).Then, you set the
schemaVersion
getter in your database class to2
and write a migration to add the missing tables: