Database Migration with DBQC

A practical guide for engineering teams migrating between database vendors.

The Problem

Database migrations are one of the most expensive, risky projects an engineering team undertakes. The numbers are well-understood:

for 6+ months ($225K+ in loaded salary alone).

Postgres. The next migration costs the same as this one.

The bulk of that cost is query rewriting. Schema migration (DDL) is mechanical and well-tooled. But every SQL statement in every service must be audited, translated to the target dialect, tested, and deployed. That is the 80% of the work and 90% of the risk.

The DBQC Approach

DBQC is a compiler that takes a language-agnostic query AST and produces SQL for a specific target database. The same AST compiles to Postgres, MySQL, SQLite, DuckDB (DBQC standard) and Oracle, SQL Server, DB2 (DBQC Pro).

The migration keeps execution where it already belongs: your application uses its existing driver, credentials, transaction handling, and rollout controls to run each target's generated SQL. DBQC provides the portable definition and the validation, test, and review evidence around that change.

The migration workflow:

  1. Write DBQC definitions against your current database, or disassemble an

existing SQL statement into a DBQC definition as the conversion step.

  1. Compile to your source dialect and verify correctness.
  2. Change the target parameter and recompile for your destination database.

The migration is a parameter change, not a rewrite.

A legacy database passes through a compiler bridge and fans out cleanly to cloud, mobile, and modern application destinations.

An existing SQL statement passes through a conversion step into a structured DBQC definition with discovered schema context, then compiles into SQL for supported database targets.

The Dual-Compile Migration Workflow

This is the step-by-step process for migrating a production system from one database vendor to another using DBQC.

Step 1: Discover your source schema

DBQC's schema discovery tool introspects your live database and emits typed table definitions in your language. It reads only catalog metadata (no data access), supports SSL and SSH tunnels, and needs only a read-only user.

# Oracle source database (via DBQC Pro)
python3 dbqc_discover.py \
  --url oracle://readonly@db.prod.internal/billing \
  --ssl \
  --format python \
  > tables.py

# Through an SSH bastion (common in enterprise networks)
python3 dbqc_discover.py \
  --host db.internal \
  --database billing \
  --ssh-host bastion.example.com \
  --ssl \
  --format python \
  > tables.py

# Test credentials before full discovery
python3 dbqc_discover.py \
  --url oracle://readonly@db.prod.internal/billing \
  --ssl \
  --test-connection
# -> Connected to Oracle 19.3 / Schema 'BILLING': 84 tables

Password handling is built for production use: --password-env DB_PASSWORD reads from an environment variable (no shell history exposure), `--password-file /run/secrets/db_pass` reads from a Docker secret or mounted file, and --password prompts interactively on TTY. Credentials never appear in generated output.

The discovery tool supports Postgres, MySQL, and SQLite engines natively. For Oracle, SQL Server, and DB2 source schemas, use the JSON wire format with the DBQC Pro compile endpoint, or define tables manually using the generated examples as a template — the table definitions are small, typed data structures, not pages of boilerplate.

Step 2: Write your queries in DBQC

Take your existing SQL and either disassemble it into DBQC or express it in DBQC's query DSL. The DSL is available in Python, Java, Scala, Rust, and TypeScript — use whatever language your services are written in. Once the statement is represented as a DBQC definition, the ordinary compiler workflow validates it and emits the target SQL.

Here is a real example: a monthly revenue summary with joins, aggregation, filtering, and date handling.

Before (Oracle SQL):

SELECT
  c.customer_name,
  TO_CHAR(o.order_date, 'YYYY-MM') AS order_month,
  SUM(oi.unit_price * oi.quantity) AS total_revenue,
  COUNT(DISTINCT o.order_id) AS order_count
FROM customers c
  JOIN orders o ON c.customer_id = o.customer_id
  JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date >= DATE '2025-01-01'
  AND o.status <> 'cancelled'
GROUP BY c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM')
HAVING SUM(oi.unit_price * oi.quantity) > 1000
ORDER BY total_revenue DESC
FETCH FIRST 50 ROWS ONLY

After (DBQC Python DSL):

from dbqc import Table, col, lit, count_distinct, sum_, Compiler

