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.
-
Declare the provider. Import reads from a live database, so it needs a
PROVIDERblock naming the provider and pinning its plugin version. Create a single.sqlfile in your project directory with just that block — the schema files themselves will come from the import:-- provider.sqlPROVIDER 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" -
Import the schema into a directory:
Terminal window nschema import --out-dir ./schemasThis writes the live schema out as
.sqlfiles. To adopt only part of the database, you can use the same--scopeargument that works withplanandapply:Terminal window nschema import --out-dir ./schemas --scope app --scope billingAs a safety measure,
importwon’t import into a directory that already contains.sqlfiles; pass--forceif you really mean to re-import over existing files. -
Review and commit. Read the generated files, tidy them if you like, and check them into source control.
-
Verify a no-op plan. A plan immediately after import should show no changes:
Terminal window nschema plan -
Manage changes from here. Edit the
.sqlfiles and use the normal plan / apply workflow from now on.
Seeding state at the same time
Section titled “Seeding state at the same time”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:
nschema refresh