NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / IMPORT A POSTGRESQL DATABASE

Import a PostgreSQL database

Copies a live PostgreSQL database into a new RasterizedDB database in one run: it reads the source's schema, creates the tables, streams the rows in, then adds the primary keys, unique constraints and foreign keys, and exits. The source is only read. Use it to move an application's data over, or to try RasterizedDB on a copy of real data.

Before you start

  • The server binary (see the install recipe), and network access from this machine to the PostgreSQL server.
  • A RasterizedDB data directory that has been started once, so its first role exists: the new database starts with the roles of the directory's default database. The local-dev or systemd-service recipe makes one.
  • No RasterizedDB server running on that directory during the import. Stop it first; start it again afterwards.
  • A PostgreSQL role that can read the tables, its password in PGPASSWORD.
  • Quiet writes on the source. Each table is copied as of the moment its copy starts; rows written to the source during the import may or may not come across.

Settings

The source is named with the usual PostgreSQL variables; the bash script reads them directly and the PowerShell script takes them as parameters (with the same variables as defaults).

bash variablePowerShell parameterDefaultWhat it does
RDB_BIN-RdbBinrasterizeddb / rasterizeddb.exeThe server binary.
RDB_DATA-Data./dataThe RasterizedDB data directory.
RDB_IMPORT_INTO-IntorequiredThe new database's name. It must not exist yet.
PGHOST-PgHostlocalhostSource host.
PGPORT-PgPort5432Source port.
PGUSER-PgUserpostgresSource role.
PGDATABASE-PgDatabaserequiredSource database.
PGPASSWORD$env:PGPASSWORDnoneSource password. Never put it on the command line.
RDB_IMPORT_SSLMODE-SslModepreferdisable, prefer, require or verify-full. require encrypts without checking the server's identity; over any network you do not control, use verify-full.
RDB_IMPORT_SCHEMA-SchemapublicThe schema to read.
RDB_IMPORT_ONLY-Onlyall tablesTables to import (comma-separated in bash).
RDB_IMPORT_EXCLUDE-ExcludenoneTables to leave out.
RDB_IMPORT_JSON-JsonautoWhat json/jsonb columns become: auto uses a JSONB column wherever every document in it is an object and TEXT elsewhere; text always keeps the text as written; native always uses JSONB and refuses rows whose document is not an object.
RDB_IMPORT_WIDE_NUMERIC-WideNumericfailA numeric(p, s) with more than nine decimal places stops the import (fail), or becomes TEXT with every digit kept (text).
RDB_IMPORT_BATCH_ROWS-BatchRows5000Rows per transaction while loading.
RDB_IMPORT_WITHOUT_CONSTRAINTS=1-WithoutConstraintsoffImport the rows without primary keys, unique constraints and foreign keys.
RDB_IMPORT_DRY_RUN=1-DryRunoffReport what would be imported, and what would not come across unchanged, without creating anything.

Run it

Look first, then import:

sh
export PGHOST=pg.internal PGUSER=app PGDATABASE=shop PGPASSWORD='…'
RDB_DATA=/var/lib/rasterizeddb RDB_IMPORT_INTO=shop RDB_IMPORT_DRY_RUN=1 ./setup.sh
sudo systemctl stop rasterizeddb
sudo --preserve-env=PGHOST,PGUSER,PGDATABASE,PGPASSWORD -u rasterizeddb \
  RDB_BIN=/usr/local/bin/rasterizeddb RDB_DATA=/var/lib/rasterizeddb RDB_IMPORT_INTO=shop ./setup.sh
sudo systemctl start rasterizeddb

Run it as the user that owns the data directory (rasterizeddb under the systemd-service recipe). Run as root, it would leave the new database's files owned by root, and the service could not open them.

powershell
$env:PGPASSWORD = '…'
.\setup.ps1 -Data C:\ProgramData\RasterizedDB\data -Into shop -PgHost pg.internal -PgUser app -PgDatabase shop -DryRun
.\setup.ps1 -Data C:\ProgramData\RasterizedDB\data -Into shop -PgHost pg.internal -PgUser app -PgDatabase shop

The import ends with a report that names every difference between the source and what was created: dropped defaults, constraints that could not be carried over, views and sequences left behind. Read it before pointing an application at the copy.

Check that it works

Start the server again and compare row counts with the source:

sh
psql "postgresql://rasterized@127.0.0.1:5432/shop?sslmode=require" -c "SELECT count(*) FROM orders"
psql "host=pg.internal dbname=shop user=app" -c "SELECT count(*) FROM orders"

Stop or undo

If an import fails part way with an error, the new database is dropped, so nothing half-copied is left behind; the error says whether the removal succeeded. If the process is killed instead, drop the half-made database yourself before importing again. To remove an imported database later, connect to another database and DROP DATABASE shop.

