import { bigint, check, index, jsonb, pgEnum, pgTable, text, timestamp, uniqueIndex, } from "drizzle-orm/pg-core"; import { uuidv7WithDefault } from "../helpers.ts"; import { and, isNotNull, or, sql } from "drizzle-orm"; export const actionEnum = pgEnum("raw_action", ["create", "update", "delete"]); export const rawRecords = pgTable( "raw_records", { id: uuidv7WithDefault().primaryKey(), tap_id: bigint({ mode: "bigint" }).notNull(), received_at: timestamp({ withTimezone: true }).notNull().defaultNow(), did: text().notNull(), rev: text().notNull(), collection: text().notNull(), rkey: text().notNull(), action: actionEnum().notNull(), cid: text(), // nullable on deletes record: jsonb(), // nullable on deletes }, (table) => [ uniqueIndex().on(table.did, table.collection, table.rkey, table.rev), check( "raw_records_not_null_unless_delete", or(sql`${table.action} = 'delete'`, and(isNotNull(table.cid), isNotNull(table.record)))!, ), index().on(table.collection), ], );