Skip to main content

Postgres Datastore

@svendowideit/postgres-datastorev2026.08.13.1beta· 2mo agoBEHAVIORSDATASTORES
01README

PostgreSQL datastore and model type for swamp. Swamp model schemas (Zod) map directly to PostgreSQL table schemas (DDL) with native column types. Every data mutation is automatically versioned using SQL:2011 SYSTEM VERSIONING via the periods extension.

Quick Start

1. Start PostgreSQL with the periods extension:

  -e POSTGRES_USER=swamp -e POSTGRES_PASSWORD=swamp -e POSTGRES_DB=swamp \
  -p 5432:5432 \
  pgxn/pgxn-tools:latest \
  bash -c "docker-entrypoint.sh postgres & sleep 3 && psql -U swamp -d swamp -c 'CREATE EXTENSION IF NOT EXISTS periods;' && wait"

2. Configure swamp to use the datastore:

  type: "@svendowideit/postgres-datastore"
  config:
    connectionString: "postgres://swamp:swamp@localhost:5432/swamp"
    schema: "swamp"
    ssl: "disable"

3. Verify it's healthy: bash swamp datastore status # Expected: healthy: true, periods: available 4. Create a model and a versioned table:

  --global-args '{"connectionString":"postgres://swamp:swamp@localhost:5432/swamp","schema":"swamp"}'

swamp model method run servers create --args '{
  "tableName": "servers",
  "schema": {
    "id": "string.uuid",
    "hostname": "string",
    "ip": "string",
    "region": {"type": "string", "optional": true},
    "tags": "json",
    "created_at": "string.datetime"
  }
}' ```
**5. Insert, query, and version data:**
```bash # Insert rows swamp model method run servers run --args '{
  "tableName": "servers", "operation": "insert",
  "data": [
    {"id":"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11","hostname":"web-01","ip":"10.0.1.10","region":"us-east-1","tags":["production"],"created_at":"2026-01-15T10:00:00Z"}
  ]
}'
# Update (creates a new version automatically) swamp model method run servers run --args '{
  "tableName": "servers", "operation": "update",
  "data": [{"id":"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11","region":"eu-west-1"}]
}'
# Query current data swamp model method run servers query --args '{"tableName":"servers"}'
# List versions swamp model method run servers list_versions --args '{"tableName":"servers"}'
# Query historical data at a specific version swamp model method run servers query --args '{"tableName":"servers","versionId":"<uuid-from-list_versions>"}' ```
**6. Import an existing PostgreSQL table:**
```bash swamp model method run servers import_table --args '{
  "sourceSchema": "public",
  "sourceTable": "legacy_inventory",
  "mode": "readonly"
}' ```
## What You Get
Each swamp model becomes a typed PostgreSQL table with native column types (UUID, TEXT, BIGINT, BOOLEAN, TIMESTAMPTZ, JSONB, etc.) and automatic version history via a companion `_history` table. You can query your data directly with any PostgreSQL client:
```sql SELECT * FROM swamp.servers;                    -- current rows SELECT * FROM swamp.servers__as_of('2026-01-15 10:02:00+00');  -- point-in-time SELECT * FROM swamp.servers_history WHERE id = '...';          -- full audit trail SELECT * FROM swamp._versions WHERE table_name = 'servers';    -- version log ```
## Prerequisites
- PostgreSQL 15+ with the `periods` extension installed - The datastore auto-creates the required schema and installs the extension
  on first use (requires CREATE EXTENSION privileges)

See the README for full documentation on schema migration, backup/restore, security, upgrades, and troubleshooting.
02Behaviors1
@svendowideit/postgres-modelv2026.08.12.1postgres_model/mod.ts

Global Arguments

ArgumentTypeDescription
connectionStringstringPostgreSQL connection URI
schemastringPostgreSQL schema
fn create(tableName: string, schema: record)
Create a PostgreSQL table from a Zod schema definition with system versioning
ArgumentTypeDescription
tableNamestringName of the table to create
schemarecordJSON representation of the Zod schema (field name → type descriptor)
fn run(tableName: string, operation: enum, data: array)
Execute a data operation (insert/update/delete) and create a version snapshot
ArgumentTypeDescription
tableNamestringTarget table name
operationenumData operation to perform
dataarrayArray of records to insert, update, or delete
fn query(tableName: string, versionId?: string, columns?: array, where?: string, limit: number)
Query current or historical data from a versioned table
ArgumentTypeDescription
tableNamestringTarget table name
versionId?stringIf provided, query rows as they existed at this version
columns?arrayColumns to return (default: all)
where?stringRaw SQL WHERE clause fragment (without the WHERE keyword)
limitnumberMaximum rows to return
fn list_versions(tableName: string)
List all versions for a table, newest first
ArgumentTypeDescription
tableNamestringTarget table name
fn upgrade(tableName: string, newSchema: record)
Migrate a table schema using gradual row migration
ArgumentTypeDescription
tableNamestringTarget table name
newSchemarecordNew JSON schema (field name → type descriptor)
fn gc(tableName: string, keepCount: number)
Garbage-collect old versions, keeping the most recent
ArgumentTypeDescription
tableNamestringTarget table name
keepCountnumberNumber of recent versions to keep
fn import_table(sourceSchema: string, sourceTable: string, mode: enum, discoverSchema: boolean, modelType?: string)
Import an existing PostgreSQL table into the swamp schema manager
ArgumentTypeDescription
sourceSchemastringPostgreSQL schema where the table lives
sourceTablestringName of the table to import
modeenumAccess mode for the imported table
discoverSchemabooleanWhether to discover the schema from information_schema
modelType?stringModel type to register the import under (defaults to @svendowideit/postgres-model)

Resources

result(infinite)— Operation result data
table_metadata(infinite)— Stored table schema for use during upgrades
03Datastores1
PostgreSQL Datastoreconfigurable
@svendowideit/postgres-datastoremod.ts

PostgreSQL datastore with periods extension for SQL:2011 SYSTEM VERSIONING. Distributed locking via pg_advisory_lock.

Config Fields

FieldTypeDescription
connectionStringstringPostgreSQL connection URI
maxConnectionsnumber
idleTimeoutMsnumber
connectTimeoutMsnumber
04Stats
B
80 / 100
Downloads
15
Archive size
83.9 KB
  • Has README or module doc2/2earned
  • README has a code example1/1earned
  • README is substantive1/1earned
  • Most symbols documented1/1earned
  • No slow types (deprecated)1/1earned
  • Dependencies pass trust audit2/2earned
  • Has description1/1earned
  • Platform support declared (or universal)2/2earned
  • License1/2partial

    no SPDX license declared

  • Verified public repository0/2missing
05Platforms
06Labels