import { and, eq, inArray } from 'drizzle-orm' import { db } from '../db/db_index' import { uploadUrlStatus } from '../db/schema' export async function createUploadUrlStatus(key: string): Promise { await db.insert(uploadUrlStatus).values({ key, status: 'pending', }) } export async function claimUploadUrlStatus(key: string): Promise { const result = await db .update(uploadUrlStatus) .set({ status: 'claimed' }) .where(and(eq(uploadUrlStatus.key, key), eq(uploadUrlStatus.status, 'pending'))) .returning() return result.length > 0 } /** * Of the given keys, the ones that still exist with status 'pending' — i.e. uploads that * were issued by the app and have not been attached to anything yet. Callers use this to * reject unknown/reused upload URLs *before* writing rows that would otherwise be orphaned * when the later claim fails. */ export async function getPendingUploadUrlKeys(keys: string[]): Promise { const unique = [...new Set(keys.filter(Boolean))] if (unique.length === 0) { return [] } const rows = await db .select({ key: uploadUrlStatus.key }) .from(uploadUrlStatus) .where(and(inArray(uploadUrlStatus.key, unique), eq(uploadUrlStatus.status, 'pending'))) return rows.map((row) => row.key) }