musicus_mobile/lib/database.dart

103 lines
2.6 KiB
Dart
Raw Normal View History

2019-12-03 12:42:43 +01:00
import 'dart:math';
import 'package:moor/moor.dart';
part 'database.g.dart';
2019-12-03 12:42:43 +01:00
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,
});
}
2020-03-22 16:46:28 +01:00
class PerformanceModel {
final Person person;
final Ensemble ensemble;
final Instrument role;
2020-03-22 16:46:28 +01:00
PerformanceModel({
this.person,
this.ensemble,
this.role,
});
}
@UseMoor(
include: {
'database.moor',
},
)
class Database extends _$Database {
Database.connect(DatabaseConnection connection) : super.connect(connection);
@override
int get schemaVersion => 1;
2020-03-21 15:41:03 +01:00
@override
MigrationStrategy get migration => MigrationStrategy(
beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON');
},
);
2020-03-21 15:41:03 +01:00
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> updateRecording(
2020-03-22 16:46:28 +01:00
Recording recording, List<PerformanceModel> models) async {
await transaction(() async {
await (delete(performances)
..where((p) => p.recording.equals(recording.id)))
.go();
await into(recordings).insert(recording, orReplace: true);
2020-03-22 16:46:28 +01:00
for (final model in models) {
await into(performances).insert(Performance(
recording: recording.id,
2020-03-30 17:33:36 +02:00
person: model.person?.id,
ensemble: model.ensemble?.id,
role: model.role?.id,
2020-03-22 16:46:28 +01:00
));
}
});
}
}