musicus_mobile/lib/database.dart
Elias Projahn 7f783bd016 Database: Fix worksByComposer
While the previous code was indeed valid SQL is wasn't the best way to
do this. Also, only works with parts where included in the result set.
This is fixed now. Some optimization may still be neccessary.
2020-03-22 16:31:38 +01:00

89 lines
2.3 KiB
Dart

import 'dart:math';
import 'package:moor_flutter/moor_flutter.dart';
part 'database.g.dart';
final _random = Random(DateTime.now().millisecondsSinceEpoch);
int generateId() => _random.nextInt(0xFFFFFFFF);
class WorkModel {
final Work work;
final List<int> instrumentIds;
WorkModel({
@required this.work,
@required this.instrumentIds,
});
}
@UseMoor(
include: {
'database.moor',
},
)
class Database extends _$Database {
Database(String fileName)
: super(FlutterQueryExecutor.inDatabaseFolder(path: fileName));
@override
int get schemaVersion => 1;
@override
MigrationStrategy get migration =>
MigrationStrategy(beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON');
});
Future<void> updatePerson(Person person) async {
await into(persons).insert(person, orReplace: true);
}
Future<void> updateInstrument(Instrument instrument) async {
await into(instruments).insert(instrument, orReplace: true);
}
Future<void> updateWork(WorkModel model, List<WorkModel> parts) async {
await transaction(() async {
final workId = model.work.id;
await (delete(works)..where((w) => w.id.equals(workId))).go();
await (delete(works)..where((w) => w.partOf.equals(workId))).go();
Future<void> insertWork(WorkModel model) async {
await into(works).insert(model.work);
await batch((b) => b.insertAll(
instrumentations,
model.instrumentIds
.map((id) =>
Instrumentation(work: model.work.id, instrument: id))
.toList()));
}
await insertWork(model);
for (final part in parts) {
await insertWork(part);
}
});
}
Future<void> updateEnsemble(Ensemble ensemble) async {
await into(ensembles).insert(ensemble, orReplace: true);
}
Future<void> updateRole(Role role) async {
await into(roles).insert(role, orReplace: true);
}
Future<void> updateRecording(
Recording recording, List<Performance> perfs) async {
await transaction(() async {
await (delete(performances)
..where((p) => p.recording.equals(recording.id)))
.go();
await into(recordings).insert(recording, orReplace: true);
for (final perf in perfs) {
await into(performances).insert(perf);
}
});
}
}