mnemo_cards/mnemo_cards_backend/lib/database/daos/test_dao.dart
Dmitry 2a4b3ecc4e
Some checks failed
Backend CI / test (push) Waiting to run
Backend CI / build (push) Blocked by required conditions
Deploy Mnemo Cards / Deploy Backend (push) Waiting to run
Deploy Mnemo Cards / Deploy Web App (push) Blocked by required conditions
Deploy Mnemo Cards / Final Verification (push) Blocked by required conditions
Web App CI / test (push) Has been cancelled
Web App CI / build (push) Has been cancelled
test
2026-01-24 18:18:58 +03:00

234 lines
7.9 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:drift/drift.dart';
import 'package:drift_postgres/drift_postgres.dart';
import '../database.dart';
import '../tables/tests.dart';
part 'test_dao.g.dart';
@DriftAccessor(
tables: [Tests, TestQuestions, TestPackRelations, TestStatistics],
)
class TestDao extends DatabaseAccessor<AppDatabase> with _$TestDaoMixin {
TestDao(super.db);
// ==================== Tests ====================
/// Получить тест по ID (включая soft-deleted для доступа по прямой ссылке)
///
/// Примечание: soft-deleted тесты не показываются в списке пака (getTestsByPackId),
/// но доступны по прямой ссылке для завершения начатых тестов.
Future<Test?> getTestById(String id) {
return (select(tests)..where((t) => t.id.equals(id))).getSingleOrNull();
}
/// Получить все тесты (только активные)
Future<List<Test>> getAllTests() {
return (select(tests)..where((t) => t.isDeleted.equals(false))).get();
}
/// Получить тесты пака (только активные)
Future<List<Test>> getTestsByPackId(String packId) async {
final query = select(tests).join([
innerJoin(
testPackRelations,
testPackRelations.testId.equalsExp(tests.id) &
testPackRelations.packId.equals(packId),
),
])..where(tests.isDeleted.equals(false));
return query.map((row) => row.readTable(tests)).get();
}
/// Создать тест
Future<String> createTest(TestsCompanion test) async {
final inserted = await into(tests).insertReturning(test);
return inserted.id;
}
/// Обновить тест
Future<bool> updateTest(Test test) {
return update(tests).replace(test);
}
/// Удалить тест (soft delete)
Future<void> softDeleteTest(String testId) {
return (update(tests)..where((t) => t.id.equals(testId))).write(
TestsCompanion(
isDeleted: const Value(true),
deletedAt: Value(PgDateTime(DateTime.now())),
updatedAt: Value(PgDateTime(DateTime.now())),
),
);
}
/// Soft delete tests that have expired (expiresAt <= now)
///
/// When expiresAt is reached, test becomes soft-deleted (available only by direct link)
Future<int> softDeleteExpiredTests() async {
final now = DateTime.now();
final expiredTests = await (select(tests)..where(
(t) =>
t.expiresAt.isSmallerOrEqualValue(PgDateTime(now)) &
t.isDeleted.equals(false),
))
.get();
var deleted = 0;
for (final test in expiredTests) {
await softDeleteTest(test.id);
deleted++;
}
return deleted;
}
/// Hard delete old generated tests that were soft-deleted.
///
/// This is important because we use soft delete for regular operations,
/// but generated tests are ephemeral and otherwise will accumulate in DB
/// (along with their questions/stats). Hard delete triggers FK cascades.
///
/// Hard deletes tests that were soft-deleted more than [olderThan] ago.
Future<int> hardDeleteOldSoftDeletedGeneratedTests({
required Duration olderThan,
}) async {
final threshold = DateTime.now().subtract(olderThan);
final toDelete =
await (select(tests)..where(
(t) =>
t.isDeleted.equals(true) &
t.version.equals('generated') &
t.deletedAt.isSmallerThanValue(PgDateTime(threshold)),
))
.get();
var deleted = 0;
for (final test in toDelete) {
deleted += await (delete(tests)..where((t) => t.id.equals(test.id))).go();
}
return deleted;
}
/// Hard delete generated tests that are not linked to any pack.
///
/// These tests are unreachable from the product (no pack relation) and
/// should not accumulate forever. This also cleans up historical leftovers
/// from the earlier bug where generated tests were created but not linked.
Future<int> hardDeleteOrphanGeneratedTests({
required Duration olderThan,
}) async {
final threshold = DateTime.now().subtract(olderThan);
final rows =
await (select(tests).join([
leftOuterJoin(
testPackRelations,
testPackRelations.testId.equalsExp(tests.id),
),
])..where(
tests.version.equals('generated') &
tests.createdAt.isSmallerThanValue(PgDateTime(threshold)) &
testPackRelations.testId.isNull(),
))
.get();
final orphanTests = rows.map((r) => r.readTable(tests)).toList();
var deleted = 0;
for (final test in orphanTests) {
deleted += await (delete(tests)..where((t) => t.id.equals(test.id))).go();
}
return deleted;
}
/// Связать тест с паком
Future<void> linkTestToPack(String testId, String packId) async {
await into(testPackRelations).insert(
TestPackRelationsCompanion.insert(testId: testId, packId: packId),
mode: InsertMode.insertOrIgnore,
);
}
/// Удалить связь теста с паком
Future<void> unlinkTestFromPack(String testId, String packId) async {
await (delete(testPackRelations)..where(
(tpr) => tpr.testId.equals(testId) & tpr.packId.equals(packId),
))
.go();
}
/// Получить packId для теста
Future<String?> getPackIdForTest(String testId) async {
final relation =
await (select(testPackRelations)
..where((tpr) => tpr.testId.equals(testId))
..limit(1))
.getSingleOrNull();
return relation?.packId;
}
/// Получить все packId для теста
Future<List<String>> getPackIdsForTest(String testId) async {
final relations = await (select(
testPackRelations,
)..where((tpr) => tpr.testId.equals(testId))).get();
return relations.map((r) => r.packId).toList();
}
// ==================== TestQuestions ====================
/// Получить вопросы теста (только активные, отсортированные по orderIndex)
Future<List<TestQuestion>> getTestQuestions(String testId) {
return (select(testQuestions)
..where((tq) => tq.testId.equals(testId) & tq.isDeleted.equals(false))
..orderBy([(tq) => OrderingTerm(expression: tq.orderIndex)]))
.get();
}
/// Создать вопрос теста
Future<String> createTestQuestion(TestQuestionsCompanion question) async {
final inserted = await into(testQuestions).insertReturning(question);
return inserted.id;
}
/// Обновить вопрос теста
Future<bool> updateTestQuestion(TestQuestion question) {
return update(testQuestions).replace(question);
}
/// Удалить вопрос теста (soft delete)
Future<void> softDeleteTestQuestion(String questionId) {
return (update(
testQuestions,
)..where((tq) => tq.id.equals(questionId))).write(
TestQuestionsCompanion(
isDeleted: const Value(true),
deletedAt: Value(PgDateTime(DateTime.now())),
updatedAt: Value(PgDateTime(DateTime.now())),
),
);
}
// ==================== TestStatistics ====================
/// Получить статистику теста пользователя
Future<TestStatistic?> getTestStatistics(String userId, String testId) {
return (select(testStatistics)
..where((ts) => ts.userId.equals(userId) & ts.testId.equals(testId)))
.getSingleOrNull();
}
/// Создать статистику теста
Future<String> createTestStatistics(
TestStatisticsCompanion statistics,
) async {
final inserted = await into(testStatistics).insertReturning(statistics);
return inserted.id;
}
/// Обновить статистику теста
Future<bool> updateTestStatistics(TestStatistic statistics) {
return update(testStatistics).replace(statistics);
}
}