-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwatch_shared_test.dart
260 lines (212 loc) · 8.29 KB
/
watch_shared_test.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
@TestOn('!browser')
// TODO watched query tests on web
// require a forked version of Drift's worker
// The forked version is not published yet.
import 'dart:async';
import 'dart:math';
import 'package:sqlite_async/sqlite_async.dart';
import 'package:sqlite_async/src/utils/shared_utils.dart';
import 'package:test/test.dart';
import 'utils/test_utils_impl.dart';
final testUtils = TestUtils();
createTables(SqliteDatabase db) async {
await db.writeTransaction((tx) async {
await tx.execute(
'CREATE TABLE assets(id INTEGER PRIMARY KEY AUTOINCREMENT, make TEXT, customer_id INTEGER)');
await tx.execute('CREATE INDEX assets_customer ON assets(customer_id)');
await tx.execute(
'CREATE TABLE customers(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
await tx.execute(
'CREATE TABLE other_customers(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
await tx.execute('CREATE VIEW assets_alias AS SELECT * FROM assets');
});
}
void main() {
group('Query Watch Tests', () {
late String path;
List<String> sqlitePaths = [];
setUp(() async {
path = testUtils.dbPath();
sqlitePaths = testUtils.findSqliteLibraries();
await testUtils.cleanDb(path: path);
});
for (var sqlite in sqlitePaths) {
test('getSourceTables - $sqlite', () async {
final db = SqliteDatabase.withFactory(
await testUtils.testFactory(path: path, sqlitePath: sqlite));
await db.initialize();
await createTables(db);
var versionRow = await db.get('SELECT sqlite_version() as version');
print('Testing SQLite ${versionRow['version']} - $sqlite');
final tables = await getSourceTables(db,
'SELECT * FROM assets INNER JOIN customers ON assets.customer_id = customers.id');
expect(tables, equals({'assets', 'customers'}));
final tables2 = await getSourceTables(db,
'SELECT count() FROM assets INNER JOIN "other_customers" AS oc ON assets.customer_id = oc.id AND assets.make = oc.name');
expect(tables2, equals({'assets', 'other_customers'}));
final tables3 = await getSourceTables(db, 'SELECT count() FROM assets');
expect(tables3, equals({'assets'}));
final tables4 =
await getSourceTables(db, 'SELECT count() FROM assets_alias');
expect(tables4, equals({'assets'}));
final tables5 =
await getSourceTables(db, 'SELECT sqlite_version() as version');
expect(tables5, equals(<String>{}));
});
}
test('watch', () async {
final db = await testUtils.setupDatabase(path: path);
await createTables(db);
const baseTime = 20;
const throttleDuration = Duration(milliseconds: baseTime);
final stream = db.watch(
'SELECT count() AS count FROM assets INNER JOIN customers ON customers.id = assets.customer_id',
throttle: throttleDuration);
final rows = await db.execute(
'INSERT INTO customers(name) VALUES (?) RETURNING id',
['a customer']);
final id = rows[0]['id'];
var done = false;
inserts() async {
while (!done) {
await db.execute(
'INSERT INTO assets(make, customer_id) VALUES (?, ?)',
['test', id]);
await Future.delayed(
Duration(milliseconds: Random().nextInt(baseTime * 2)));
}
}
const numberOfQueries = 10;
inserts();
try {
List<DateTime> times = [];
final results = await stream.take(numberOfQueries).map((e) {
times.add(DateTime.now());
return e;
}).toList();
var lastCount = 0;
for (var r in results) {
final count = r.first['count'];
// This is not strictly incrementing, since we can't guarantee the
// exact order between reads and writes.
// We can guarantee that there will always be a read after the last write,
// but the previous read may have been after the same write in some cases.
expect(count, greaterThanOrEqualTo(lastCount));
lastCount = count;
}
// The number of read queries must not be greater than the number of writes overall.
expect(numberOfQueries, lessThanOrEqualTo(results.last.first['count']));
DateTime? lastTime;
for (var r in times) {
if (lastTime != null) {
var diff = r.difference(lastTime);
expect(diff, greaterThanOrEqualTo(throttleDuration));
}
lastTime = r;
}
} finally {
done = true;
}
});
test('onChange', () async {
final db = await testUtils.setupDatabase(path: path);
await createTables(db);
const baseTime = 20;
const throttleDuration = Duration(milliseconds: baseTime);
var done = false;
inserts() async {
while (!done) {
await db.execute('INSERT INTO assets(make) VALUES (?)', ['test']);
await Future.delayed(
Duration(milliseconds: Random().nextInt(baseTime)));
}
}
inserts();
final stream = db.onChange({'assets', 'customers'},
throttle: throttleDuration).asyncMap((event) async {
// This is where queries would typically be executed
return event;
});
var events = await stream.take(3).toList();
done = true;
expect(
events,
equals([
UpdateNotification.empty(),
UpdateNotification.single('assets'),
UpdateNotification.single('assets')
]));
});
test('single onChange', () async {
final db = await testUtils.setupDatabase(path: path);
await createTables(db);
const baseTime = 20;
const throttleDuration = Duration(milliseconds: baseTime);
final stream = db.onChange({'assets', 'customers'},
throttle: throttleDuration,
triggerImmediately: false).asyncMap((event) async {
// This is where queries would typically be executed
return event;
});
var eventsFuture = stream.take(1).toList();
await db.execute('INSERT INTO assets(make) VALUES (?)', ['test']);
var events = await eventsFuture;
expect(events, equals([UpdateNotification.single('assets')]));
});
test('watch with parameters', () async {
final db = await testUtils.setupDatabase(path: path);
await createTables(db);
const baseTime = 20;
const throttleDuration = Duration(milliseconds: baseTime);
final rows = await db.execute(
'INSERT INTO customers(name) VALUES (?) RETURNING id',
['a customer']);
final id = rows[0]['id'];
final stream = db.watch(
'SELECT count() AS count FROM assets WHERE customer_id = ?',
parameters: [id],
throttle: throttleDuration);
var done = false;
inserts() async {
while (!done) {
await db.execute(
'INSERT INTO assets(make, customer_id) VALUES (?, ?)',
['test', id]);
await Future.delayed(
Duration(milliseconds: Random().nextInt(baseTime * 2)));
}
}
const numberOfQueries = 10;
inserts();
try {
List<DateTime> times = [];
final results = await stream.take(numberOfQueries).map((e) {
times.add(DateTime.now());
return e;
}).toList();
var lastCount = 0;
for (var r in results) {
final count = r.first['count'];
// This is not strictly incrementing, since we can't guarantee the
// exact order between reads and writes.
// We can guarantee that there will always be a read after the last write,
// but the previous read may have been after the same write in some cases.
expect(count, greaterThanOrEqualTo(lastCount));
lastCount = count;
}
// The number of read queries must not be greater than the number of writes overall.
expect(numberOfQueries, lessThanOrEqualTo(results.last.first['count']));
DateTime? lastTime;
for (var r in times) {
if (lastTime != null) {
var diff = r.difference(lastTime);
expect(diff, greaterThanOrEqualTo(throttleDuration));
}
lastTime = r;
}
} finally {
done = true;
}
});
});
}