-
Notifications
You must be signed in to change notification settings - Fork 365
/
database.dart
192 lines (156 loc) · 5.66 KB
/
database.dart
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import 'dart:convert';
import 'package:drift/drift.dart';
import 'package:json_annotation/json_annotation.dart' as j;
import '../data/sample_data.dart' as people;
part 'database.g.dart';
class Users extends Table {
/// The user id
IntColumn get id => integer().autoIncrement()();
// The user name
TextColumn get name => text()();
/// The users birth date
///
/// Mapped from json `born_on`
@JsonKey('born_on')
DateTimeColumn get birthDate => dateTime()();
BlobColumn get profilePicture => blob().nullable()();
TextColumn get preferences =>
text().map(const PreferenceConverter()).nullable()();
}
class Friendships extends Table {
IntColumn get firstUser => integer()();
IntColumn get secondUser => integer()();
BoolColumn get reallyGoodFriends =>
boolean().withDefault(const Constant(false))();
@override
Set<Column> get primaryKey => {firstUser, secondUser};
}
@j.JsonSerializable()
class Preferences {
bool receiveEmails;
Preferences(this.receiveEmails);
factory Preferences.fromJson(Map<String, dynamic> json) =>
_$PreferencesFromJson(json);
Map<String, dynamic> toJson() => _$PreferencesToJson(this);
}
class PreferenceConverter extends NullAwareTypeConverter<Preferences, String> {
const PreferenceConverter();
@override
Preferences requireFromSql(String fromDb) {
return Preferences.fromJson(json.decode(fromDb) as Map<String, dynamic>);
}
@override
String requireToSql(Preferences value) {
return json.encode(value.toJson());
}
}
@DriftDatabase(
tables: [Users, Friendships],
queries: {
'mostPopularUsers': 'SELECT * FROM users u '
'ORDER BY (SELECT COUNT(*) FROM friendships '
'WHERE first_user = u.id OR second_user = u.id) DESC LIMIT :amount',
'amountOfGoodFriends': 'SELECT COUNT(*) FROM friendships f WHERE '
'f.really_good_friends = TRUE AND '
'(f.first_user = :user OR f.second_user = :user)',
'friendshipsOf': ''' SELECT
f.really_good_friends, "user".**
FROM friendships f
INNER JOIN users "user" ON "user".id IN (f.first_user, f.second_user) AND
"user".id != :user
WHERE (f.first_user = :user OR f.second_user = :user)''',
'userCount': 'SELECT COUNT(id) FROM users',
'settingsFor': 'SELECT preferences FROM users WHERE id = :user',
'usersById': 'SELECT * FROM users WHERE id IN ?',
'returning': 'INSERT INTO friendships VALUES (?, ?, ?) RETURNING *;',
},
)
class Database extends _$Database {
/// We make the schema version configurable to test migrations
@override
final int schemaVersion;
Database(DatabaseConnection e, {this.schemaVersion = 2}) : super(e);
Database.executor(QueryExecutor db) : this(DatabaseConnection(db));
/// It will be set in the onUpgrade callback. Null if no migration occurred
int? schemaVersionChangedFrom;
/// It will be set in the onUpgrade callback. Null if no migration occurred
int? schemaVersionChangedTo;
MigrationStrategy? overrideMigration;
@override
MigrationStrategy get migration {
return overrideMigration ??
MigrationStrategy(
onCreate: (m) async {
await m.createTable(users);
if (schemaVersion >= 2) {
// ensure that transactions can be used in a migration callback.
await transaction(() async {
await m.createTable(friendships);
});
}
},
onUpgrade: (m, from, to) async {
schemaVersionChangedFrom = from;
schemaVersionChangedTo = to;
if (from == 1) {
await m.createTable(friendships);
}
},
beforeOpen: (details) async {
if (details.wasCreated) {
// make sure that transactions can be used in the beforeOpen callback.
await transaction(() async {
await batch((batch) {
batch.insertAll(
users, [people.dash, people.duke, people.gopher]);
});
});
}
},
);
}
Future<void> deleteUser(User user, {bool fail = false}) {
return transaction(() async {
final id = user.id;
await (delete(friendships)
..where((f) => f.firstUser.equals(id) | f.secondUser.equals(id)))
.go();
if (fail) {
throw Exception('oh no, the query misteriously failed!');
}
await delete(users).delete(user);
});
}
Stream<User> watchUserById(int id) {
return (select(users)..where((u) => u.id.equals(id))).watchSingle();
}
Future<User> getUserById(int id) {
return (select(users)..where((u) => u.id.equals(id))).getSingle();
}
Future<int> writeUser(Insertable<User> user) {
return into(users).insert(user);
}
Selectable<User> friendsOf(int id) => friendshipsOf(id).map((r) => r.user);
Future<void> makeFriends(User a, User b, {bool? goodFriends}) async {
var friendsValue = const Value<bool>.absent();
if (goodFriends != null) {
friendsValue = Value(goodFriends);
}
final companion = FriendshipsCompanion(
firstUser: Value(a.id),
secondUser: Value(b.id),
reallyGoodFriends: friendsValue,
);
if (connection.executor.dialect == SqlDialect.sqlite) {
await into(friendships)
.insert(companion, mode: InsertMode.insertOrReplace);
} else if (connection.executor.dialect == SqlDialect.postgres) {
await into(friendships)
.insert(companion, mode: InsertMode.insertOrIgnore);
}
}
Future<void> updateSettings(int userId, Preferences c) async {
await (update(users)..where((u) => u.id.equals(userId)))
.write(UsersCompanion(preferences: Value(c)));
}
}