DBQC Schema Discovery and Code Generation

DBQC discovers a language-neutral schema snapshot from a live database. The tool at server/core/dbqc/schema/discover.py introspects **PostgreSQL, MySQL, or SQLite** and emits the supported JSON format.

A live database schema passes through a discovery prism and becomes clean typed table definitions.

How It Works

The pipeline is connect → discover → (in-memory Table model) → emit. The script connects read-only, reads the database catalog (column names, types, nullability), maps each native column type onto a DBQC SqlType, and renders the result in your target language. The in-memory model is the narrow waist: N engines + M languages stay N+M code paths, never N×M.

The generated code is the starting point for building queries. Query compilation uses those definitions rather than a live database connection, and the same schema model can power VS Code completion, hover, and local diagnostics. DBQC returns SQL for the driver that already executes the application's queries.

Usage

# engine is inferred from the --url scheme, or set it explicitly with --engine
python3 server/core/dbqc/schema/discover.py --engine postgres --format json
python3 server/core/dbqc/schema/discover.py --url postgresql://ro@localhost/mydb --output .dbqc-schema.json

# Java schema classes: named typed columns rather than string column names
python3 dbqc_discover.py --url postgresql://ro@localhost/mydb --format java-schema > DbqcSchema.java

python3 dbqc_discover.py --self-test    # validate every mapping + emitter; no database needed

Connecting to Your Database

The script needs read-only access and reads only catalog metadata (information_schema on PG/MySQL; sqlite_master + PRAGMA table_info on SQLite). It does NOT read data, modify schemas, or execute any DML.

Run python3 dbqc_discover.py --connection-help for copy-paste examples.

Quick examples

# Local Postgres — individual flags
python3 dbqc_discover.py --host localhost --database mydb --user postgres --format python

# Connection URL (same as before)
python3 dbqc_discover.py --url postgresql://readonly@localhost/mydb --format scala

# RDS with SSL — one flag
python3 dbqc_discover.py --url postgresql://admin@mydb.abc.rds.amazonaws.com/mydb --ssl --format json

# Through an SSH bastion
python3 dbqc_discover.py --host db.internal --database mydb --ssh-host bastion.example.com --format java

# Supabase
python3 dbqc_discover.py --url postgresql://postgres:$PASS@db.xyz.supabase.co/postgres --ssl --format typescript

# MySQL
python3 dbqc_discover.py --engine mysql --host localhost --database mydb --user root --format java

# SQLite — just a file path
python3 dbqc_discover.py --url ./app.db --format rust

# Test credentials before full discovery
python3 dbqc_discover.py --host db.prod --ssl --test-connection
# → Connected to PostgreSQL 15.4 / Schema 'public': 23 tables

Connection flags

Flag Purpose Default
--url Full connection URL (overrides individual flags) DATABASE_URL env var
--host Database host PGHOST / MYSQL_HOST / localhost
--port Database port PGPORT / MYSQL_TCP_PORT / engine default
--user Database user PGUSER / MYSQL_USER / OS user
--database Database name PGDATABASE / MYSQL_DATABASE
--engine postgres, mysql, or sqlite Inferred from URL scheme
--schema Schema to introspect public (PG), database name (MySQL)

Password handling

Passwords never need to appear in shell history:

Method Flag Example
Environment variable --password-env VAR --password-env DB_PASSWORD
File (first line) --password-file PATH --password-file /run/secrets/db_pass
Interactive prompt --password Prompts via TTY
Embedded in URL --url postgresql://user:pass@host/db Works but visible in history
Standard env vars (automatic) PGPASSWORD, MYSQL_PWD

Priority: URL-embedded > --password-env > --password-file > --password prompt > standard env vars.

SSL/TLS

Flag Purpose Default
--ssl Enable SSL with sensible defaults Off
--ssl-mode Fine-grained: require, verify-ca, verify-full (PG); REQUIRED, VERIFY_CA, VERIFY_IDENTITY (MySQL) require / REQUIRED
--ssl-ca CA certificate path —
--ssl-cert Client certificate path —
--ssl-key Client key path —

SSH tunnels

Flag Purpose Default
--ssh-host Bastion / jump host —
--ssh-port SSH port 22
--ssh-user SSH user OS user
--ssh-key SSH private key path ~/.ssh/id_rsa

The tool opens an SSH tunnel (ssh -L) to forward a local port to the database, connects through it, and cleans up on exit. Zero third-party dependencies — uses the system ssh binary.

Security notes

interactive --password prompt for local use.

installed.

What It Generates

