DrizzleとSQLite (d1) で条件付きユニーク制約
投稿日: 2025/07/03
例えば、あるpostレコードに紐づくpost contents一覧の中で、is_current == trueなカラムは1つまでに制限したい。
export const postContents = t.sqliteTable( "post_contents", { id: t.text().primaryKey(), postId: t .text("post_id") .notNull() .references(() => posts.id), isCurrent: t .integer("is_current", { mode: "boolean" }) .notNull() .default(false), ...timestamps, }, (table) => [ t .uniqueIndex("post_contents_current_unique") .on(table.postId) .where(sql`${table.isCurrent} = true`), ], )
以下のようなSQLが発行される
CREATE UNIQUE INDEX `post_contents_current_unique` ON `post_contents` (`post_id`) WHERE `is_current` = 1;