Limits

  • One schema per run. Import another schema into another database with RDB_IMPORT_SCHEMA.
  • An import builds a new database; it does not update an existing one. To import again, drop the database first.
  • Views, materialised views and foreign tables are not copied; the report lists them.

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB: copy a live PostgreSQL database (schema, rows, then keys and
# constraints) into a new RasterizedDB database, then exit. Run it while no
# RasterizedDB server is using the data directory.
#
# The source is read with the usual PostgreSQL variables (PGHOST, PGPORT,
# PGUSER, PGDATABASE, PGPASSWORD), for example:
#   PGHOST=pg.internal PGUSER=app PGDATABASE=shop PGPASSWORD='…' RDB_IMPORT_INTO=shop ./setup.sh
set -euo pipefail

RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}"                         # the RasterizedDB data directory
RDB_IMPORT_INTO="${RDB_IMPORT_INTO:-}"                 # required: name of the new database
RDB_IMPORT_SSLMODE="${RDB_IMPORT_SSLMODE:-prefer}"     # disable, prefer, require or verify-full
RDB_IMPORT_SCHEMA="${RDB_IMPORT_SCHEMA:-public}"
RDB_IMPORT_ONLY="${RDB_IMPORT_ONLY:-}"                 # tables to import, comma-separated (default: all)
RDB_IMPORT_EXCLUDE="${RDB_IMPORT_EXCLUDE:-}"           # tables to leave out, comma-separated
RDB_IMPORT_JSON="${RDB_IMPORT_JSON:-auto}"             # auto, text or native
RDB_IMPORT_WIDE_NUMERIC="${RDB_IMPORT_WIDE_NUMERIC:-fail}"  # fail or text
RDB_IMPORT_BATCH_ROWS="${RDB_IMPORT_BATCH_ROWS:-5000}"
RDB_IMPORT_WITHOUT_CONSTRAINTS="${RDB_IMPORT_WITHOUT_CONSTRAINTS:-0}"  # 1 skips keys and foreign keys
RDB_IMPORT_DRY_RUN="${RDB_IMPORT_DRY_RUN:-0}"          # 1 reports what would come across, creates nothing

die() { echo "error: $*" >&2; exit 1; }

command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -n "$RDB_IMPORT_INTO" ] || die "set RDB_IMPORT_INTO to the name of the new database"
[ -n "${PGDATABASE:-}" ] || die "set PGDATABASE (and PGHOST, PGPORT, PGUSER, PGPASSWORD) to the source database"
[ -n "${PGPASSWORD:-}" ] || echo "warning: PGPASSWORD is not set; only a source that needs no password will work" >&2

# The new database starts with the roles of the directory's default database,
# so the directory must have been started once (with its first role) already.
[ -d "$RDB_DATA" ] && [ -n "$(ls -A "$RDB_DATA")" ] \
  || die "$RDB_DATA is empty: start a server on it once first, so the role you will log in with exists"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"
if [ -f "$RDB_DATA/rasterizeddb.lock" ] && command -v flock >/dev/null 2>&1 \
  && ! flock -n "$RDB_DATA/rasterizeddb.lock" true; then
  die "a server is running on $RDB_DATA; stop it first (sudo systemctl stop rasterizeddb)"
fi

args=(--location "$RDB_DATA" --pg-import-into "$RDB_IMPORT_INTO"
  --pg-import-host "${PGHOST:-localhost}" --pg-import-port "${PGPORT:-5432}"
  --pg-import-user "${PGUSER:-postgres}" --pg-import-database "$PGDATABASE"
  --pg-import-sslmode "$RDB_IMPORT_SSLMODE" --pg-import-schema "$RDB_IMPORT_SCHEMA"
  --pg-import-json "$RDB_IMPORT_JSON" --pg-import-wide-numeric "$RDB_IMPORT_WIDE_NUMERIC"
  --pg-import-batch-rows "$RDB_IMPORT_BATCH_ROWS")
[ -z "$RDB_IMPORT_ONLY" ] || args+=(--pg-import-only-tables "$RDB_IMPORT_ONLY")
[ -z "$RDB_IMPORT_EXCLUDE" ] || args+=(--pg-import-exclude-tables "$RDB_IMPORT_EXCLUDE")
[ "$RDB_IMPORT_WITHOUT_CONSTRAINTS" != 1 ] || args+=(--pg-import-without-constraints)
[ "$RDB_IMPORT_DRY_RUN" != 1 ] || args+=(--pg-import-dry-run)

echo "Importing $PGDATABASE from ${PGHOST:-localhost}:${PGPORT:-5432} (schema $RDB_IMPORT_SCHEMA) into $RDB_IMPORT_INTO at $RDB_DATA"
"$RDB_BIN" "${args[@]}"

if [ "$RDB_IMPORT_DRY_RUN" = 1 ]; then
  echo "Dry run: nothing was created."
