Skip to main content

Generate an SQL Schema from a Migrations Directory

Question

How to generate an SQL schema file from an existing migrations directory to quickly set up a database for integration tests?

Answer

  1. Inspect the Migration Directory: Dump the migration directory to an SQL file using the atlas schema inspect command:

    atlas schema inspect \
    --url "file://path/to/migrations" \
    --dev-url "<DEV-URL>" \
    --format "{{ sql . }}" > schema.sql
    Dev URL

    Replace <DEV-URL> with the URL of your dev-database

  2. Apply the Schema to Your Test Database: Once the schema.sql file is generated, you can also apply it to your database using the atlas schema apply command:

    atlas schema apply \
    --url "<DATABASE-URL>" \
    --dev-url "<DEV-URL>" \
    --to "file://schema.sql"
    Dev URL

    Replace <DEV-URL> with the URL of your dev-database, and <DATABASE-URL> with the URL of your test database.

Alternative Approach

If you prefer to apply the schema represented by the migrations directory directly to your test database without generating a schema file, you can use the atlas schema apply command with the migration directory as the desired state.

atlas schema apply \
--url "<DATABASE-URL>" \
--dev-url "<DEV-URL>" \
--to "file://path/to/migrations"