# Table definitions (generated by dbqc_discover.py)
customers = Table("customers", {
    "customer_id": "int8",
    "customer_name": "varchar(200)",
}, db_schema="billing")

orders = Table("orders", {
    "order_id": "int8",
    "customer_id": "int8",
    "order_date": "date",
    "status": "varchar(20)",
}, db_schema="billing")

order_items = Table("order_items", {
    "order_id": "int8",
    "unit_price": "numeric(12,2)",
    "quantity": "int4",
}, db_schema="billing")

# The query -- written once, compiles to any dialect
monthly_revenue = (
    customers
    .join(orders, col(customers, "customer_id") == col(orders, "customer_id"))
    .join(order_items, col(orders, "order_id") == col(order_items, "order_id"))
    .where(
        col(orders, "order_date") >= lit("2025-01-01"),
        col(orders, "status") != lit("cancelled"),
    )
    .group_by(
        col(customers, "customer_name"),
        date_trunc("month", col(orders, "order_date")),
    )
    .having(sum_(col(order_items, "unit_price") * col(order_items, "quantity")) > lit(1000))
    .select(
        customer_name=col(customers, "customer_name"),
        order_month=date_trunc("month", col(orders, "order_date")),
        total_revenue=sum_(col(order_items, "unit_price") * col(order_items, "quantity")),
        order_count=count_distinct(col(orders, "order_id")),
    )
    .order_by(desc("total_revenue"))
    .limit(50)
)

This query compiles to correct SQL for Oracle, Postgres, MySQL, SQLite, DuckDB, SQL Server, and DB2. The DBQC compiler handles dialect differences automatically:

vs DATE_FORMAT(col, '%Y-%m') (MySQL)

[col] (SQL Server)

differences

You write the query once. The compiler knows the rules for each dialect.

This is a one-time cost that pays for itself on every future migration. The Oracle-specific SQL you have today is disposable — it only works on Oracle. The DBQC query is permanent infrastructure that works on every database you will ever use.

Step 3: Verify on your source database

Compile all your queries against the source dialect to prove they produce valid SQL for your current database. This is your baseline — if it compiles for Oracle today, the query logic is correct.

python3 my_queries.py check --target oracle
[check] Compiling 47 queries for oracle...
  user_report: OK
  monthly_revenue: OK
  audit_log_query: OK
  customer_lifetime_value: OK
  ... (43 more)
All 47 queries compiled successfully for oracle.

Every DBQC client library (Python, Java, Scala, Rust, TypeScript) includes this check mode. It compiles every query against the DBQC compiler endpoint and exits non-zero on any failure. Bad column names, type mismatches, missing tables -- caught at build time, not at 2 AM in production.

Step 4: Dual-compile — prove both dialects work

This is where the migration safety comes from. Compile the same queries against both your source and destination dialects:

# Compile for source (Oracle)
python3 my_queries.py check --target oracle
# All 47 queries compiled successfully for oracle.

# Compile for destination (Postgres)
python3 my_queries.py check --target postgres
# All 47 queries compiled successfully for postgres.

Both pass. Every query that runs on your Oracle database today will produce valid SQL for Postgres. You have not deployed anything, changed any infrastructure, or risked any production traffic. You have mathematical proof that your queries are portable.

If a query fails on the destination dialect, you find out here — at your desk, during business hours — not during a Saturday night cutover window.

Step 5: CI dual-compile gate

Lock this safety into your build pipeline. Every commit, every pull request, compiles to both dialects. A query that works on Oracle but fails on Postgres blocks the merge.

name: DBQC Dual-Compile Gate
on: [push, pull_request]

jobs:
  dbqc-migration-check:
    runs-on: ubuntu-latest
    services:
      dbqc:
        image: volv-server:latest
        ports:
          - 8080:8080
    env:
      DBQC_ENDPOINT: http://localhost:8080/api/dbqc/compile
    steps:
      - uses: actions/checkout@v4

      - name: Compile for Oracle (source)
        run: python3 my_queries.py check --target oracle

      - name: Compile for Postgres (destination)
        run: python3 my_queries.py check --target postgres

      - name: Report
        if: success()
        run: echo "All queries compile for both Oracle and Postgres."

This CI gate gives you a property that no consulting engagement can match: continuous migration readiness. Every developer on your team, on every commit, is verifying that the migration will work. New queries are written portable from day one. Regressions are caught in minutes, not discovered during the migration project.

