mvp-ai's picture
download
raw
6.37 kB
#!/usr/bin/env python3
"""Scaffold a table migration for a new resource.
Stdlib only -- no third-party dependencies (references/conventions.md).
Follows the patterns in references/database-schema-design.md: created_at/
updated_at on every table (DB006), UUID primary keys for public-facing
resources (DB001), and RLS colocated with the table's own migration (DB030)
when --rls is passed.
Column DSL: "name:type[,name:type...]" using generic type names that map to
either raw SQL (--target supabase) or a Prisma model (--target prisma):
uuid, text, integer, bigint, boolean, timestamp, jsonb, numeric
Examples:
python3 generate.py products --columns "title:text,price:integer" --rls --output ./my-app
python3 generate.py products --columns "title:text,price:integer" --target prisma --output ./my-app
python3 generate.py orders --rls --dry-run
"""
import argparse
import datetime
import re
import sys
from pathlib import Path
SQL_TYPES = {
"uuid": "uuid",
"text": "text",
"integer": "integer",
"bigint": "bigint",
"boolean": "boolean",
"timestamp": "timestamptz",
"jsonb": "jsonb",
"numeric": "numeric",
}
PRISMA_TYPES = {
"uuid": "String",
"text": "String",
"integer": "Int",
"bigint": "BigInt",
"boolean": "Boolean",
"timestamp": "DateTime",
"jsonb": "Json",
"numeric": "Decimal",
}
def parse_columns(spec: str):
if not spec:
return []
cols = []
for part in spec.split(","):
part = part.strip()
if not part:
continue
if ":" not in part:
print(f"error: column '{part}' must be name:type", file=sys.stderr)
sys.exit(1)
name, type_ = part.split(":", 1)
name, type_ = name.strip(), type_.strip().lower()
if type_ not in SQL_TYPES:
print(f"error: unknown type '{type_}' (known: {', '.join(SQL_TYPES)})", file=sys.stderr)
sys.exit(1)
cols.append((name, type_))
return cols
def to_snake(name: str) -> str:
name = re.sub(r"[_\-\s]+", "_", name).strip("_")
name = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)
return name.lower()
def to_pascal(snake: str) -> str:
return "".join(w.capitalize() for w in snake.split("_"))
def render_supabase(table: str, columns, with_rls: bool) -> str:
col_lines = "\n".join(f" {name} {SQL_TYPES[type_]}," for name, type_ in columns)
rls_block = ""
if with_rls:
rls_block = f"""
alter table {table} enable row level security;
-- Starter policy: adjust the USING/WITH CHECK expressions for real
-- ownership/tenant logic before relying on this (see auth-patterns.md,
-- database-schema-design.md DB015/DB030). This placeholder denies all
-- access until you replace the `false` conditions.
create policy "{table}_select_own" on {table}
for select using (false); -- TODO: e.g. user_id = auth.uid()
create policy "{table}_insert_own" on {table}
for insert with check (false); -- TODO: e.g. user_id = auth.uid()
create policy "{table}_update_own" on {table}
for update using (false); -- TODO: e.g. user_id = auth.uid()
create policy "{table}_delete_own" on {table}
for delete using (false); -- TODO: e.g. user_id = auth.uid()
"""
return f"""-- Migration: create {table}
-- Generated by fullstack-pro-max scripts/database/generate.py
-- Review every default and policy below before applying (DB058, DB030).
create table if not exists {table} (
id uuid primary key default gen_random_uuid(),
{col_lines}
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
-- Shared updated_at trigger -- safe to run even if it already exists.
create or replace function set_updated_at()
returns trigger as $$
begin
new.updated_at = now();
return new;
end;
$$ language plpgsql;
drop trigger if exists set_{table}_updated_at on {table};
create trigger set_{table}_updated_at
before update on {table}
for each row execute function set_updated_at();
{rls_block}"""
def render_prisma(table: str, columns) -> str:
model_name = to_pascal(to_snake(table))
if model_name.endswith("s") and not model_name.endswith("ss"):
model_name = model_name[:-1] # naive singularization for the model name
col_lines = "\n".join(f" {name} {PRISMA_TYPES[type_]}" for name, type_ in columns)
return f"""// Prisma model fragment for {table} -- paste into schema.prisma and adjust.
// Generated by fullstack-pro-max scripts/database/generate.py
model {model_name} {{
id String @id @default(uuid())
{col_lines}
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("{table}")
}}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("table", help="Table/resource name, e.g. 'products' or 'order_items'")
parser.add_argument("--columns", default="", help='Comma-separated "name:type" pairs')
parser.add_argument("--rls", action="store_true", help="Include starter Row-Level Security policies (Supabase target only)")
parser.add_argument("--target", choices=["supabase", "prisma"], default="supabase")
parser.add_argument("--output", type=Path, default=Path("./generated"), help="Project root to write into")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
table = to_snake(args.table)
columns = parse_columns(args.columns)
if args.target == "supabase":
content = render_supabase(table, columns, args.rls)
timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S")
rel_path = f"supabase/migrations/{timestamp}_create_{table}.sql"
else:
content = render_prisma(table, columns)
rel_path = f"prisma/fragments/{table}.prisma"
target = args.output / rel_path
if args.dry_run:
print(f"--- would write {target} ---")
print(content)
return
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
print(f"wrote {target}")
if args.target == "supabase" and not args.rls:
print("Note: no --rls passed -- if this table needs tenant/user isolation, add policies before shipping (DB015).")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
6.37 kB
·
Xet hash:
a6366793fcd5deb728b31dfa150c8df62d03a78c812f23b808ccc050db530a01

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.