1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
part 'database.g.dart';
@DataClassName('BookmarkRow')
class Bookmarks extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 200)();
TextColumn get url => text()();
TextColumn get note => text().withDefault(const Constant(''))();
BoolColumn get favorite => boolean().withDefault(const Constant(false))();
DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
}
@DriftDatabase(tables: <Type>[Bookmarks])
class AppDatabase extends _$AppDatabase {
AppDatabase(super.executor);
AppDatabase.memory() : super(NativeDatabase.memory());
factory AppDatabase.open() => AppDatabase(_open());
@override
int get schemaVersion => 1;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (Migrator m) => m.createAll(),
onUpgrade: (Migrator m, int from, int to) async {
},
);
Stream<List<BookmarkRow>> watchAllRows() => (select(bookmarks)
..orderBy(<OrderClauseGenerator<$BookmarksTable>>[
(t) => OrderingTerm(expression: t.favorite, mode: OrderingMode.desc),
(t) => OrderingTerm(expression: t.createdAt, mode: OrderingMode.desc),
]))
.watch();
Future<({int id, bool created})> insertRow({
required String title,
required String url,
String note = '',
}) async {
final BookmarkRow? existing = await (select(bookmarks)
..where((t) => t.url.equals(url))
..limit(1))
.getSingleOrNull();
if (existing != null) return (id: existing.id, created: false);
final int id = await into(bookmarks).insert(BookmarksCompanion.insert(
title: title,
url: url,
note: Value<String>(note),
));
return (id: id, created: true);
}
Future<void> updateFavorite(int id, {required bool favorite}) => (update(bookmarks)
..where((t) => t.id.equals(id)))
.write(BookmarksCompanion(favorite: Value<bool>(favorite)));
Future<int> deleteRow(int id) =>
(delete(bookmarks)..where((t) => t.id.equals(id))).go();
}
LazyDatabase _open() => LazyDatabase(() async {
final Directory dir = await getApplicationSupportDirectory();
final File file = File(p.join(dir.path, 'bookmarks.sqlite'));
return NativeDatabase.createInBackground(file);
});