-- name: CreateAttachment :one INSERT INTO attachments ( id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, error_code ) SELECT sqlc.arg(id)::uuid, sqlc.arg(chat_id)::uuid, sqlc.arg(owner_id)::uuid, sqlc.arg(s3_key)::text, sqlc.arg(filename)::text, sqlc.arg(content_type)::attachment_content_type, sqlc.arg(size_bytes)::int, sqlc.arg(sha256)::text, NULLIF(sqlc.arg(error_code)::text, '') WHERE EXISTS ( SELECT 1 FROM chat_members WHERE chat_id = sqlc.arg(chat_id) AND user_id = sqlc.arg(owner_id) ) RETURNING *; -- name: CreateMessageAttachment :exec INSERT INTO message_attachments ( message_id, attachment_id, position ) VALUES ( sqlc.arg(message_id), sqlc.arg(attachment_id), sqlc.arg(position) ); -- name: GetAttachmentByID :one SELECT * FROM attachments WHERE id = $1::uuid; -- name: ListAttachmentsByIDs :many SELECT status FROM attachments WHERE chat_id = sqlc.arg(chat_id)::uuid AND id = ANY(sqlc.arg(ids)::uuid[]); -- name: ListMessageAttachmentIDs :many SELECT attachment_id FROM message_attachments WHERE message_id = sqlc.arg(message_id)::uuid ORDER BY position; -- name: ListMessageAttachmentsByMessageIDs :many SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[]) ORDER BY message_id, position; -- name: ListStaleAttachmentUploads :many SELECT id, s3_key FROM attachments WHERE status = 'queued' AND created_at < sqlc.arg(cutoff)::timestamptz; -- name: ListAttachmentsForReconcile :many SELECT a.id, a.s3_key, a.status, a.size_bytes, a.created_at, EXISTS ( SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id ) AS referenced FROM attachments a; -- name: MarkAttachmentFailedIfReady :execrows UPDATE attachments SET status = 'failed', error_code = sqlc.arg(error_code)::text, updated_at = now() WHERE id = sqlc.arg(id)::uuid AND status = 'ready'; -- name: MarkAttachmentReady :one UPDATE attachments SET status = 'ready', updated_at = now() WHERE id = $1::uuid RETURNING *; -- name: DeleteQueuedAttachment :execrows DELETE FROM attachments WHERE id = sqlc.arg(id)::uuid AND status = 'queued';