Import from PostgreSQL
RasterizedDB can copy a live PostgreSQL database into a new RasterizedDB database: the schema first, then every row, then the keys. Use it to migrate an application off PostgreSQL. It is a one-shot copy: it does not write back to PostgreSQL, does not keep the two in sync, and only ever creates a new database.
You can run it two ways, with the same options and the same result:
- the
IMPORT DATABASEstatement, sent to a running server, or - the
--pg-import-*flags, which run the import when the server starts and then exit.
Before you start
- Plan a quiet source. Each table is copied as of the moment its copy starts. If the application keeps writing to PostgreSQL during the import, tables copied at different moments can disagree. Stop writes, or import from a replica or a restored snapshot.
- Pick a new name for the target. An import refuses a database name that already exists here. Drop the old one first or use another name.
- Check the source names. Table and column names must be plain identifiers (letters, digits, underscores, not needing quotes), and no table may have two columns whose names differ only in case. An import that finds either stops before creating anything and lists every offending name at once. Rename them in the source, or leave those tables out.
- Use a superuser.
IMPORT DATABASEis an administrative statement; ordinary roles are refused. - The source role needs to read the schema's catalogue and
SELECTevery table being imported.
Step 1: dry run
DRY RUN connects, reads the catalogue and plans the whole import, then reports what it would do and every difference it would introduce, without creating anything:
IMPORT DATABASE FROM POSTGRES 'postgresql://migrator:secret@pg.internal:5432/shop?sslmode=verify-full'
DRY RUN
INTO shop;The result is one text column, one line per row:
Would import 3 tables from postgresql://migrator:***@pg.internal:5432/shop?sslmode=verify-full into "shop"
source server: PostgreSQL 17.2
customers about 120000 rows 0.0s (2 keys)
orders about 940000 rows 0.0s (1 key, 1 foreign key)
order_lines about 3100000 rows 0.0s (1 key, 1 foreign key)
about 4160000 rows to copy
2 Things that did not come across unchanged:
- orders.id is generated by a sequence; its values are imported but the column will not allocate new ones
- customers.created_on: date became TIMESTAMP at midnight; this engine has no date-only typeRow counts in a dry run are PostgreSQL's estimates; a table that has never been analysed shows row count unknown (never analysed). Fix anything that stops the plan, decide whether the listed differences are acceptable, then run it for real.
Step 2: run the import
From SQL, on a running server
Connect to the server as a superuser over the PostgreSQL protocol (for example with psql) and run:
IMPORT DATABASE FROM POSTGRES 'postgresql://migrator:secret@pg.internal:5432/shop?sslmode=verify-full'
INTO shop;The statement runs on your connection and returns when the import is finished, with the same report as the dry run (now with real row counts and times). Keep the session open for as long as it takes. It cannot run inside a transaction block (BEGIN … COMMIT); it fails with SQLSTATE 25001 there.
The same statement with the connection spelled out instead of as a URI:
IMPORT DATABASE FROM POSTGRES
HOST 'pg.internal' PORT 5432
DATABASE 'shop' USER 'migrator' PASSWORD 'secret'
SSLMODE 'verify-full'
SCHEMA 'public'
EXCLUDE TABLES (audit_log, sessions)
INTO shop;From the command line, with the server stopped
The flag form opens the data directory itself, so run it when no server is using that directory: on a new machine, or with the service stopped. (A server holds an exclusive lock on its data directory, so a second process pointed at it is refused at start-up.) It prints the report and exits, unless --pg-import-and-serve is given, in which case the server starts normally afterwards.
sudo systemctl stop rasterizeddb
export PGPASSWORD='secret'
sudo -E -u rasterizeddb rasterizeddb \
--location /var/lib/rasterizeddb \
--pg-import-from 'postgresql://migrator@pg.internal:5432/shop?sslmode=verify-full' \
--pg-import-into shop
sudo systemctl start rasterizeddbRun it as the user that owns the data directory (the one the service runs as). Run as root, it would create the new database's files owned by root, and the service could not open them afterwards.
While it runs
The target database exists from the start but refuses connections until the import finishes. A client that tries gets SQLSTATE 57P03: database "shop" is being imported and is not ready for connections yet. This keeps applications from writing rows into tables whose keys have not been put back yet.
If the import fails at any point after the target was created, the target database is dropped again, and the error says whether that worked. You never get half a database that looks like a whole one.
When it finishes, the new database has the same roles as the server's default database, so the accounts you already use can connect to it.
Options
Every clause has a matching flag. Clauses can be given in any order before INTO.
| Clause | Flag | Default | What it does |
|---|---|---|---|
'<uri>' (first, after POSTGRES) | --pg-import-from <URI> | Source connection URI, postgresql://user:password@host:port/dbname?sslmode=…. | |
HOST '<host>' | --pg-import-host <HOST> | $PGHOST, else localhost | Source host. |
PORT <n> | --pg-import-port <PORT> | $PGPORT, else 5432 | Source port. |
DATABASE '<name>' | --pg-import-database <NAME> | $PGDATABASE | Source database. Required, from one place or another. |
USER '<user>' | --pg-import-user <USER> | $PGUSER, else postgres | Source user. |
PASSWORD '<password>' | --pg-import-password <PASSWORD> | $PGPASSWORD | Source password. Prefer PGPASSWORD: a password on the command line is visible to other users in ps. |
SSLMODE '<mode>' | --pg-import-sslmode <MODE> | prefer | disable, prefer, require or verify-full (see below). |
SCHEMA '<schema>' | --pg-import-schema <NAME> | public | The one schema to read. |
ONLY TABLES (a, b) | --pg-import-only-tables a,b | all tables | Import only these. The flag is repeatable and takes a comma-separated list. |
EXCLUDE TABLES (c) | --pg-import-exclude-tables c | none | Leave these out. Repeatable, comma-separated. |
BATCH <rows> | --pg-import-batch-rows <N> | 5000 | Rows per transaction on the way in. |
JSON AS TEXT|NATIVE | --pg-import-json auto|text|native | auto | What json and jsonb columns become (see JSON columns). |
WIDE NUMERIC AS FAIL|TEXT | --pg-import-wide-numeric fail|text | fail | What to do with a numeric declared with more decimal places than RasterizedDB can store. |
WITHOUT CONSTRAINTS | --pg-import-without-constraints | off | Import the rows without primary keys, unique constraints and foreign keys. |
DRY RUN | --pg-import-dry-run | off | Plan and report, create nothing. |
INTO <name> | --pg-import-into <NAME> | Name of the new database. Required. On the command line, setting it is what runs an import. | |
--pg-import-and-serve | off | After a command-line import, start the server instead of exiting. |
IMPORT FROM POSTGRESQL …, IMPORT FROM PG … and leaving out the word DATABASE are also accepted. ONLY can also be written INCLUDE.
Where connection settings come from. On the command line, a flag beats the URI, and the URI beats the libpq environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE, PGSSLMODE). PGPASSWORD is used even when a URI is given, as long as no password flag is, so you can keep the password out of the written-down URI. In the SQL statement the server's own environment is not consulted; say everything in the statement.
TLS. The sslmode values mean what they mean in libpq. require encrypts but does not check who the server is, so anyone who can intercept the connection can read the password and every row. Across anything but a trusted network, use verify-full, which checks the certificate against the public root certificates and the host name. verify-ca is accepted and treated as verify-full. allow is treated as prefer.
What comes across
The import reads PostgreSQL's catalogue directly, so partitioned tables are read once through their parent (not once per partition and again through the parent), and a column of a domain is created as the domain's base type, with its length or scale.
Types
| PostgreSQL | Becomes | Note |
|---|---|---|
bool | BOOLEAN | |
int2, int4, int8 | SMALLINT, INTEGER, BIGINT | |
oid, xid, cid | BIGINT | unsigned 32-bit values need the wider column |
float4, float8 | REAL, DOUBLE PRECISION | |
numeric(p, s) | NUMERIC(p, s) | up to 30 decimal places; finer is refused unless WIDE NUMERIC AS TEXT |
numeric (no scale) | NUMERIC | every value is checked as it arrives |
numeric(p, s) with negative s | NUMERIC | values held exactly, but new values are not rounded to the scale |
money | NUMERIC | the exact amount, without the currency symbol |
character(n) | CHARACTER(n) | length kept; compared and shown blank-padded |
bpchar without a length | BPCHAR | compares the same, does not keep trailing spaces |
varchar(n), varchar | VARCHAR(n), VARCHAR | |
text, name, citext, xml | TEXT | |
"char" | TEXT | |
uuid | UUID | |
inet, cidr | INET | |
bytea | BYTEA | |
timestamp | TIMESTAMP | |
timestamptz | TIMESTAMPTZ | |
date | TIMESTAMP | at midnight; there is no date-only type |
| any array | TEXT[] | elements are stored as text whatever the element type |
json, jsonb | JSONB or TEXT | see JSON columns |
enums, composites, ranges, multiranges, time, timetz, interval, macaddr, bit, varbit, tsvector, tsquery, geometric types, pg_lsn, anything unrecognised | TEXT | holding PostgreSQL's own text rendering of the value |
Every type change is named in the report. Nothing is skipped: a type with no counterpart becomes TEXT holding PostgreSQL's rendering, which is exact.
Every value is checked. Each value is validated against its target column before it is written. A value that cannot be stored exactly (for example a numeric with more decimal places than its column, NaN in a numeric, or a timestamp out of range) stops the import with the table, row and column named, rather than being stored as something else. A generated column's stored values are imported as ordinary data.
Keys and defaults
- Primary keys and unique constraints come across, up to 8 columns each. To keep the load fast, each table is created with its keys, the keys are dropped while rows are loaded, and then added back, which checks every row once.
- Unique indexes over plain columns come across as unique constraints. Partial unique indexes and unique indexes over expressions do not; the report lists them.
- Foreign keys, composite ones included, are added once every table holds its rows, so load order and reference cycles do not matter.
ON DELETE/ON UPDATEactions andMATCH FULLare kept. A key that wasNOT VALIDin the source is addedNOT VALID. A key that references a table outside the imported schema, or one you left out, is not carried over and is reported. NOT NULLcomes across on every column.- Defaults: constants come across.
now(),CURRENT_TIMESTAMPandCURRENT_DATEbecomeCURRENT_TIMESTAMP. Anything else that calls into PostgreSQL (a function, another column) is dropped and reported. - Sequences and identity columns: the values in the table come across as data, but the column's
nextval(…)default or identity is dropped. Aserial,bigserialor identity column will not generate new ids after the import until you give it a default again; see Schema objects for sequences.
What does not come across
- Views, materialized views, sequences and foreign tables. The report counts them. Recreate views and sequences afterwards; see Schema objects.
- Ordinary (non-unique) indexes. Recreate the ones your queries need with
CREATE INDEX; see Indexes. CHECKconstraints, triggers, functions, procedures, grants and comments.- Other schemas. One import reads one schema. To bring several, run one import per schema, each into its own database.
- Changes made after the import. There is no incremental or repeated sync.
JSON columns
--pg-import-json (or JSON AS … in SQL) decides what a json or jsonb column becomes:
| Value | Result |
|---|---|
auto (default) | A native JSONB column. |
text | TEXT, holding each document exactly as PostgreSQL rendered it. |
native | Always a native JSONB column. |
Typed drivers expect a jsonb column to come back as JSON, which is why auto uses JSONB. Choose text when the application must read back the exact original text of each document.
Trap: JSON whose keys are data, with --json-shadow-tables
The server flag --json-shadow-tables (off by default) stores JSON columns by taking each document apart into a table of its own, with a column per key. With it on, auto uses JSONB only where every document in the column is an object or an array, and TEXT otherwise.
That storage cannot cope with documents whose keys are data: a map keyed by user ids, dates, product codes or column names. Every new key adds a column, and each new column rewrites every row stored so far, so the load slows to a crawl as it goes. If the server runs with --json-shadow-tables on and the source has such columns, import them with --pg-import-json text (or JSON AS TEXT), or leave the flag off. See JSON.
Wide NUMERIC columns
RasterizedDB's NUMERIC keeps at most 30 decimal places. A column declared finer than that stops the plan, naming the column, before anything is created:
IMPORT DATABASE FROM POSTGRES 'postgresql://migrator@pg.internal/ledger'
WIDE NUMERIC AS TEXT
INTO ledger;WIDE NUMERIC AS TEXT (--pg-import-wide-numeric text) imports such columns as TEXT: every digit is kept, but the column is no longer a number. Otherwise, change the column in the source or leave the table out.
After the import
- Read the report's list of things that did not come across unchanged.
- Recreate what was not carried: secondary indexes, views, sequences or defaults for id columns,
CHECKconstraints. - Point the application at the new database. Its accounts are the server's default database's roles; manage them as in Security.
- Run your application's tests against it before switching over. PostgreSQL compatibility lists where RasterizedDB answers differently.
Going the other way: pg_dump
PostgreSQL's own pg_dump can dump a RasterizedDB database over the PostgreSQL protocol, for a restore into PostgreSQL or into another RasterizedDB database:
pg_dump -h db.internal -p 5432 -U rasterized --no-owner -Fc -f app.dump app
pg_restore --no-owner -h pg.internal -d app app.dumpPlain SQL output works too:
pg_dump -h db.internal -p 5432 -U rasterized --no-owner -Fp -f app.sql app
psql -h pg.internal -d app -f app.sqlA dump carries tables and their rows, column types, NOT NULL, defaults, CHECK, primary, unique and foreign keys, secondary indexes, sequences with their current values, identity columns, views and materialized views. It leaves out functions and procedures, triggers, domains (their columns keep the base type), grants and column collations; pg_dump --verbose prints a warning naming what was left out.
A partitioned table is dumped as one plain table with all its rows, followed by a CREATE INDEX … USING partition (…) statement that converts it back into a partitioned table when restored into RasterizedDB. PostgreSQL rejects that one statement, keeps a plain table with every row, and pg_restore reports one ignored error. To restore into PostgreSQL without it, leave the entry out:
pg_restore -l app.dump | grep -v partition_key > list
pg_restore --no-owner -L list -h pg.internal -d app app.dumpUse --no-owner when the target does not have the same roles. To load a dump that PostgreSQL made, use IMPORT DATABASE FROM POSTGRES instead of pg_restore.
Limits
- One-way, one-shot, one schema per import. The target must be a new database.
- Table and column names that need quoting, or columns differing only in case, stop the import.
- Sequences, identity and other non-constant defaults are dropped; id columns do not generate new values until you set them up again.
- Non-unique indexes,
CHECKconstraints, views, triggers, functions and grants are not imported. - Partial and expression unique indexes, keys over more than 8 columns, and foreign keys leaving the imported tables are not imported (each is reported).
- Every array becomes
TEXT[];datebecomesTIMESTAMP; types with no counterpart becomeTEXT. - The command-line form needs the data directory to itself: stop the server first, or use the SQL form.