-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathsqlite_serialize.dart
More file actions
385 lines (327 loc) · 14.3 KB
/
Copy pathsqlite_serialize.dart
File metadata and controls
385 lines (327 loc) · 14.3 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:brick_build/generators.dart';
import 'package:brick_core/src/model.dart';
import 'package:brick_sqlite/brick_sqlite.dart';
import 'package:brick_sqlite/db.dart' show InsertForeignKey, InsertTable;
import 'package:brick_sqlite_generators/src/sqlite_serdes_generator.dart';
import 'package:meta/meta.dart';
import 'package:source_gen/source_gen.dart' show InvalidGenerationSourceError;
/// Generate a function to produce a [ClassElement] to SQLite data
class SqliteSerialize<_Model extends SqliteModel> extends SqliteSerdesGenerator<_Model> {
/// Generate a function to produce a [ClassElement] to SQLite data
SqliteSerialize(
super.element,
super.fields, {
required super.repositoryName,
});
@override
final doesDeserialize = false;
///
String? get tableName => element.name;
@override
List<String> get instanceFieldsAndMethods {
final fieldsToColumns = <String>[];
final uniqueFields = <String, String>{};
fieldsToColumns.add('''
'${InsertTable.PRIMARY_KEY_FIELD}': const RuntimeSqliteColumnDefinition(
association: false,
columnName: '${InsertTable.PRIMARY_KEY_COLUMN}',
iterable: false,
type: int,
)''');
for (final field in unignoredFields) {
final annotation = fields.annotationForField(field);
final checker = checkerForType(field.type);
final columnName = providerNameForField(annotation.name, checker: checker);
final columnInsertionType = checker.withoutNullResultType;
// T0D0 support List<Future<Sibling>> for 'association'
fieldsToColumns.add('''
'${field.name}': const RuntimeSqliteColumnDefinition(
association: ${checker.isSibling || (checker.isIterable && checker.isArgTypeASibling)},
columnName: '$columnName',
iterable: ${checker.isIterable},
type: $columnInsertionType,
)''');
if (annotation.unique) {
final value = uniqueValueForField(field.name, checker: checker);
uniqueFields[value] = columnName;
}
}
final primaryKeyByUniqueColumns = generateUniqueSqliteFunction(uniqueFields);
final afterSaveCallbacks = unignoredFields.where((f) {
final checker = checkerForType(f.type);
return checker.isIterable && checker.isArgTypeASibling;
}).map(_saveIterableAssociationFieldToJoins);
return [
'@override\nfinal Map<String, RuntimeSqliteColumnDefinition> fieldsToSqliteColumns = {${fieldsToColumns.join(',\n')}};',
primaryKeyByUniqueColumns,
"@override\nfinal String tableName = '$tableName';",
if (afterSaveCallbacks.isNotEmpty)
"@override\nFuture<void> afterSave(instance, {required provider, repository}) async {${afterSaveCallbacks.join('\n')}}",
];
}
@override
String? coderForField(
FieldElement field,
SharedChecker<Model> checker, {
required bool wrappedInFuture,
required Sqlite fieldAnnotation,
}) {
final name = providerNameForField(fieldAnnotation.name, checker: checker);
final fieldValue = serdesValueForField(field, fieldAnnotation.name!, checker: checker);
if (name == InsertTable.PRIMARY_KEY_COLUMN) {
throw InvalidGenerationSourceError(
'Field named `${InsertTable.PRIMARY_KEY_COLUMN}` conflicts with primary key',
todo: 'Rename the field from ${InsertTable.PRIMARY_KEY_COLUMN}',
element: field,
);
}
if (fieldAnnotation.ignoreTo) return null;
if (fieldAnnotation.columnType != null) {
return fieldValue;
}
// DateTime
if (checker.isDateTime) {
final nullableSuffix = checker.isNullable ? '?' : '';
return '$fieldValue$nullableSuffix.toIso8601String()';
// bool
} else if (checker.isBool) {
return _boolForField(fieldValue, checker.isNullable);
// double, int, num, String
} else if (checker.isDartCoreType) {
return fieldValue;
// Iterable
} else if (checker.isIterable) {
final argTypeChecker = checkerForType(checker.argType);
// Iterable<enum>
if (argTypeChecker.isEnum) {
final nullablePrefix = checker.isNullable ? '?' : '';
final nullableDefault = checker.isNullable ? ' ?? []' : '';
final serializeMethod = argTypeChecker.enumSerializeMethod(providerName);
final serializedValue = serializeMethod != null
? 's.$serializeMethod()'
: fieldAnnotation.enumAsString
? 's.name'
: '${SharedChecker.withoutNullability(checker.argType)}.values.indexOf(s)';
return '''
jsonEncode($fieldValue$nullablePrefix.map((s) =>
$serializedValue
).toList()$nullableDefault)
''';
}
// Iterable<Future<bool>>, Iterable<Future<DateTime>>, Iterable<Future<double>>,
// Iterable<Future<int>>, Iterable<Future<num>>, Iterable<Future<String>>, Iterable<Future<Map>>
if (checker.isArgTypeAFuture) {
if (checker.isSerializable && !checker.isArgTypeASibling) {
// Iterable<Future<bool>>
final wrappedValue =
checker.isBool ? _boolForField(fieldValue, fieldAnnotation.nullable) : fieldValue;
return 'jsonEncode(await Future.wait<${argTypeChecker.unFuturedArgType}>($wrappedValue) ?? [])';
}
}
// Set<any>
// jsonEncode can't convert LinkedHashSet
if (checker.isSet && !checker.isArgTypeASibling) {
return checker.isNullable
? '$fieldValue == null ? null : jsonEncode($fieldValue.toList())'
: 'jsonEncode($fieldValue.toList())';
}
// Iterable<bool>
if (argTypeChecker.isBool) {
return 'jsonEncode($fieldValue.map((b) => ${_boolForField('b', fieldAnnotation.nullable)}).toList())';
}
// Iterable<DateTime>, Iterable<double>, Iterable<int>, Iterable<num>, Iterable<String>, Iterable<Map>
if (argTypeChecker.isDartCoreType || argTypeChecker.isMap) {
return checker.isNullable
? '$fieldValue == null ? null : jsonEncode($fieldValue)'
: 'jsonEncode($fieldValue)';
}
// Iterable<toJson>
if (argTypeChecker.toJsonMethod != null) {
final serializedValue = 'jsonEncode($fieldValue)';
return checker.isNullable
? '$fieldValue != null ? $serializedValue : null'
: serializedValue;
}
// SqliteModel, Future<SqliteModel>
} else if (checker.isSibling) {
final instance = wrappedInFuture ? '(await $fieldValue)' : fieldValue;
final nullabilitySuffix = checker.isUnFuturedTypeNullable || checker.isNullable ? '!' : '';
final upsertMethod = '''
$instance$nullabilitySuffix.${InsertTable.PRIMARY_KEY_FIELD} ??
await provider.upsert<${SharedChecker.withoutNullability(checker.unFuturedType)}>(
$instance$nullabilitySuffix, repository: repository
)''';
if (checker.isUnFuturedTypeNullable) {
return '$instance != null ? $upsertMethod : null';
}
return upsertMethod;
// enum
} else if (checker.isEnum) {
final nullabilitySuffix = checker.isNullable ? '?' : '';
final serializeMethod = checker.enumSerializeMethod(providerName);
if (serializeMethod != null) {
return '$fieldValue$nullabilitySuffix.$serializeMethod()';
}
if (fieldAnnotation.enumAsString) {
return '$fieldValue$nullabilitySuffix.name';
}
if (checker.isNullable) {
return '$fieldValue != null ? ${SharedChecker.withoutNullability(field.type)}.values.indexOf($fieldValue!) : null';
}
return '${SharedChecker.withoutNullability(field.type)}.values.indexOf($fieldValue)';
// Map
} else if (checker.isMap) {
if (checker.isNullable) {
return '$fieldValue != null ? jsonEncode($fieldValue) : null';
}
return 'jsonEncode($fieldValue)';
} else if (checker.toJsonMethod != null) {
final nullableSuffix = checker.isNullable ? '!' : '';
final output = 'jsonEncode($fieldValue$nullableSuffix.toJson())';
if (checker.isNullable) {
return '$fieldValue != null ? $output : null';
}
return output;
}
return null;
}
/// Generates the method `primaryKeyByUniqueColumns` for the adapter
@protected
@mustCallSuper
String generateUniqueSqliteFunction(Map<String, String> uniqueFields) {
final functionDeclaration =
'@override\nFuture<int?> primaryKeyByUniqueColumns(${element.name} instance, DatabaseExecutor executor) async';
if (uniqueFields.isEmpty) {
return '$functionDeclaration => instance.primaryKey;';
}
return """$functionDeclaration {
final where = <String>[];
final args = <Object?>[];
final fields = <String, Object?>{
${uniqueFields.entries.map((e) => "'${e.value}': instance.${e.key}").join(',\n ')}
};
for (final entry in fields.entries) {
if (entry.value != null) {
where.add('\${entry.key} = ?');
args.add(entry.value);
}
}
if (where.isEmpty) {
return null;
}
final results = await executor.rawQuery(
'SELECT * FROM `$tableName` WHERE ' + where.join(' OR ') + ' LIMIT 1',
args,
);
// SQFlite returns [{}] when no results are found
if (results.isEmpty || (results.length == 1 && results.first.isEmpty)) {
return null;
}
return results.first['${InsertTable.PRIMARY_KEY_COLUMN}'] as int;
}""";
}
@override
bool ignoreCoderForField(FieldElement field, Sqlite annotation, SharedChecker<Model> checker) {
if (annotation.columnType != null) return false;
return super.ignoreCoderForField(field, annotation, checker);
}
String _saveIterableAssociationFieldToJoins(FieldElement field) {
final annotation = fields.annotationForField(field);
var checker = checkerForType(field.type);
final fieldValue = serdesValueForField(field, annotation.name!, checker: checker);
final wrappedInFuture = checker.isFuture;
if (wrappedInFuture) {
checker = checkerForType(checker.argType);
}
final joinsTable = InsertForeignKey.joinsTableName(
annotation.name!,
localTableName: fields.element.name!,
);
final joinsForeignColumn = InsertForeignKey.joinsTableForeignColumnName(
SharedChecker.withoutNullability(checker.unFuturedArgType),
);
final joinsLocalColumn = InsertForeignKey.joinsTableLocalColumnName(fields.element.name!);
// Iterable<Future<SqliteModel>>
final insertStatement =
'INSERT OR IGNORE INTO `$joinsTable` (`$joinsLocalColumn`, `$joinsForeignColumn`)';
var siblingAssociations = fieldValue;
var upsertMethod =
'(await s).${InsertTable.PRIMARY_KEY_FIELD} ?? await provider.upsert<${SharedChecker.withoutNullability(checker.unFuturedArgType)}>((await s), repository: repository)';
// Iterable<SqliteModel>
if (!checker.isArgTypeAFuture) {
siblingAssociations = wrappedInFuture ? '(await $fieldValue)' : fieldValue;
upsertMethod =
's.${InsertTable.PRIMARY_KEY_FIELD} ?? await provider.upsert<${SharedChecker.withoutNullability(checker.unFuturedArgType)}>(s, repository: repository)';
}
final removeStaleAssociations = field.isPublic
? _removeStaleAssociations(
field.name!,
joinsForeignColumn,
joinsLocalColumn,
joinsTable,
siblingAssociations,
checker.isUnFuturedTypeNullable,
checker.unFuturedArgType.nullabilitySuffix != NullabilitySuffix.none,
)
: '';
final nullabilitySuffix = checker.isNullable ? '?' : '';
final nullabilityDefault = checker.isNullable ? ' ?? []' : '';
return '''
if (instance.${InsertTable.PRIMARY_KEY_FIELD} != null) {
$removeStaleAssociations
await Future.wait<int?>($siblingAssociations$nullabilitySuffix.map((s) async {
final id = $upsertMethod;
return await provider.rawInsert('$insertStatement VALUES (?, ?)', [instance.${InsertTable.PRIMARY_KEY_FIELD}, id]);
})$nullabilityDefault);
}
''';
}
String _boolForField(String fieldValue, bool nullable) {
if (nullable) {
return '$fieldValue == null ? null : ($fieldValue! ? 1 : 0)';
}
return '$fieldValue ? 1 : 0';
}
/// Provides the value for the SQL lookup. Most often this is simply the field
/// name, but more complex use cases may require a specific property to be called
/// on the class itself.
///
/// However, it is strongly, strongly discouraged to use anything more than a primitive
/// for unique values. A complex class with multiple fields and methods will significantly
/// confuse maintenance. A string or int or double is more than sufficient to determine
/// a row's uniqueness.
@protected
String uniqueValueForField(String? fieldName, {required SharedChecker checker}) {
return fieldName ?? '';
}
}
String _removeStaleAssociations(
String fieldName,
String joinsForeignColumn,
String joinsLocalColumn,
String joinsTable,
String siblingAssociations,
/// `true` when `Iterable<Model>` is `Iterable<Model>?`
bool nullableField,
/// `true` when `<Model>` in `Iterable<Model>` is `Iterable<Model?>`
bool nullableArgType,
) {
final argTypeNullabilitySuffix = nullableArgType ? '?' : '';
var newIdFieldsValue =
'$siblingAssociations.map((s) => s$argTypeNullabilitySuffix.${InsertTable.PRIMARY_KEY_FIELD}).whereType<int>()';
if (nullableField) {
newIdFieldsValue =
'$siblingAssociations?.map((s) => s$argTypeNullabilitySuffix.${InsertTable.PRIMARY_KEY_FIELD}).whereType<int>() ?? []';
}
return '''
final ${fieldName}OldColumns = await provider.rawQuery('SELECT `$joinsForeignColumn` FROM `$joinsTable` WHERE `$joinsLocalColumn` = ?', [instance.${InsertTable.PRIMARY_KEY_FIELD}]);
final ${fieldName}OldIds = ${fieldName}OldColumns.map((a) => a['$joinsForeignColumn']);
final ${fieldName}NewIds = $newIdFieldsValue;
final ${fieldName}IdsToDelete = ${fieldName}OldIds.where((id) => !${fieldName}NewIds.contains(id));
await Future.wait<void>(${fieldName}IdsToDelete.map((id) async {
return await provider.rawExecute('DELETE FROM `$joinsTable` WHERE `$joinsLocalColumn` = ? AND `$joinsForeignColumn` = ?', [instance.${InsertTable.PRIMARY_KEY_FIELD}, id]).catchError((e) => null);
}));
''';
}