See CI / CD for the full CI setup, including Makefile targets, pre-commit hooks, and per-language check commands.

Step 6: Incremental migration

With the CI gate green, start migrating services one at a time. The change is a configuration update — literally one string.

Before (service points at Oracle):

# config.py
DBQC_TARGET = "oracle"

After (service points at Postgres):

# config.py
DBQC_TARGET = "postgres"

That is the entire code change. The queries do not change. The application logic does not change. The DBQC compiler produces Postgres SQL instead of Oracle SQL.

Migrate incrementally:

  1. Start with a low-risk, read-heavy service (reporting, dashboards, analytics).
  2. Run it against Postgres for a week. Monitor query performance, check results.
  3. Move the next service. Then the next.
  4. Each service migrates independently — there is no big-bang cutover.

Your Oracle database and Postgres database run in parallel during the migration window. Services that have migrated talk to Postgres; services that have not still talk to Oracle. There is no flag day.

Step 7: Rollback

If something goes wrong after flipping a service to Postgres — unexpected query performance, a dialect edge case, an infrastructure issue — roll back:

# config.py
DBQC_TARGET = "oracle"  # reverted

Deploy. The service is back on Oracle. No code rewrite. No emergency SQL translation. No 3 AM scramble to rebuild Oracle-specific queries from memory.

Compare this to a traditional migration rollback: you rewrote 200 queries from Oracle SQL to Postgres SQL. Rolling back means re-rewriting all 200 queries back to Oracle SQL, then deploying, then testing. That is not a rollback plan. That is a second migration project.

With DBQC, rollback is a one-line config change that you can make in 30 seconds and deploy in your normal CI/CD pipeline.

Step 8: Post-migration

Once all services are running on Postgres and the Oracle database is decommissioned:

  1. Delete the Oracle database. You are done with it.
  2. Drop DBQC Pro if you no longer need Oracle/SQL Server/DB2 dialects. Your

queries still compile to Postgres, MySQL, SQLite, and DuckDB on the standard DBQC product.

  1. Your queries are permanently portable. The next time someone says "we

should evaluate CockroachDB" or "the mobile app needs SQLite," your queries already compile for those targets. The investment you made in step 2 pays dividends on every future dialect decision.

Cost Comparison

Three approaches to migrating a 50-service system with approximately 500 SQL queries from Oracle to Postgres:

Dimension Consulting Firm DIY with SQLGlot DBQC Pro
Upfront cost $200K-$500K $0 + 2-3 engineers x 6 months ($225K+ loaded) $749-$14,999/yr (launch pricing)
Timeline to production 6-12 months 3-6 months Incremental (weeks to months)
Migration method Audit, rewrite, test every query Parse Oracle SQL, transpile to Postgres SQL Change target parameter per service
Rollback plan Rewrite back to Oracle ($$$) Re-transpile (hours to days) One config change (seconds)
Next migration Start from scratch ($200K+) Re-transpile (but still SQL-to-SQL) Already done (change the parameter)
CI safety net None (manual QA) Custom tooling required Built-in dual-compile gate
Language support N/A Python only Python, Java, Scala, Rust, TypeScript
Ongoing value after migration None SQLGlot stays in Python codebase Portable queries across all services

The real math: 3 engineers diverted for 6 months at $150K/yr loaded salary = $225K in direct engineering cost, plus the opportunity cost of what those engineers were not building. DBQC Pro Business at $14,999/yr is 15x cheaper in year one and includes the rollback safety net, the CI gate, and permanent portability. Over a 3-year horizon (accounting for one additional migration), DBQC Pro costs $45K total vs. $450K+ for two consulting engagements.

Common Migration Paths

DBQC handles dialect-specific SQL differences automatically. Here is what the compiler does for the most common migration paths.

Oracle to Postgres (most common)

The dominant enterprise migration path. DBQC handles:

