Skip to content

Adopting an existing database

If you already have a database with an unmanaged schema, you don’t have to write your SQL from scratch. The nschema import command reads a live schema and writes it out as DDL source files, so you can adopt an existing database and manage it going forward.

  1. Declare the provider. Import reads from a live database, so it needs a PROVIDER block naming the provider and pinning its plugin version. Create a single .sql file in your project directory with just that block — the schema files themselves will come from the import:

    -- provider.sql
    PROVIDER postgres (
    version = '4.0.0'
    );

    Supply the connection string out of band so it stays out of source control (see Configuration blocks):

    Terminal window
    export NSCHEMA_POSTGRES_CONNECTION_STRING="Host=localhost;Database=app;Username=postgres;Password=postgres"
  2. Import the schema into a directory:

    Terminal window
    nschema import --out-dir ./schemas

    This writes the live schema out as .sql files. To adopt only part of the database, you can use the same --scope argument that works with plan and apply:

    Terminal window
    nschema import --out-dir ./schemas --scope app --scope billing

    As a safety measure, import won’t import into a directory that already contains .sql files; pass --force if you really mean to re-import over existing files.

  3. Review and commit. Read the generated files, tidy them if you like, and check them into source control.

  4. Verify a no-op plan. A plan immediately after import should show no changes:

    Terminal window
    nschema plan
  5. Manage changes from here. Edit the .sql files and use the normal plan / apply workflow from now on.

If you plan to use a state store for offline planning, don’t forget to seed it from the live database with nschema refresh once your BACKEND block is configured:

Terminal window
nschema refresh