Adopting an existing database
import { Steps } from “@astrojs/starlight/components”;
You don’t have to start from an empty database. nschema import reads
a live schema and writes it out as DDL source files, so you can adopt
an existing database and manage it going forward.
-
Point at the database. Set the connection string and a
PROVIDER postgresblock (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, scope it:Terminal window nschema import --out-dir ./schemas --scope app --scope billingimportrefuses to overwrite 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. This is now your desired schema.
-
Verify a no-op plan. A plan immediately after import should show no changes — proof that NSchema’s model of the database matches reality:
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, seed it from the live
database with nschema refresh once your BACKEND block is
configured:
nschema refreshTip: diff import against recorded state
Section titled “Tip: diff import against recorded state”import output is canonicalised the same way NSchema records state, so you can compare a fresh
import against nschema show to spot differences between the live
database and your recorded state.