else
  echo
  echo "Done. Start the server on $RDB_DATA as usual, then connect to the new database:"
  echo "  psql \"postgresql://rasterized@127.0.0.1:5432/$RDB_IMPORT_INTO?sslmode=require\""
fi
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB: copy a live PostgreSQL database (schema, rows, then keys and
  constraints) into a new RasterizedDB database, then exit. Run it while no
  RasterizedDB server is using the data directory.
.DESCRIPTION
  The source password is read from $env:PGPASSWORD, never from the command line.
.EXAMPLE
  $env:PGPASSWORD = '…'
  .\setup.ps1 -Into shop -PgHost pg.internal -PgUser app -PgDatabase shop
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
    # The RasterizedDB data directory.
    [string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
    # Name of the new database.
    [string]$Into = $env:RDB_IMPORT_INTO,
    [string]$PgHost = $(if ($env:PGHOST) { $env:PGHOST } else { 'localhost' }),
    [int]$PgPort = $(if ($env:PGPORT) { [int]$env:PGPORT } else { 5432 }),
    [string]$PgUser = $(if ($env:PGUSER) { $env:PGUSER } else { 'postgres' }),
    [string]$PgDatabase = $env:PGDATABASE,
    [ValidateSet('disable', 'prefer', 'require', 'verify-full')]
    [string]$SslMode = $(if ($env:RDB_IMPORT_SSLMODE) { $env:RDB_IMPORT_SSLMODE } else { 'prefer' }),
    [string]$Schema = $(if ($env:RDB_IMPORT_SCHEMA) { $env:RDB_IMPORT_SCHEMA } else { 'public' }),
    # Tables to import (default: all) and to leave out.
    [string[]]$Only = @(),
    [string[]]$Exclude = @(),
    [ValidateSet('auto', 'text', 'native')]
    [string]$Json = $(if ($env:RDB_IMPORT_JSON) { $env:RDB_IMPORT_JSON } else { 'auto' }),
    [ValidateSet('fail', 'text')]
    [string]$WideNumeric = $(if ($env:RDB_IMPORT_WIDE_NUMERIC) { $env:RDB_IMPORT_WIDE_NUMERIC } else { 'fail' }),
    [int]$BatchRows = $(if ($env:RDB_IMPORT_BATCH_ROWS) { [int]$env:RDB_IMPORT_BATCH_ROWS } else { 5000 }),
    # Skip primary keys, unique constraints and foreign keys.
    [switch]$WithoutConstraints,
    # Report what would come across; create nothing.
    [switch]$DryRun
)
$ErrorActionPreference = 'Stop'

$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }
if (-not $Into) { throw 'Pass -Into with the name of the new database.' }
if (-not $PgDatabase) { throw 'Pass -PgDatabase (or set $env:PGDATABASE) with the source database.' }
if (-not $env:PGPASSWORD) { Write-Warning 'PGPASSWORD is not set; only a source that needs no password will work.' }

# The new database starts with the roles of the directory's default database,
# so the directory must have been started once (with its first role) already.
if (-not (Test-Path -LiteralPath $Data) -or -not (Get-ChildItem -LiteralPath $Data -Force | Select-Object -First 1)) {
    throw "$Data is empty: start a server on it once first, so the role you will log in with exists."
}
$Data = (Resolve-Path -LiteralPath $Data).Path

$serverArgs = @('--location', $Data, '--pg-import-into', $Into,
    '--pg-import-host', $PgHost, '--pg-import-port', "$PgPort", '--pg-import-user', $PgUser,
    '--pg-import-database', $PgDatabase, '--pg-import-sslmode', $SslMode, '--pg-import-schema', $Schema,
    '--pg-import-json', $Json, '--pg-import-wide-numeric', $WideNumeric, '--pg-import-batch-rows', "$BatchRows")
if ($Only) { $serverArgs += @('--pg-import-only-tables', ($Only -join ',')) }
if ($Exclude) { $serverArgs += @('--pg-import-exclude-tables', ($Exclude -join ',')) }
if ($WithoutConstraints) { $serverArgs += '--pg-import-without-constraints' }
if ($DryRun) { $serverArgs += '--pg-import-dry-run' }

Write-Host "Importing $PgDatabase from ${PgHost}:$PgPort (schema $Schema) into $Into at $Data"
& $cmd.Source @serverArgs
if ($LASTEXITCODE -ne 0) { throw "The import failed (exit $LASTEXITCODE); the message is above. If a server is running on $Data, stop it first." }

if ($DryRun) { Write-Host 'Dry run: nothing was created.' }
else {
    Write-Host ''
    Write-Host "Done. Start the server on $Data as usual, then connect to the new database:"
    Write-Host "  psql `"postgresql://rasterized@127.0.0.1:5432/${Into}?sslmode=require`""
}
✓ page rendered in 171 µs axum + tera + htmx · no other javascript