For each table, the script emits a typed definition in your target format. (Examples below are the tool's actual output for a SQLite users table.)

JSON (for endpoint clients)

{
  "users": {
    "type": "table",
    "name": "users",
    "heading": [
      {"name": "id", "type": "text"},
      {"name": "name", "type": "text"},
      {"name": "age", "type": "int8", "nullable": true},
      {"name": "balance", "type": "numeric(12,2)", "nullable": true},
      {"name": "created_at", "type": "timestamp", "nullable": true},
      {"name": "bio", "type": "varchar(200)", "nullable": true}
    ],
    "dbSchema": "main"
  }
}

The wire shape is fixed by the server's circe codecs and is exact: the discriminator key is type (snake_case), a FieldType is an object with a "type" field and an optional "nullable": true ({"type": "uuid"} for non-null, {"type": "text", "nullable": true} for nullable; parameterized types include their params in the type string: "numeric(12,2)", "varchar(200)"), and Heading is an ordered array of objects each with "name", "type", and optionally "nullable": true. Getting any of these wrong fails to decode.

Python (for dbqc.py)

from dbqc import Table

users = Table("users", {
    "id": "text",
    "name": "text",
    "age": "int8",
    "balance": "numeric(12,2)",
    "created_at": "timestamp",
    "bio": "varchar(200)",
}, db_schema="main", opt_columns={"age", "balance", "created_at", "bio"})

Java (for Dbqc.java)

var users = Dbqc.table("users", new java.util.LinkedHashMap<>() {{
   put("id", "text");
   put("name", "text");
   put("age", "int8");
   put("balance", "numeric(12,2)");
   put("created_at", "timestamp");
   put("bio", "varchar(200)");
}}, "main", java.util.Set.of("age", "balance", "created_at", "bio"));

Java schema class (for Java compiler checks)

Use --format java-schema when Java code should refer to generated columns rather than repeating string names. Save the output as DbqcSchema.java alongside Dbqc.java, regenerate it after every schema change, and compile it with the application.

var query = DbqcSchema.Users.TABLE.where(
    DbqcSchema.Users.ID.eq(java.util.UUID.fromString(userId))
).select(Dbqc.exprs(
    "email", DbqcSchema.Users.EMAIL.expr()
));

DbqcSchema.Users.ID is a Dbqc.Column and EMAIL is a Dbqc.Column. Therefore a renamed or removed column no longer leaves a valid string literal in application code, and Java rejects comparisons such as Users.ID.eq(Users.EMAIL) before DBQC is called. Use .expr() when passing a generated column to the general DBQC query DSL.

Scala (for direct DBQC usage)

import com.volvwealth.dbqc.api.*
import scala.collection.immutable.VectorMap

val users: Source.Table = Source.Table(
   "users",
   Heading(VectorMap(
      "id" -> FieldType(SqlType.Text, false),
      "name" -> FieldType(SqlType.Text, false),
      "age" -> FieldType(SqlType.Int8, true),
      "balance" -> FieldType(SqlType.Numeric(12, 2), true),
      "created_at" -> FieldType(SqlType.Timestamp, true),
      "bio" -> FieldType(SqlType.Varchar(200), true),
   )),
   "main",
)

Rust (for dbqc-rs)

let users = table("users", &[
   ("id", "text"),
   ("name", "text"),
   ("age", "int8"),
   ("balance", "numeric(12,2)"),
   ("created_at", "timestamp"),
   ("bio", "varchar(200)"),
], "main", &["age", "balance", "created_at", "bio"]);

TypeScript (for dbqc.ts)

const users = table("users", {
   "id": "text",
   "name": "text",
   "age": "int8",
   "balance": "numeric(12,2)",
   "created_at": "timestamp",
   "bio": "varchar(200)",
}, "main", new Set(["age", "balance", "created_at", "bio"]));

SqlType — the canonical 16

Every native column type is mapped onto exactly one of the 16 SqlType cases (see api/src/SqlType.scala). Anything with no equivalent is skipped with a warning rather than emitted as a wrong type.

bool · char(n) · varchar(n) · text · int2 · int4 · int8 · float4 · float8 · numeric(p,s) · enum(name) · date · timestamp · interval · jsonb · uuid

There is no separate timestamptz/time/json/bytea type: a timezone-aware timestamp maps to timestamp (its SQL rendering is timestamptz), and the only JSON type is jsonb.

Type Mapping

PostgreSQL

PostgreSQL DBQC SqlType
boolean bool
smallint / int2 int2
integer / int4 int4
bigint / int8 int8
real / float4 float4
double precision / float8 float8
numeric(p,s) / decimal(p,s) numeric(p,s)
character(n) / char(n) char(n)
character varying(n) / varchar(n) varchar(n) (unbounded → text)
text text
uuid uuid
date date
timestamp / timestamptz timestamp
interval interval
json / jsonb jsonb
USER-DEFINED (enum) enum(name)
arrays, ranges, geometry, … skipped + warning

MySQL

MySQL DBQC SqlType
tinyint(1) bool
tinyint(n) / smallint int2
mediumint / int / integer int4
bigint int8
float float4
double / real float8
decimal(p,s) / numeric(p,s) numeric(p,s)
char(n) char(n)
varchar(n) varchar(n)
tinytext / text / mediumtext / longtext text
date date
datetime / timestamp timestamp
json jsonb (warning)
enum(...) text (warning — MySQL inline enum has no named type)
year int2 (warning)
time, binary/varbinary/blob, bit skipped + warning

SQLite

SQLite has type affinity rather than strict types; the declared type string is mapped, falling back to SQLite's affinity rules. A PRIMARY KEY column is treated as NOT NULL.

SQLite declared type DBQC SqlType
boolean / bool bool
smallint / int2 int2
int / integer / bigint / anything with INT affinity int8
real / float / double float8
numeric(p,s) / decimal(p,s) numeric(p,s) (bare → numeric(0,0) + warning)
char(n) / varchar(n) char(n) / varchar(n)
text / clob / CHAR affinity text
date date
datetime / timestamp timestamp
uuid uuid
json / jsonb jsonb (warning)
blob / empty affinity skipped + warning

Verification

python3 dbqc_discover.py --self-test validates every engine's type mapping and every emitter against expected output, with no database required. The JSON wire shape is additionally proven by decoding it through the real server codec (the dbqc.verify round-trip), so generated definitions are guaranteed to be accepted by the compile endpoint.

Workflow

  1. Set up a read-only user (one-time, PG/MySQL).
  2. Run codegen after schema changes: python3 dbqc_discover.py --url … --format > tables..
  3. Import the generated tables in your query code.
  4. Build queries with the matching DBQC client.
  5. Compile via the DBQC endpoint or the Scala compiler.

Re-run codegen whenever your schema changes, and commit the generated files — they're your source of truth for column names and types.