Files
lincodex/backend/db/queries/assessment_signals.sql

79 lines
2.5 KiB
SQL

-- New outcomes share the generic idempotency row and are counted for the
-- attempt's rolling receipt window. Replays bypass this query in the usecase.
-- name: CountRecentAssessmentSignalOutcomes :one
SELECT
count(*)::bigint AS outcome_count,
COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at
FROM assessment_signal_idempotency_outcomes
WHERE
attempt_id = sqlc.arg(attempt_id)
AND received_at > sqlc.arg(since);
-- The attempt row is already locked by the caller. Store a parent before its
-- bounded child events, in the same transaction as the immutable receipt.
-- name: InsertAssessmentSignalBatch :exec
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
VALUES (
sqlc.arg(id),
sqlc.arg(attempt_id),
sqlc.arg(received_at),
sqlc.arg(event_count)
);
-- Each inserted event is checked by the database guard against attempt state
-- and the aggregate capacity as a second line of defense.
-- name: InsertAssessmentSignalEvent :exec
INSERT INTO assessment_signal_events (
batch_id,
attempt_id,
ordinal,
item_instance_id,
kind,
occurred_at,
duration_ms,
size_bytes
) VALUES (
sqlc.arg(batch_id),
sqlc.arg(attempt_id),
sqlc.arg(ordinal),
sqlc.arg(item_instance_id),
sqlc.arg(kind),
sqlc.arg(occurred_at),
sqlc.narg(duration_ms)::integer,
sqlc.narg(size_bytes)::integer
);
-- Count events only for the already owner-locked attempt.
-- name: CountAssessmentSignalEvents :one
SELECT count(*)::bigint AS event_count
FROM assessment_signal_events
WHERE attempt_id = sqlc.arg(attempt_id);
-- The generic reservation has already established that a previous outcome is
-- expired before this child is removed and replaced in the same transaction.
-- name: DeleteExpiredAssessmentSignalOutcome :exec
DELETE FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = sqlc.arg(scope_hash);
-- Save exactly one immutable response receipt for each live idempotency scope.
-- name: InsertAssessmentSignalOutcome :exec
INSERT INTO assessment_signal_idempotency_outcomes (
scope_hash,
attempt_id,
status,
accepted_events,
received_at
) VALUES (
sqlc.arg(scope_hash),
sqlc.arg(attempt_id),
sqlc.arg(status),
sqlc.arg(accepted_events),
sqlc.arg(received_at)
);
-- Read only the receipt associated with the reserved idempotency scope.
-- name: GetAssessmentSignalOutcome :one
SELECT status, accepted_events, received_at
FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = sqlc.arg(scope_hash);