Oracle Postgres What DBQC does
VARCHAR2(n) VARCHAR(n) Type name normalization
NUMBER INTEGER / NUMERIC Precision-aware type mapping
DECODE(a, b, c, d) CASE WHEN a = b THEN c ELSE d END Function rewriting
NVL(a, b) COALESCE(a, b) Null-handling function translation
FETCH FIRST n ROWS ONLY LIMIT n Pagination syntax
SYSDATE CURRENT_TIMESTAMP Date function translation
"IDENTIFIER" "identifier" Case-sensitive identifier handling
(+) outer join syntax LEFT JOIN / RIGHT JOIN Join syntax normalization
Sequences (seq.NEXTVAL) nextval('seq') Sequence access syntax

SQL Server to Postgres

SQL Server Postgres What DBQC does
[identifier] "identifier" Bracket to double-quote conversion
BIT BOOLEAN Boolean type mapping
NVARCHAR(n) VARCHAR(n) Unicode string normalization
DATETIMEOFFSET TIMESTAMPTZ Timezone-aware timestamp mapping
UNIQUEIDENTIFIER UUID UUID type mapping
TOP n LIMIT n Result limiting syntax
GETDATE() CURRENT_TIMESTAMP Date function translation
ISNULL(a, b) COALESCE(a, b) Null-handling normalization

MySQL to Postgres

MySQL Postgres What DBQC does
` identifier ` "identifier" Backtick to double-quote conversion
<=> IS NOT DISTINCT FROM NULL-safe equality
IFNULL(a, b) COALESCE(a, b) Null-handling normalization
AUTO_INCREMENT GENERATED ALWAYS AS IDENTITY Auto-increment translation
TINYINT(1) BOOLEAN Boolean idiom detection
CONCAT(a, b) `a \ \ b` String concatenation normalization

Oracle to MySQL

Oracle MySQL What DBQC does
CLOB TEXT Large text type mapping
NUMBER INT / DECIMAL Precision-aware type mapping
BINARY_FLOAT FLOAT Float type normalization
DECODE(...) CASE WHEN ... END Function rewriting
NVL(a, b) IFNULL(a, b) or COALESCE(a, b) Null-handling translation

Any dialect to SQLite (embedded/mobile)

When your mobile app or embedded system needs a local database, DBQC compiles the same queries to SQLite. The compiler handles full type simplification automatically — NUMERIC(12,2) becomes SQLite's numeric affinity, BOOLEAN becomes INTEGER, UUID becomes TEXT, and pagination/date functions are rewritten for SQLite's function set. Write your queries once in your backend service, compile to Postgres for the server and SQLite for the mobile client.

Addressing the Rewrite Cost

The honest answer: yes, you have to rewrite your queries into DBQC. That is a real cost. But consider what you are comparing:

Option A: Rewrite Oracle SQL into Postgres SQL.

Option B: Rewrite Oracle SQL into DBQC.

Server, and DB2.

The upfront cost is the same either way. The difference is what you own when you are done. Option A gives you queries that work on one database. Option B gives you queries that work on every database, forever.

This is not a hypothetical. Companies migrate databases more than once. Oracle to Postgres today. Postgres to CockroachDB (Postgres-compatible) in three years when you need global distribution. A SQLite variant for the mobile app next quarter. An analytics replica on DuckDB for the data team. Every one of those is a parameter change with DBQC. Every one of those is a new rewrite project without it.

Getting Started

1. Sign up for DBQC Pro.

Launch pricing is available through December 31, 2026. Pro starts at $749/yr (regular $1,499). Prepay year 2 before Dec 31, 2026 and lock in the launch rate for both years. See Pricing for all tiers.

2. Run schema discovery.

python3 dbqc_discover.py \
  --url oracle://readonly@db.prod/mydb \
  --ssl \
  --test-connection

python3 dbqc_discover.py \
  --url oracle://readonly@db.prod/mydb \
  --ssl \
  --format python \
  > tables.py

3. Start with your highest-value queries.

Pick the 10-20 most-used queries in your most critical service. Rewrite them in DBQC. Set up the dual-compile CI gate. Get the team comfortable with the workflow.

4. Expand incrementally.

Migrate the next service, then the next. Each one follows the same pattern: discover, rewrite, dual-compile, flip, verify.

5. Flip and decommission.

When all services are migrated, decommission the source database. Drop the DBQC Pro subscription if you no longer need enterprise dialects.

Further Reading

Makefile, and pre-commit hooks

connection options (SSL, SSH, password handling)

Prisma, and AI SQL generators