Skip to content

Commit 780b092

Browse files
committed
db: Write a first Drift schema
Also add a .gitattributes file, excluding `*.g.dart` files from diffs. We didn't really need this when the only such files were the JSON serialization/deserialization files in the API bindings, because those are pretty compact; but this generated ORM code is much longer and makes it more necessary.
1 parent 483a3ef commit 780b092

File tree

4 files changed

+553
-0
lines changed

4 files changed

+553
-0
lines changed

.gitattributes

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Suppress noisy generated files in diffs.
2+
3+
# Dart files generated from the files next to them:
4+
*.g.dart -diff
5+
6+
# On the other hand, keep diffs for pubspec.lock. It contains
7+
# information independent of any non-generated file in the tree.
8+
# And thankfully it's much less verbose than, say, a yarn.lock.
9+
#pubspec.lock -diff

lib/model/database.dart

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import 'dart:io';
2+
3+
import 'package:drift/drift.dart';
4+
import 'package:drift/native.dart';
5+
import 'package:path/path.dart' as path;
6+
import 'package:path_provider/path_provider.dart';
7+
8+
part 'database.g.dart';
9+
10+
// TODO unify with Account in store.dart
11+
class Accounts extends Table {
12+
Column<int> get id => integer().autoIncrement()();
13+
14+
Column<String> get realmUrl => text().map(const UriConverter())();
15+
Column<int> get userId => integer()();
16+
17+
Column<String> get email => text()();
18+
Column<String> get apiKey => text()();
19+
20+
Column<String> get zulipVersion => text()();
21+
Column<String> get zulipMergeBase => text().nullable()();
22+
Column<int> get zulipFeatureLevel => integer()();
23+
24+
@override
25+
List<Set<Column<Object>>> get uniqueKeys => [
26+
{realmUrl, userId},
27+
{realmUrl, email},
28+
];
29+
}
30+
31+
class UriConverter extends TypeConverter<Uri, String> {
32+
const UriConverter();
33+
@override String toSql(Uri value) => value.toString();
34+
@override Uri fromSql(String fromDb) => Uri.parse(fromDb);
35+
}
36+
37+
LazyDatabase _openConnection() {
38+
return LazyDatabase(() async {
39+
// TODO decide if this path is the right one to use
40+
final dbFolder = await getApplicationDocumentsDirectory();
41+
final file = File(path.join(dbFolder.path, 'db.sqlite'));
42+
return NativeDatabase.createInBackground(file);
43+
});
44+
}
45+
46+
@DriftDatabase(tables: [Accounts])
47+
class AppDatabase extends _$AppDatabase {
48+
AppDatabase(QueryExecutor e) : super(e);
49+
50+
AppDatabase.live() : this(_openConnection());
51+
52+
@override
53+
int get schemaVersion => 1; // TODO migrations
54+
55+
Future<int> createAccount(AccountsCompanion values) {
56+
return into(accounts).insert(values);
57+
}
58+
}

0 commit comments

Comments
 (0)