> For the complete documentation index, see [llms.txt](https://docs.adiom.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.adiom.io/reference/connectors/postgresql.md).

# PostgreSQL

The PostgreSQL connector is supported both as a source and a destination. It is built into dsync/dsynct and connects directly using a PostgreSQL connection URL. As a source it copies tables and then follows changes through logical replication.

## Configuration

Provide a connection URL as the source or destination argument. Both the `postgresql://` and `postgres://` schemes are accepted. The URL selects one database:

```
postgresql://user:password@host:5432/dbname
```

You must list the tables to sync with `--namespace`. Tables are not discovered automatically. A namespace is `schema.table`, and the schema is required even for `public`:

```bash
dsynct sync \
--namespace public.orders \
--namespace public.customers \
postgresql://user:password@host:5432/shop $DESTINATION
```

Connector options go directly after the connection URL.

| Option                        | Default      | Description                                                                                                                                                                                                                                     |
| ----------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--replication-slot`          | `dsync_slot` | Name of the logical replication slot used for CDC.                                                                                                                                                                                              |
| `--publication-name`          | `dsync_pub`  | Name of the publication used for CDC.                                                                                                                                                                                                           |
| `--manual`                    | `false`      | Do not create the replication slot and publication. Use this when you create and manage them yourself.                                                                                                                                          |
| `--enable-replica-mode`       | `true`       | Run every session with `session_replication_role = 'replica'`, which disables triggers and rules on a destination. Requires a superuser. Set `--enable-replica-mode=false` for other users.                                                     |
| `--page-size`                 | `1000`       | Number of rows read per query during initial sync.                                                                                                                                                                                              |
| `--doc-partition`             | `100000`     | Approximate number of rows per initial sync task.                                                                                                                                                                                               |
| `--estimated-count-threshold` | `1000000`    | Tables with an estimated row count below this value are counted exactly for progress reporting.                                                                                                                                                 |
| `--stream-max-batch-size`     | `100`        | Number of change events after which a batch is sent to the destination. A soft limit: whole transactions are kept together, a batch is also cut at every table change, and an idle stream sends each transaction on its own.                    |
| `--stream-max-batch-wait`     | `5s`         | How long an incomplete batch may wait. Also soft: it is checked when the next transaction arrives.                                                                                                                                              |
| `--stream-flush-delay`        | `3m`         | How long after receiving a commit the connector confirms it to PostgreSQL, which then frees the write-ahead log up to that point. Keep it longer than the cursor save interval of the sync, so that a restart can resume from the saved cursor. |

## Prerequisites

### As a Source

* Every table must have a primary key. A table without one, or a namespace given without its schema, fails at start with `syntax error at end of input`. The message comes from the query that reads the key definition.
* Primary key constraint names must be unique in the database. PostgreSQL names them `<table>_pkey` by default, so a table with the same name in two schemas, for example `public.orders` and `archive.orders`, is the usual cause of a clash. See [Limitations](#limitations).
* Composite primary keys may only contain integer, text, boolean, floating point and `bytea` columns. See [Limitations](#limitations).
* The user needs `SELECT` on the tables, plus at least one other privilege on them (for example `REFERENCES`) or ownership, so that the primary key definition is visible. With `SELECT` alone the key is invisible and the sync fails with the same `syntax error at end of input`.
* A user that is not a superuser must pass `--enable-replica-mode=false`. On PostgreSQL 15 and later, `GRANT SET ON PARAMETER session_replication_role TO <user>` is an alternative.

For CDC, in addition:

* The server must run with `wal_level=logical`. Otherwise the sync fails with `logical decoding requires wal_level >= logical`.
* The user needs the `REPLICATION` attribute.
* The connector creates a publication for the listed tables and a replication slot when a sync starts. For that, the user must own the tables and be allowed to create publications in the database. If you cannot grant this, create both yourself and pass `--manual`:

```sql
CREATE PUBLICATION dsync_pub FOR TABLE public.orders, public.customers;
SELECT pg_create_logical_replication_slot('dsync_slot', 'pgoutput');
```

Create the publication before the slot.

{% hint style="warning" %}
The connector never removes the replication slot. An unused slot makes PostgreSQL keep its write-ahead log, and the disk fills up over time. Drop the slot and the publication when the migration is finished:

```sql
SELECT pg_drop_replication_slot('dsync_slot');
DROP PUBLICATION dsync_pub;
```

{% endhint %}

If you run more than one sync against the same database, give each its own `--replication-slot` and `--publication-name`. A new sync that uses the default names drops and recreates the existing slot and publication.

### As a Destination

* The tables must exist before the sync starts, each with a primary key. The connector does not create tables or columns, and it reads the table definitions once at start.
* The primary key column must not be named `_id`. The `_id` field of a document is never written, so the initial sync cannot fill such a column.
* The user needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the tables and `USAGE` on the schema. `SELECT` is needed because rows are written with `INSERT ... ON CONFLICT DO UPDATE`.
* A user that is not a superuser must pass `--enable-replica-mode=false`. Triggers and rules on the destination tables then fire for the synced rows. On PostgreSQL 15 and later, `GRANT SET ON PARAMETER session_replication_role TO <user>` lets a regular user keep replica mode.

## Data Type

The PostgreSQL connector uses **BSON**. Syncing to or from a JSON connector, such as Cosmos DB NoSQL, requires a [transformation](https://docs.adiom.io/enterprise/running-dsynct/data-transformations.md).

## ID Format

The ID is a single value named `_id`, built from the primary key. The connector also adds it to each document as the `_id` field. The primary key columns stay in the document under their own names.

| Primary key     | `_id`                                                                                                                |
| --------------- | -------------------------------------------------------------------------------------------------------------------- |
| One column      | The column value, with the BSON type of the column. For example an `integer` key gives a 32-bit integer.             |
| Several columns | A binary value that encodes all key values. It is not readable. Use the key columns in the document to read the key. |

## Emitted Format

This is what the PostgreSQL source hands to Dsync, and therefore what a [transformation](https://docs.adiom.io/enterprise/running-dsynct/data-transformations.md) receives.

**Namespace:** `schema.table`. Without a transform or `--namespace-mapping`, a MongoDB destination writes `public.orders` to the collection `orders` in the database `public`.

**Initial sync:** each row is emitted as one document with a field per column, named after the column, plus `_id`. `NULL` columns are present with a null value.

| PostgreSQL type                                                         | BSON type                                                                                                                                                                                        |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `smallint`, `integer`                                                   | 32-bit integer                                                                                                                                                                                   |
| `bigint`                                                                | 64-bit integer                                                                                                                                                                                   |
| `numeric`, `decimal`                                                    | Decimal128. Trailing zeros are dropped: `5.00` becomes `5`. `NaN`, and values with more than 34 significant digits, cannot be represented and stop the sync.                                     |
| `real`, `double precision`                                              | Double                                                                                                                                                                                           |
| `boolean`                                                               | Boolean                                                                                                                                                                                          |
| `text`, `varchar`                                                       | String                                                                                                                                                                                           |
| `char(n)`                                                               | String, padded with spaces to length `n`                                                                                                                                                         |
| `uuid`                                                                  | Binary (subtype 0) with the 16 bytes of the UUID. Not a string and not a BSON UUID.                                                                                                              |
| `bytea`                                                                 | Binary (subtype 0)                                                                                                                                                                               |
| `timestamp`, `timestamptz`, `date`                                      | Date, in UTC, with millisecond precision. A `timestamp` without time zone is read as UTC, and a `date` becomes midnight UTC. `infinity` and `-infinity` become the 32-bit integers `1` and `-1`. |
| `time`                                                                  | Document: `{"microseconds": <since midnight>, "valid": true}`                                                                                                                                    |
| `interval`                                                              | Document: `{"microseconds": ..., "days": ..., "months": ..., "valid": true}`                                                                                                                     |
| `json`, `jsonb`                                                         | The decoded value: document, array, string, number or boolean. All numbers become doubles, so integers above 2^53 lose precision.                                                                |
| Arrays, for example `integer[]`, `text[]`                               | Array. A multi-dimensional array is flattened into one array.                                                                                                                                    |
| Enum types                                                              | String                                                                                                                                                                                           |
| `inet`, `cidr`                                                          | Empty document `{}`. The value is lost. See [Limitations](#limitations).                                                                                                                         |
| `money`, `timetz`, `hstore`, composite types and other types not listed | String, in the text form PostgreSQL prints.                                                                                                                                                      |
| `point`, ranges, `bit`                                                  | Documents with the fields of the driver's Go type, for example `{"p": {"x": ..., "y": ...}, "valid": true}` for a point. Convert them in a transform.                                            |

**CDC:** changes are read through logical replication.

| Source operation | Event type | ID    | Payload                                                       |
| ---------------- | ---------- | ----- | ------------------------------------------------------------- |
| `INSERT`         | `INSERT`   | `_id` | The full row.                                                 |
| `UPDATE`         | `UPDATE`   | `_id` | The row after the update. See the note on large values below. |
| `DELETE`         | `DELETE`   | `_id` | None.                                                         |

### Example

Table `public.orders`:

```sql
CREATE TABLE public.orders (
  order_id   integer PRIMARY KEY,
  customer   text,
  total      numeric(10,2),
  created_at timestamptz,
  notes      text
);
INSERT INTO public.orders VALUES (7, 'Ann', 19.99, '2024-01-02 03:04:05+00', NULL);
```

| Stage                                                | ID                     | Payload                                                                                                                                       |
| ---------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Initial sync                                         | (part of the document) | `{"_id": 7, "order_id": 7, "customer": "Ann", "total": NumberDecimal("19.99"), "created_at": ISODate("2024-01-02T03:04:05Z"), "notes": null}` |
| `INSERT` of the same row                             | `_id` = `7`            | Same as above                                                                                                                                 |
| `UPDATE orders SET total = 20.50 WHERE order_id = 7` | `_id` = `7`            | `{"_id": 7, "order_id": 7, "customer": "Ann", "total": NumberDecimal("20.5"), "created_at": ISODate("2024-01-02T03:04:05Z"), "notes": null}`  |
| `DELETE FROM orders WHERE order_id = 7`              | `_id` = `7`            | None                                                                                                                                          |

## Writing to PostgreSQL

**Namespace:** the destination namespace must be an existing `schema.table`. Use `--namespace-mapping` to map a source namespace to it, for example `--namespace-mapping shop.orders:public.orders`.

**Columns:** each document field is written to the column with the same name. The `_id` field is not written. A field that has no column makes the write fail with `column "..." does not exist`, so remove such fields with a [transformation](https://docs.adiom.io/enterprise/running-dsynct/data-transformations.md).

**Primary key:** the key value comes from different places in the two phases. Both should give the same value, or the initial sync and CDC write different rows.

| Phase        | Key value taken from                                                                                                                                 |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| Initial sync | The document fields named after the primary key columns. A document without them fails with `null value in column ... violates not-null constraint`. |
| CDC          | The ID of the event (for example the MongoDB `_id`). A key field inside the document is ignored.                                                     |

So for a MongoDB source, a table with the primary key `order_id` needs documents where the field `order_id` exists and equals `_id`. If the documents only have `_id`, add the key field with a transform:

```yaml
mappings:
  - namespace: public.orders
    add: ["order_id"]
    cel:
      order_id: id
```

The `namespace` is the mapped one (`public.orders`), because namespace mapping is applied before the transform. For an ObjectID `_id`, use `bson_object_id_string(id)` instead of `id`: written as it is, an ObjectID becomes the literal text `ObjectID("...")`.

**Writes:** rows are upserted by primary key. Deletes remove the row with that key. Each batch is written as one transaction. See [Limitations](#limitations) for what that means when a row fails.

| BSON type                      | Works with column type                                                                                                            |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| String                         | `text`, `varchar`                                                                                                                 |
| 32-bit integer, 64-bit integer | `integer`, `bigint`                                                                                                               |
| Double                         | `double precision`                                                                                                                |
| Decimal128                     | `numeric`                                                                                                                         |
| Boolean                        | `boolean`                                                                                                                         |
| Date                           | `timestamptz`                                                                                                                     |
| Array of strings               | `text[]`                                                                                                                          |
| Document                       | `jsonb`                                                                                                                           |
| Null                           | Any nullable column                                                                                                               |
| ObjectID                       | `text`, as the literal `ObjectID("...")`. Convert with `bson_object_id_string()` in a transform to store the 24-character string. |
| Binary, UUID                   | Not supported. The write fails with `cannot find encode plan`. See [Limitations](#limitations).                                   |

A string is accepted by every column type, because PostgreSQL parses it: a string works for `uuid`, `date`, `timestamptz`, `numeric` and `jsonb` columns too. Numbers and booleans are not accepted by `text` columns. A double written to an `integer` or `bigint` column is truncated, not rounded.

## Limitations

### Not Supported Yet

**TOAST during CDC.** PostgreSQL stores large `text`, `jsonb` and `bytea` values out of line (TOAST, typically above 2 KB). When a row is updated and such a value is unchanged, PostgreSQL leaves it out of the change event, and the connector forwards the row without it. A destination that replaces the whole document, such as MongoDB, then <sub>loses</sub> that field.

* *How to notice:* after an update, the document on the destination lacks a field that the row still has. `SELECT pg_column_size(col)` above about 2 KB marks candidate columns.
* *What to do:* do not rely on CDC for tables with such columns. Run a new initial sync of those tables at cutover, or stop writes to them while the migration runs.

**`TRUNCATE`.** A `TRUNCATE` on a synced table stops the sync with an error (`index out of range`). With Temporal, the change stream activity keeps failing and does not advance.

* *How to notice:* the sync ends in the `Error` state, or the error appears under Last Activity Errors in the Progress view.
* *What to do:* do not truncate synced tables while the sync runs; `DELETE` is replicated. If a table was truncated, empty the destination table and run a new sync for that namespace.

**Primary key changes.** An `UPDATE` that changes a key column arrives as a new row under the new key. The row with the old key stays on the destination.

* *How to notice:* the destination has more rows than the source. Verification reports the extra rows.
* *What to do:* avoid changing keys during the migration, or delete the old row on the destination yourself.

**Composite primary keys.** Composite keys that contain a `uuid`, `timestamp`, `timestamptz`, `date` or `numeric` column fail at start with `gob: type not registered for interface`. Composite keys made of integer, text, boolean, floating point or `bytea` columns work, but the `_id` is an opaque binary value. The key columns are still in the document under their own names.

* *What to do:* such tables cannot be synced with this connector version. A transform cannot build the ID.

**Duplicate primary key constraint names.** If two tables in the database have primary key constraints with the same name, usually a table with the same name in two schemas, the connector reads both keys as one. As a source, a single-column key is then emitted as a composite binary `_id`, or the sync fails at start with `column "..." does not exist`. As a destination, writes fail with `column "..." specified more than once` or `primary key length mismatch`.

* *How to notice:* `SELECT conname, count(*) FROM pg_constraint WHERE contype = 'p' GROUP BY conname HAVING count(*) > 1;` lists the clashes.
* *What to do:* rename one of the constraints (`ALTER TABLE ... RENAME CONSTRAINT`).

**`uuid` and `bytea` on a PostgreSQL destination.** Binary values cannot be written and fail with `cannot find encode plan`. This affects PostgreSQL to PostgreSQL syncs of such columns, and MongoDB binary or UUID fields.

* *What to do:* exclude the column with `delete` in a transform, or convert it to a string that the column accepts. A MongoDB UUID converts with `bson_uuid_string(self)`. A `bytea` value can be stored in a `text` column as `base64.encode(self.Data)`.

**Large transactions.** A transaction larger than `logical_decoding_work_mem` (64 MB by default) is streamed by PostgreSQL in parts. The connector delivers its changes only together with the next smaller transaction, and applies a rolled-back large transaction as if it had been committed.

* *What to do:* keep transactions on synced tables small during the migration, or raise `logical_decoding_work_mem` on the server so that none are streamed.

**`inet` and `cidr` columns** arrive as an empty document `{}`. Exclude them with a transform if you don't need them.

**Fetching rows by ID** is not supported, so `testsync`, Verify IDs and the Sync Tester's Test Sync currently cannot use PostgreSQL as a source. Test transforms in Transform Studio with sample rows, then with a sync into a test destination.

### Behavior to Plan For

These are not errors, but they differ from what you might expect.

* **Schema changes.** New, dropped and renamed columns, and type changes, show up in the events that follow the change. The DDL itself is not replicated, so add columns on the destination first. A change to the primary key definition requires a restart of the sync.
* **Unset fields during CDC (destination).** Only the fields present in a document are written. A field removed from a source document keeps its old column value. A field set to null is written as `NULL`.
* **Initial sync batches (destination).** A batch writes the union of the fields of all its documents. A field missing from one document is written as `NULL` for that row, which overwrites an existing value when a table is synced again. Keep documents in a namespace uniform, for example with `add` in a transform.
* **Batches are atomic (destination).** A value that does not fit its column, or a field without a column, rolls back the whole batch and stops the sync with the PostgreSQL or encoding error in the log. With `--ignore-write-failures`, the whole batch is skipped instead.
* **Names are case-sensitive.** Namespaces and field names are quoted. `public.Orders` is not `public.orders`, and a field `camelcol` does not match a column `camelCol`. A missing or misnamed destination table is reported as `no primary key found for namespace`.
* **Multi-column keys on a destination** can be fed by CDC only from a PostgreSQL source, because the event ID must carry all key parts. The initial sync works from any source when the documents contain all key fields.
* **`time` and `interval` are documents, not scalar values.** Convert them in a transform if the destination needs a string or a number.
