Phase 1: generate database types and type the Supabase clients

Types are generated from the live database's API schema by
scripts/gen-types.mjs (npm run gen:types), in the same shape as
supabase gen types, so no Supabase CLI login is needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-03 13:20:31 +02:00
co-authored by Claude Opus 5.5
parent b134f87326
commit bc8e4f3f5a
6 changed files with 546 additions and 4 deletions
+140
View File
@@ -0,0 +1,140 @@
// Generates src/lib/database.types.ts from the live database's API schema, in the same
// shape as `supabase gen types typescript` — without needing a Supabase CLI login.
// Run with: npm run gen:types (after every migration)
import { writeFileSync } from "node:fs";
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!url || !serviceKey) {
console.error("Missing Supabase env vars. Fill in .env.local first.");
process.exit(1);
}
// Foreign keys whose constraint name isn't Postgres' default `<table>_<column>_fkey`.
const FK_NAME_OVERRIDES = { "events.current_game_id": "events_current_game_fk" };
// Columns with a DB default that the API schema doesn't report (it omits array defaults).
const EXTRA_DEFAULTS = new Set(["games.placement_points"]);
const response = await fetch(`${url}/rest/v1/`, {
headers: { apikey: serviceKey, Authorization: `Bearer ${serviceKey}` },
});
if (!response.ok) {
console.error(`Could not read the schema: HTTP ${response.status}`);
process.exit(1);
}
const { definitions = {} } = await response.json();
const tables = Object.keys(definitions).sort();
if (tables.length === 0) {
console.error("No tables found. Has the migration been applied?");
process.exit(1);
}
const enums = {};
function tsType(column) {
if (column.enum && column.format?.startsWith("public.")) {
const name = column.format.slice("public.".length);
enums[name] = column.enum;
return `Database["public"]["Enums"]["${name}"]`;
}
if (column.type === "array") return `${tsType(column.items)}[]`;
if (column.format === "json" || column.format === "jsonb") return "Json";
if (column.type === "integer" || column.type === "number") return "number";
if (column.type === "boolean") return "boolean";
return "string";
}
function tableBlock(table) {
const { properties, required = [] } = definitions[table];
const columns = Object.keys(properties).sort();
const row = [];
const insert = [];
const update = [];
const relationships = [];
for (const name of columns) {
const column = properties[name];
const nullable = !required.includes(name);
const type = tsType(column) + (nullable ? " | null" : "");
const optionalOnInsert =
nullable || column.default !== undefined || EXTRA_DEFAULTS.has(`${table}.${name}`);
row.push(` ${name}: ${type};`);
insert.push(` ${name}${optionalOnInsert ? "?" : ""}: ${type};`);
update.push(` ${name}?: ${type};`);
const fk = column.description?.match(/<fk table='(\w+)' column='(\w+)'\/>/);
if (fk) {
const fkName = FK_NAME_OVERRIDES[`${table}.${name}`] ?? `${table}_${name}_fkey`;
relationships.push(
[
" {",
` foreignKeyName: "${fkName}";`,
` columns: ["${name}"];`,
" isOneToOne: false;",
` referencedRelation: "${fk[1]}";`,
` referencedColumns: ["${fk[2]}"];`,
" },",
].join("\n"),
);
}
}
return [
` ${table}: {`,
" Row: {",
...row,
" };",
" Insert: {",
...insert,
" };",
" Update: {",
...update,
" };",
relationships.length ? ` Relationships: [\n${relationships.join("\n")}\n ];` : " Relationships: [];",
" };",
].join("\n");
}
const tableBlocks = tables.map(tableBlock).join("\n");
const enumBlock = Object.keys(enums)
.sort()
.map((name) => ` ${name}: ${enums[name].map((value) => `"${value}"`).join(" | ")};`)
.join("\n");
const output = `// GENERATED by scripts/gen-types.mjs from the live database — do not edit by hand.
// Regenerate with: npm run gen:types
export type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];
export type Database = {
public: {
Tables: {
${tableBlocks}
};
Views: {
[_ in never]: never;
};
Functions: {
[_ in never]: never;
};
Enums: {
${enumBlock}
};
CompositeTypes: {
[_ in never]: never;
};
};
};
export type Tables<T extends keyof Database["public"]["Tables"]> =
Database["public"]["Tables"][T]["Row"];
export type TablesInsert<T extends keyof Database["public"]["Tables"]> =
Database["public"]["Tables"][T]["Insert"];
export type TablesUpdate<T extends keyof Database["public"]["Tables"]> =
Database["public"]["Tables"][T]["Update"];
export type Enums<T extends keyof Database["public"]["Enums"]> = Database["public"]["Enums"][T];
`;
writeFileSync(new URL("../src/lib/database.types.ts", import.meta.url), output);
console.log(`Wrote src/lib/database.types.ts (${tables.length} tables, ${Object.keys(enums).length} enums).`);