66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import { readFile } from "fs/promises";
|
|
import postgres from "postgres";
|
|
|
|
const migrationTag = "0011_unique_submission_user";
|
|
const migrationPath = "drizzle/0011_unique_submission_user.sql";
|
|
|
|
const databaseUrl = process.env.DATABASE_URL;
|
|
if (!databaseUrl) {
|
|
throw new Error("DATABASE_URL is not set");
|
|
}
|
|
|
|
const sql = postgres(databaseUrl, { max: 1 });
|
|
|
|
try {
|
|
const duplicates = await sql<{ form_id: string; user_discord_id: string; count: string }[]>`
|
|
select form_id, user_discord_id, count(*)::text as count
|
|
from form.submission
|
|
where user_discord_id is not null
|
|
group by form_id, user_discord_id
|
|
having count(*) > 1
|
|
limit 20
|
|
`;
|
|
|
|
if (duplicates.length > 0) {
|
|
console.error("Duplicate submissions would violate the unique index:");
|
|
for (const duplicate of duplicates) {
|
|
console.error(
|
|
`form_id=${duplicate.form_id} user_discord_id=${duplicate.user_discord_id} count=${duplicate.count}`
|
|
);
|
|
}
|
|
process.exit(1);
|
|
}
|
|
|
|
await sql`
|
|
create unique index if not exists "submission_form_user_discord_id_unique"
|
|
on "form"."submission" using btree ("form_id", "user_discord_id")
|
|
`;
|
|
|
|
const migrationTable = await sql<{ exists: boolean }[]>`
|
|
select to_regclass('drizzle.__drizzle_migrations') is not null as exists
|
|
`;
|
|
|
|
if (migrationTable[0]?.exists) {
|
|
const existing = await sql<{ count: string }[]>`
|
|
select count(*)::text as count
|
|
from drizzle.__drizzle_migrations
|
|
where hash = ${migrationTag}
|
|
`;
|
|
|
|
if (existing[0]?.count === "0") {
|
|
const migrationSql = await readFile(migrationPath, "utf8");
|
|
await sql`
|
|
insert into drizzle.__drizzle_migrations (hash, created_at)
|
|
values (${migrationTag}, ${Date.now()})
|
|
`;
|
|
console.log(`Applied ${migrationTag}: ${migrationSql.trim()}`);
|
|
} else {
|
|
console.log(`${migrationTag} was already recorded.`);
|
|
}
|
|
} else {
|
|
console.log("Applied index. Drizzle migration table was not found, so no migration row was recorded.");
|
|
}
|
|
} finally {
|
|
await sql.end();
|
|
}
|