2024-03-29 12:52:28 +00:00
|
|
|
import 'package:drift/drift.dart';
|
|
|
|
import 'dart:io';
|
|
|
|
import 'package:drift/native.dart';
|
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import 'package:path/path.dart' as p;
|
|
|
|
import 'package:sqlite3/sqlite3.dart';
|
|
|
|
import 'package:sqlite3_flutter_libs/sqlite3_flutter_libs.dart';
|
|
|
|
|
|
|
|
part 'database.g.dart';
|
|
|
|
|
2024-04-04 16:29:09 +00:00
|
|
|
var database = AppDatabase(); //global, since we should only use one instance
|
|
|
|
|
|
|
|
class PersistentNote extends Table {
|
2024-03-29 12:52:28 +00:00
|
|
|
TextColumn get id => text()();
|
|
|
|
TextColumn get content => text()();
|
|
|
|
}
|
|
|
|
|
2024-04-04 16:29:09 +00:00
|
|
|
class PersistentTheme extends Table {
|
|
|
|
TextColumn get brightness => text().withDefault(const Constant("dark"))();
|
|
|
|
}
|
|
|
|
|
|
|
|
@DriftDatabase(tables: [PersistentNote, PersistentTheme])
|
2024-03-29 12:52:28 +00:00
|
|
|
class AppDatabase extends _$AppDatabase {
|
|
|
|
AppDatabase() : super(_openConnection());
|
|
|
|
|
|
|
|
@override
|
2024-04-04 16:29:09 +00:00
|
|
|
int get schemaVersion => 2;
|
2024-03-29 12:52:28 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
MigrationStrategy get migration {
|
|
|
|
return MigrationStrategy(
|
|
|
|
onCreate: (Migrator m) async {
|
|
|
|
await m.createAll();
|
|
|
|
},
|
|
|
|
onUpgrade: (Migrator m, int from, int to) async {
|
2024-04-04 16:29:09 +00:00
|
|
|
if (from < 2) {
|
|
|
|
await m.renameTable(persistentNote, "note_table");
|
|
|
|
await m.createTable(persistentTheme);
|
|
|
|
}
|
2024-03-29 12:52:28 +00:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
LazyDatabase _openConnection() {
|
|
|
|
return LazyDatabase(() async {
|
|
|
|
final dbFolder = await getApplicationDocumentsDirectory();
|
|
|
|
final file = File(p.join(dbFolder.path, 'db.sqlite'));
|
|
|
|
|
|
|
|
if (Platform.isAndroid) {
|
|
|
|
await applyWorkaroundToOpenSqlite3OnOldAndroidVersions();
|
|
|
|
}
|
|
|
|
|
|
|
|
final cachebase = (await getTemporaryDirectory()).path;
|
2024-04-04 16:29:09 +00:00
|
|
|
|
2024-03-29 12:52:28 +00:00
|
|
|
sqlite3.tempDirectory = cachebase;
|
|
|
|
|
|
|
|
return NativeDatabase.createInBackground(file);
|
|
|
|
});
|
|
|
|
}
|