Files
mtusi2026lab5/db/queries/attachments.sql
T

70 lines
2.3 KiB
SQL

-- name: CreateAttachment :one
-- Compatibility for the synchronous API until CreateQueuedAttachment is wired in.
WITH legacy AS (
INSERT INTO attachments
(chat_id, owner_id, filename, object_key, staging_key, content_type, size_bytes, sha256)
VALUES (sqlc.arg(chat_id), sqlc.arg(owner_id), sqlc.arg(filename),
sqlc.arg(object_key)::text, sqlc.arg(object_key)::text,
sqlc.arg(content_type), sqlc.arg(size_bytes), sqlc.arg(sha256))
RETURNING *
), job AS (
INSERT INTO attachment_jobs (attachment_id, pipeline_version)
SELECT id, pipeline_version FROM legacy
RETURNING *
), event AS (
INSERT INTO outbox (job_id, payload, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
'initial/' || id
FROM job
RETURNING job_id
)
SELECT legacy.* FROM legacy CROSS JOIN event;
-- name: GetAttachmentForUser :one
SELECT a.*
FROM attachments AS a
JOIN chat_members AS cm ON cm.chat_id = a.chat_id
WHERE a.id = sqlc.arg(attachment_id)
AND cm.user_id = sqlc.arg(user_id);
-- name: GetAttachmentsForMessages :many
SELECT message_id, attachment_id, position
FROM messages_attachments
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
ORDER BY message_id, position;
-- name: AttachmentExistsByObjectKey :one
SELECT EXISTS (
SELECT 1 FROM attachments
WHERE object_key = sqlc.arg(object_key)::text OR staging_key = sqlc.arg(object_key)::text
UNION ALL
SELECT 1 FROM attachment_variants WHERE object_key = sqlc.arg(object_key)::text
UNION ALL
SELECT 1 FROM attachment_jobs WHERE published_original_key = sqlc.arg(object_key)::text
);
-- name: TryLockAttachmentObjectKey :one
SELECT pg_try_advisory_xact_lock(
hashtextextended(sqlc.arg(object_key)::text, 0)
)::boolean AS locked;
-- name: ListAttachmentKeys :many
SELECT id, object_key, created_at
FROM attachments
WHERE object_key > sqlc.arg(after_key)
ORDER BY object_key
LIMIT sqlc.arg(page_size);
-- name: GetAttachmentByID :one
SELECT * FROM attachments WHERE id = sqlc.arg(attachment_id);
-- name: CreateQueuedAttachment :one
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key, status
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, 'queued'
) RETURNING *;