interro
interro copied to clipboard
Add schema generator
Right now, there's no real way to know what's in the DB without inspecting the schema yourself inside a Postgres client. For the most part, I haven't minded because I tend to just use the Postgres client to get that information if I've forgotten, but most of the time my models are my source of truth for what's in the DB anyway.
However, it can be useful to have the full schema on-hand for things like static analysis tooling or LLM-assisted coding tools to read from. This PR is a first pass at outputting the DB schema after running migrations.
I was originally going to just have it run pg_dump, but then it requires that you have pg_dump installed. This may very well not be the case, especially in minimal container images like the ones I tend to run. So, since it's simple enough to query the schema in SQL, we can do it in pure Crystal.
Here is some example output against a fresh app generated by wax:
-- Generated Schema
CREATE TABLE IF NOT EXISTS schema_migrations (
name text NOT NULL,
added_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id uuid NOT NULL DEFAULT gen_random_uuid(),
email text NOT NULL,
name text NOT NULL,
password text NOT NULL,
role int4 NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO schema_migrations (name, added_at)
VALUES
('CreateUsers', '2025-01-25 00:02:25.80291-06');
CREATE UNIQUE INDEX IF NOT EXISTS schema_migrations_added_at_key ON schema_migrations (added_at);
CREATE UNIQUE INDEX IF NOT EXISTS schema_migrations_name_key ON schema_migrations (name);
CREATE UNIQUE INDEX IF NOT EXISTS users_email_key ON users (email);
CREATE UNIQUE INDEX IF NOT EXISTS users_pkey ON users (id);
When I drop and recreate my development DB and run this SQL file against it, it works pretty well. I haven't done it this against a more complex DB yet, but it's on my todo list.