This is the multi-page printable view of this section.
Docs
- 1: Introduction
- 2: Kernel Patches
- 3: PG TDE
- 3.1: Enable TDE and encrypt a table
- 3.2: Keys and WAL encryption
- 3.3: Back up, restore and migrate
- 3.4: Percona pg_tde 2.3.0 upstream manuals
- 3.4.1: Overview
- 3.4.1.1: About Transparent Data Encryption
- 3.4.1.2: How pg_tde works
- 3.4.1.3: Benefits of pg_tde
- 3.4.1.4: Encrypted data scope
- 3.4.1.5: Table access methods and pg_tde
- 3.4.1.6: Impact of pg_tde on database operations
- 3.4.1.7: Supported PostgreSQL deployments
- 3.4.1.8: Limitations of pg_tde
- 3.4.2: pg_tde documentation
- 3.4.3: Features
- 3.4.4: Install pg_tde
- 3.4.5: Install pg_tde on Debian or Ubuntu
- 3.4.6: Install pg_tde on Red Hat Enterprise Linux and Derivatives
- 3.4.7: Configure pg_tde
- 3.4.8: Validate Encryption with pg_tde
- 3.4.9: Key management
- 3.4.9.1: Key management overview
- 3.4.9.2: Keyring file configuration
- 3.4.9.3: Vault configuration
- 3.4.9.4: Using OpenBao as a key provider
- 3.4.9.5: KMIP configuration
- 3.4.9.6: Thales KMIP server configuration
- 3.4.9.7: Fortanix KMIP server configuration
- 3.4.9.8: Akeyless KMIP server configuration
- 3.4.9.9: Default principal key configuration
- 3.4.10: Architecture
- 3.4.10.1: Architecture overview
- 3.4.10.2: Encryption architecture
- 3.4.10.3: Key and key provider management
- 3.4.11: Operations
- 3.4.11.1: Encryption enforcement
- 3.4.11.2: Configure multi-tenancy
- 3.4.11.3: Backup with WAL encryption enabled
- 3.4.11.4: Restore encrypted backups
- 3.4.11.5: Upgrade pg_tde
- 3.4.11.6: Remove encryption from an encrypted table
- 3.4.11.7: Uninstall pg_tde
- 3.4.12: Configure WAL encryption
- 3.4.13: Streaming replication with tde_heap
- 3.4.14: Technical reference
- 3.4.14.1: Technical reference overview
- 3.4.14.2: Usage reference
- 3.4.15: GUC Variables
- 3.4.16: Functions
- 3.4.17: Command-line tools
- 3.4.17.1: Overview of pg_tde CLI tools
- 3.4.17.2: pg_tde_archive_decrypt
- 3.4.17.3: pg_tde_restore_encrypt
- 3.4.17.4: pg_tde_change_key_provider
- 3.4.17.5: pg_tde_checksums
- 3.4.17.6: pg_tde_waldump
- 3.4.17.7: pg_tde_upgrade
- 3.4.18: Release notes
- 3.4.18.1: pg_tde 2.3.0 (2026-11-17)
- 3.4.18.2: pg_tde 2.2.2 (2026-08-20)
- 3.4.18.3: pg_tde 2.2.1 (2026-07-06)
- 3.4.18.4: pg_tde 2.2.0 (2026-05-20)
- 3.4.18.5: pg_tde 2.1.2 (2026-03-02)
- 3.4.18.6: pg_tde 2.1.1 (2026-01-22)
- 3.4.18.7: pg_tde 2.1.0 (2025-11-28)
- 3.4.18.8: pg_tde 2.0.0 (2025-09-01)
- 3.4.18.9: pg_tde 1.0.0 (2025-06-30)
- 3.4.18.10: pg_tde Release Candidate 2 (2025-05-29)
- 3.4.18.11: pg_tde Release Candidate 1 (2025-03-27)
- 3.4.18.12: pg_tde Beta 2 (2024-12-16)
- 3.4.18.13: pg_tde Beta (2024-06-30)
- 3.4.18.14: pg_tde Alpha 1 (2024-03-28)
- 3.4.18.15: pg_tde MVP (2023-12-12)
- 3.4.18.16: Percona Transparent Data Encryption for PostgreSQL release notes index
- 3.4.19: FAQ
- 3.4.20: Contributing Guide
- 3.4.21: Get Help from Percona
- 3.4.22: Legal notice
- 3.4.23: Blog
- 3.4.23.1: Release notes
- 3.4.23.2: Guides
- 3.4.23.2.1: A production checklist for pg_tde
- 3.4.23.2.2: How pg_tde keeps data encrypted through PostgreSQL storage
- 3.4.23.3: From the Percona blog
- 3.4.23.3.1: Questions from the PostgreSQL TDE webinar
- 3.4.23.3.2: The road to the pg_tde release candidate
- 3.4.23.3.3: An early look at pg_tde
- 3.4.24: About
- 3.4.24.1: Attribution and copyright
- 3.4.24.2: Documentation errata
- 3.4.1: Overview
- 4: pgEdge · Spock
- 4.1: Start two writable nodes
- 4.2: Conflicts, monitoring and catch-up
- 4.3: Recovery, failover and rollback
- 4.4: pgEdge upstream manuals
- 4.4.1: Quick start
- 4.4.2: Spock
- 4.4.2.1: Installing and Configuring the Spock Extension
- 4.4.2.2: Creating a Spock Cluster: End-to-End Installation Guide
- 4.4.2.3: Using Spock to Create a Two-Node Cluster
- 4.4.2.4: Sizing Postgres Resources for Spock
- 4.4.2.5: Configuring Spock
- 4.4.2.6: Managing a Spock Installation
- 4.4.2.6.1: Automatic DDL Replication
- 4.4.2.6.2: Automatically Assigning Tables to Replication Sets
- 4.4.2.6.3: Filtering
- 4.4.2.6.4: Replicating Partitioned Tables
- 4.4.2.6.5: Using LOLOR to Manage Large objects
- 4.4.2.6.6: Using Spock in Read-Only Mode
- 4.4.2.6.7: Using Spock with Snowflake Sequences
- 4.4.2.7: Adding a Node to a Replicating Cluster
- 4.4.2.7.1: Modifying a Cluster with Zodan
- 4.4.2.7.2: Adding a Node with pgBackRest
- 4.4.2.7.3: Tutorial: Upgrading the Postgres Version In Place with pg_upgrade
- 4.4.2.8: Conflict Types
- 4.4.2.9: Conflict-Free Delta-Apply Columns (Conflict Avoidance)
- 4.4.2.10: Monitoring the Configuration and Health of Your Cluster
- 4.4.2.10.1: Finding Cluster Information
- 4.4.2.10.2: Lag Tracking
- 4.4.2.10.3: Monitoring a Node with the Spock Status Views
- 4.4.2.10.4: Using spock.sync_event to Confirm Synchronization
- 4.4.2.11: Spock Functions
- 4.4.2.11.1: Spock Functions
- 4.4.2.11.1.1: spock.cleanup_resolutions
- 4.4.2.11.1.2: spock.gen_slot_name()
- 4.4.2.11.1.3: spock.get_country()
- 4.4.2.11.1.4: spock.max_proto_version()
- 4.4.2.11.1.5: spock.min_proto_version()
- 4.4.2.11.1.6: spock.node_add_interface()
- 4.4.2.11.1.7: spock.node_alter()
- 4.4.2.11.1.8: spock.node_create()
- 4.4.2.11.1.9: spock.node_drop_interface()
- 4.4.2.11.1.10: spock.node_drop()
- 4.4.2.11.1.11: spock.node_info()
- 4.4.2.11.1.12: spock.node_refresh_info()
- 4.4.2.11.1.13: spock.replicate_ddl()
- 4.4.2.11.1.14: spock.repset_add_all_seqs()
- 4.4.2.11.1.15: spock.repset_add_all_tables()
- 4.4.2.11.1.16: spock.repset_add_partition()
- 4.4.2.11.1.17: spock.repset_add_seq()
- 4.4.2.11.1.18: spock.repset_add_table()
- 4.4.2.11.1.19: spock.repset_alter()
- 4.4.2.11.1.20: spock.repset_create()
- 4.4.2.11.1.21: spock.repset_drop()
- 4.4.2.11.1.22: spock.repset_remove_partition()
- 4.4.2.11.1.23: spock.repset_remove_seq()
- 4.4.2.11.1.24: spock.repset_remove_table()
- 4.4.2.11.1.25: spock.repset_show_table()
- 4.4.2.11.1.26: spock.sub_add_repset()
- 4.4.2.11.1.27: spock.sub_alter_interface()
- 4.4.2.11.1.28: spock.sub_alter_options()
- 4.4.2.11.1.29: spock.sub_alter_skiplsn()
- 4.4.2.11.1.30: spock.sub_alter_sync
- 4.4.2.11.1.31: spock.sub_create()
- 4.4.2.11.1.32: spock.sub_disable
- 4.4.2.11.1.33: spock.sub_drop()
- 4.4.2.11.1.34: spock.sub_enable
- 4.4.2.11.1.35: spock.sub_remove_repset
- 4.4.2.11.1.36: spock.sub_resync_table
- 4.4.2.11.1.37: spock.sub_show_status
- 4.4.2.11.1.38: spock.sub_show_table
- 4.4.2.11.1.39: spock.sub_wait_for_sync
- 4.4.2.11.1.40: spock.sync_event
- 4.4.2.11.1.41: spock.sync_seq
- 4.4.2.11.1.42: spock.table_wait_for_sync()
- 4.4.2.11.1.43: spock.version_num()
- 4.4.2.11.1.44: spock.version()
- 4.4.2.11.1.45: spock.wait_slot_confirm_lsn()
- 4.4.2.11.1.46: spock.xact_commit_timestamp_origin()
- 4.4.2.11.2: Management Functions
- 4.4.2.11.3: Node Management
- 4.4.2.11.4: Replication Set Management
- 4.4.2.11.5: Subscription Management Functions
- 4.4.2.11.1: Spock Functions
- 4.4.2.12: Upgrading the Spock Extension
- 4.4.2.13: Recovery
- 4.4.2.13.1: Recovering from Catastrophic Node Failure
- 4.4.2.14: Logical Slot Failover
- 4.4.2.15: Limitations and Restrictions
- 4.4.2.16: Internals
- 4.4.2.16.1: Design proposals
- 4.4.2.16.2: Historical plans
- 4.4.2.16.3: Design decisions
- 4.4.2.16.4: spock Output Plugin
- 4.4.2.16.5: Spock Protocol
- 4.4.2.17: Troubleshooting Spock
- 4.4.2.18: Frequently Asked Questions
- 4.4.2.19: Spock Release Notes
- 4.4.2.20: pglogical to Spock function names
- 4.4.3: LOLOR
- 4.4.3.1: Installing and Configuring lolor
- 4.4.3.2: lolor Release Notes
- 4.4.3.3: Using lolor
- 4.4.3.4: Using pg_upgrade with lolor
- 4.4.4: Snowflake
- 4.4.5: SafeSession
- 4.4.6: About this site
- 4.4.6.1: Sources and attribution
- 4.4.6.2: License texts
- 4.4.6.3: Maintenance and coverage
- 5: MySQL
- 5.1: Install and connect
- 5.2: Server configuration and authentication
- 5.2.1: Password authentication and TLS
- 5.2.2: pg_mysql object index
- 5.2.2.1: Schemas
- 5.2.2.2: Types and domains
- 5.2.2.3: Collations
- 5.2.2.4: Casts
- 5.2.2.5: Functions
- 5.2.2.5.1: String and binary functions
- 5.2.2.5.2: Numeric functions
- 5.2.2.5.3: Date and time functions
- 5.2.2.5.4: Conditional functions
- 5.2.2.5.5: Session functions
- 5.2.2.5.6: Type conversion helpers
- 5.2.2.5.7: Comparison operator functions
- 5.2.2.5.8: Arithmetic operator functions
- 5.2.2.5.9: Bitwise and logical operator functions
- 5.2.2.5.10: Pattern and JSON operator functions
- 5.2.2.5.11: String and number helpers
- 5.2.2.5.12: Temporal conversion helpers
- 5.2.2.5.13: Binary and string storage helpers
- 5.2.2.5.14: Aggregate support functions
- 5.2.2.5.15: Index support functions
- 5.2.2.5.16: Session state and variable helpers
- 5.2.2.5.17: DDL and write helpers
- 5.2.2.5.18: SHOW and metadata helpers
- 5.2.2.6: Aggregates
- 5.2.2.7: Operators
- 5.2.2.8: Metadata views
- 5.2.2.9: Metadata tables
- 5.2.2.10: Index access method, classes and families
- 5.2.2.11: Operator family members
- 5.2.2.12: Table indexes
- 5.2.2.13: Primary keys and domain checks
- 5.2.2.14: NOT NULL in metadata schemas
- 5.2.2.15: NOT NULL in performance_schema.events_*
- 5.2.2.16: NOT NULL in other performance_schema tables
- 5.3: SQL and type compatibility
- 5.4: Clients and drivers
- 5.5: Migration and recovery
- 5.6: Limits and troubleshooting
- 5.7: Protocol, dialect and origins
- 6: SQL Server
Start with Introduction to choose a build and understand what has been exercised. Kernel Patches traces each capability to its upstream source and matching extension. The four operator manuals below cover encryption, replication and the two integrated client protocols.
For the upstream references, open the Percona pg_tde manual or the pgEdge extension collection. Each includes the original notices and the versions used for the English and Chinese editions.
1 - Introduction
Mimus combines four sets of changes on PostgreSQL 19.0. An application using libpq, a PostgreSQL driver or psql connects to the native PostgreSQL server. You can use this entry point on its own, including to administer the extensions.
| You need to… | Start here |
|---|---|
| Run PostgreSQL SQL, manage roles or configure client authentication | PostgreSQL 19 manual |
| Protect selected relations and recover them with their keys | PG TDE |
| Accept writes in the same database on two nodes | pgEdge Spock |
| Connect an application with a MySQL driver | MySQL |
| Connect a SQL Server client using TDS and T-SQL | SQL Server |
For a deployment decision, check the tested configurations and outstanding release work. For a source build, identify the base and matching extensions.
Choose one compatibility listener per instance. PostgreSQL remains available alongside either MySQL or TDS. Deployment boundaries
1.1 - Connections and extensions
From connection to table
Every Mimus instance accepts native PostgreSQL connections. For a MySQL application add pg_mysql; for a SQL Server application add babelfishpg_tds and the Babelfish language and type extensions. The compatibility listener has its own port and object naming rules. Use native PostgreSQL to inspect the physical tables and roles behind either interface.
Choose at most one compatibility protocol per instance. All databases in a data directory share server processes and preload settings. An application that needs both MySQL and TDS needs two instances. The deployment rule is a product support boundary; the server does not enforce it at startup.
On the Debian 13 amd64 r4 candidate, the single-node DocumentDB engine and separate MongoDB gateway passed two logical restore tests. With pg_restore -N cron, the target installer recreated its default jobs. To retain the archived jobs and their history, the test paused scheduling on a fresh target, installed DocumentDB and unscheduled its four newly created jobs in one transaction, then restored the complete archive and resumed scheduling. A restored job ran again. In both tests PyMongo read all 63 documents by the original collection name. Older archives missing the collection catalog still need the original database or a matching physical backup.
Storage and replication
pg_tde encrypts relation data locally. Spock replicates logical changes. To protect both copies of a replicated table, provision a key provider and create the encrypted table and indexes on each node. A two-node research test verified the encrypted rows after writes from PyMySQL and FreeTDS. For deployment, select the protocol for each instance and rehearse failover with the keys and software it needs. Kernel patch groups
1.2 - Connect with PostgreSQL
Use the host, port, login role and database assigned to your instance. On the database host, the instance owner can also use the configured Unix socket. With the endpoint in the usual libpq environment variables (PGHOST, PGPORT, PGUSER and PGDATABASE), run:
Run this with the psql from your Mimus installation when identifying a build. Role access follows PostgreSQL authentication and privileges. Creating the encryption and replication extensions takes administrative privileges. MySQL and TDS clients negotiate authentication through their own listeners. A successful native login proves only the native connection. PostgreSQL client authentication
1.3 - Version and verification
What was verified
The 19.0.1-r4 candidate passed product acceptance on Debian 13 amd64. Its OCI image index is sha256:db9e09fa1c9294f406a53964a6b57c2543f5277743b54b15f509a5448447deae. Frozen source identities
| Scope | Result |
|---|---|
| Debian 13 amd64 candidate image | 31/31 product checks, 97/97 preload and installation orders across 12 supported combinations, and 7/7 Spock checks. The release precheck passed with zero waivers. |
| Kernel and backup | All 245 core tests passed on ordinary heap and again on forced tde_heap. All 12 physical backups across the candidate and assertion builds passed independent restore and offline page checks. |
| Native kernel | check-world passed on Debian 13 amd64 and Ubuntu 26.04 amd64 and arm64. All 36 plain data-directory handoff checks passed. Ubuntu coverage applies to the frozen kernel. |
Four upstream suites returned nonzero exit codes. The failures match the reviewed baselines.
| Upstream suite | Exit code | Result |
|---|---|---|
Percona global TDE installcheck-world | 2 | 622 SQL and isolation checks passed. TAP had 31 passing groups, 7 failures and 2 with no tests. Failures include ordinary-tool expectations and operations refused on encrypted sources. |
| pg_tde Meson | 4 | 39 passed, 4 failed, 3 skipped. Two tests lacked Perl dependencies, one differed in Unicode alignment and one expected a physical upgrade of an encrypted cluster. |
| pg_tde Meson with live key services | 1 | 43 passed, 1 failed, 2 skipped. The remaining test expected a physical upgrade that Mimus refuses. |
| Spock SQL | 2 | 32/34 passed. matview and autoddl differed in the order of DROP CASCADE notices. The separate TAP run passed 30 groups with 663 assertions, with one PG17-only group skipped. |
Earlier validation on Rocky Linux 10.3 x86-64 with GCC 14.3.1 built and exercised all nine cumulative patches. The four-component tree passed 245 core tests before the pgrx header fix. With that fix, pgrx 0.20.1 passed 790 PG19 tests with 3 upstream-default skips. The earlier two-node study exercised bidirectional MySQL/TDS writes on an encrypted table, subscriber catch-up, conflict resolution and point-in-time recovery with plaintext and encrypted WAL. An earlier Ubuntu arm64 candidate passed core regression in six configurations before Spock integration.
Choosing this revision
As of 5 December 2026 the Debian 13 amd64 candidate can proceed to signing. The source branches are pending upload, and the official Git tag and image publication are pending. Plan a trial with your own drivers, schema and backup chain before adopting any feature. Citus and TimescaleDB are outside the supported configuration, including when pg_tde is disabled. With encrypted WAL, r4 excludes cascading physical replication and a restarted standby receiving WAL again from the start of a segment (RISK-36). Backup and recovery · Spock failover boundaries
1.4 - Extension and application compatibility
Choosing extension binaries
Build native extensions using the pg_config and headers from the target Mimus installation. A shared PostgreSQL major version tells you the SQL baseline. It does not establish binary compatibility with every third-party module. The full kernel includes Babelfish parser and executor changes as well as the storage and replication interfaces. For Citus or TimescaleDB workloads, choose a separately supported PostgreSQL installation.
Validating a workload
Exercise the driver’s connection startup and parameter binding, representative DDL, reads and writes, and a restore into a second instance. Through the selected compatibility protocol and native PostgreSQL check null handling, type and collation mapping, generated keys and error handling. The four-component test used a shared table with integer columns. It provides a baseline for a driver trial. Tested scope
Storage and third-party extensions
The kernel excludes OrioleDB. Citus and TimescaleDB are unsupported even on clusters with TDE disabled. For table reorganization use PostgreSQL 19’s native REPACK. An external pg_repack 1.5.3 run rewrote encrypted storage as ordinary heap while queries still returned the original rows. Check encryption on the table, indexes and TOAST storage after a rewrite. PG TDE
2 - Kernel Patches
Start at Base for the PostgreSQL version and the data directory’s feature requirements. Then follow the pairs in order. The first layer of each pair carries selected upstream changes. The second integrates them with the preceding layers and the matching extension. A server built through 401 contains all four groups. Use native PostgreSQL alone or enable one compatibility listener per instance. TDE and Spock serve storage and replication independently.
2.1 - Base · PostgreSQL 19.0
Version identity
19.0.1 means community PostgreSQL 19.0 (REL_19_0, 5c839a2a08b9) plus Mimus revision 1. In 19.0.1-r4, the final patch commit 7af97b6707f5 and the integration commit 0d8a551aa121 in pgsty/mimus have the same tree, 07fbb73680de. The candidate was built from that tree. Some programs in this build, including pg_dump --version, report PostgreSQL 19.0. Keep the build revision and the extension builds with the backup inventory. PostgreSQL 19 manual
What 000 shares
Patch 000 adds common code to record features on first use and check requirements when the server starts. Later pairs supply the feature-specific checks. Read SHOW mimus_required_features on a running server. An unused cluster starts with an empty list. A cluster that installed an extension can still need its recovery support after application sessions disconnect. Preserve the recorded requirements and provision the matching recovery software.
No extension is needed for native PostgreSQL connections. Start here to connect with psql or check the tested platforms.
Match the extension sources
The r4 freeze records the nine kernel layers and the extension inputs in patch/series.json (format 8, patch repository commit 4089ead024de). The kernel layers are 000, 100, 101, 200, 201, 300, 301, 400 and 401, in that order. The standard installation prefix is /usr/mimus-19. Build each extension with that installation’s bin/pg_config and headers. The SQL extension version alone cannot identify a local adaptation.
For a MySQL installation, the mimus/ checkout already contains the integrated kernel. The sibling pg_mysql/ checkout supplies the complete extension. Build from the two source repositories
| Component | Source to build | Resulting Git tree |
|---|---|---|
| pg_tde | pg_tde/ at 5424c937188c plus ext-pg-tde- patches 000, 002, 007, 008, 009, 010 in manifest order | c62d1e2dceae |
| Spock | spock/ at 5.0.15, frozen commit e710faa6fe21126d898fa660e9b6dc8ed0da9438 | 8da352a31c41 |
| pg_mysql | pg_mysql/ at 1e631f9802c5 | 53dd9be3e87b |
| Babelfish extensions | babelfish/babelfish_extensions/ at 99c35f5ebb80 plus ext-babelfish- patches 001, 004, 010, 011, 012, 013, 014 | 891436a7f948 |
For pg_tde, prepare the indicated extension sources with subprojects/libkmip at 1bf36d7ecdb8, then run meson setup build -Dpg_config=/usr/mimus-19/bin/pg_config and meson install -C build in the extension directory. For Spock, put the matching bin directory first in PATH and run make PG_CONFIG=/usr/mimus-19/bin/pg_config followed by make PG_CONFIG=/usr/mimus-19/bin/pg_config install. Run the install step with write access to the target prefix.
2.2 - 100 / 101 · Percona TDE
Percona storage changes
100 imports selected changes from Percona’s PostgreSQL 19 tree, including its TOAST fix. A pluggable storage manager, relation-file identity during rewrites, asynchronous I/O callbacks and WAL segment I/O hooks give pg_tde a place to encrypt and decrypt pages. The extension supplies tde_heap, key management and the WAL implementation. Percona PostgreSQL
Integration and compatibility
101 integrates callback registration and checks that the TDE storage, WAL and recovery methods are ready before replay on a marked directory. The matching backup client checks whether the source requires TDE-aware WAL handling. Using an older plain client can bypass this check. The paired pg_tde_waldump also identifies Spock’s subtransaction commit-time record in encrypted WAL. These interfaces affect extension builds even if every application table uses ordinary heap storage.
To choose which objects to encrypt and which backup tool to use, follow the PG TDE manual.
Index DDL on encrypted tables
In the four-change Babelfish and TDE candidate, 002-pg-tde-index-encryption.patch changes the DDL event handler in the pg_tde extension. A B-tree index reports btree in pg_am. The extension reads the index file’s encryption state when handling ALTER INDEX, including the internal ALTER that records the original name of an index created over TDS.
Acceptance covered enforcement both on and off. Encrypted indexes stayed encrypted after a fillfactor change, a tablespace move and REINDEX. Enforcement continued to reject parameter changes to a plaintext index. Existing indexes retain their own storage state. Check indexes moved with an older build individually by OID. Verify indexes and TOAST · Candidate build manifest
2.3 - 200 / 201 · Spock
Upstream replication support
200 imports PG19 patches 015, 025, 030, 035 and 090 from Spock 5.0.15. The apply worker can use a column’s previous value to merge concurrent increments. When a conflicting local row wins but its numeric value must still change, the worker can write a new row version and preserve the original timestamp and origin. Upstream patch 030 added a separate CommitTs/SUBTRANS_TS WAL record (0x20) for this history. Spock PG19 patches
Recovery support
201 records the cluster requirement when CREATE EXTENSION spock succeeds. In r4, 201 writes the surviving subtransaction timestamp and origin overrides in the same WAL record as the transaction’s COMMIT. The matching kernel replays them even on a recovery instance without logical workers. Archives containing the earlier 0x20 record require their original recovery environment. Preloading the extension on the writable nodes enables replication. Before activating it, upgrade every physical standby and PITR environment that may have to replay a new record. Use pg_waldump for plaintext WAL or the paired pg_tde_waldump and keys for encrypted WAL.
For node setup, conflict handling and rollback decisions, see the Spock manual.
2.4 - 300 / 301 · MySQL
300 imports the server-side changes selected from OpenHalo v19.0.0. Its protocol hooks let a preloaded module register a listener and drive the client handshake and command loop in a PostgreSQL backend. pg_mysql supplies the MySQL protocol and dialect. The native listener continues to speak PostgreSQL. OpenHalo
301 adapts protocol registration, type coercion, collation and foreign-key handling, and the server defaults. It checks for the registered MySQL callbacks on a cluster that depends on them. Use the matching pg_mysql build when starting or restoring that cluster. An application migration should exercise its actual driver and column types. Deploy a separate instance if TDS access is also required.
For application access and compatibility, see the MySQL manual.
2.5 - 400 / 401 · SQL Server
400 imports native Babelfish changes selected against its PG19 beta base. They give the Babelfish extensions access to parser, executor, catalog, session and error-reporting paths needed for T-SQL. babelfishpg_tds handles the wire connection. babelfishpg_tsql, babelfishpg_common and babelfishpg_money provide the language and supporting types. Babelfish for PostgreSQL
401 completes the port to the 19.0 release. It reconciles listener and parser changes with OpenHalo, adds startup checks for dependent clusters and connects the Babelfish dump helpers to the Meson build. Use the complete pair to build the dump utilities. When migrating a database, verify SQL Server object naming, temporary tables and dump/restore on the chosen build. The cross-protocol row test covered a table defined on both nodes.
For connecting a TDS client and assessing T-SQL compatibility, see the SQL Server manual.
The current 401 also scopes a temporary union inside pg_bswap128() so that pgrx can generate Rust bindings from the installed PG19 headers. Regenerate bindings against the target Mimus SDK.
Four Babelfish and pg_tde changes
These four changes passed acceptance on a 19.0.1 candidate built on the frozen nine-patch baseline. Earlier baseline images share the version number. The tested Debian 13 x86-64 image ID starts with a3b80a5a99a1. Its /usr/mimus-19/share/mimus/increments.json records each patch’s SHA-256 and its input and output trees. The final kernel, Babelfish extension and pg_tde extension trees are a5c4770bf6b4, c97c68290e5d and 043d79f80d1c, respectively.
| Change | Delivered in | What users see |
|---|---|---|
| 1 · Table encryption option | Babelfish extension 001 | CREATE TABLE … WITH (ENCRYPTION=ON/OFF) fails before creating a table, preventing accidental delivery of a plaintext table as encrypted. |
| 2 · Index DDL on encrypted tables | pg_tde extension 002 | TDS can add an index with enforcement on. An encrypted index stays encrypted after PG changes its parameters, moves its tablespace or rebuilds it. Index patch |
| 3 · Per-table selection | SQL example in the image | A dedicated TDS transaction creates the table and verifies its storage, two indexes, TOAST table and TOAST index before committing. Deploy and verify |
| 4 · Temporary relation cleanup | Babelfish extension 004 and kernel 402 | Statements and cursors release their own references. A cursor can finish reading a temporary relation after a procedure returns, with cleanup governed by the transaction outcome. |
The release and assertion builds passed all four cases. Each read and updated seven existing permanent tables after a restart. The release build passed 245 native PG regression tests in each of six configurations. Item 5 is closed. The three T-SQL temporary objects use heap/off, and their relation files and query spills may contain plaintext. Temporary objects and storage coverage
3 - PG TDE
Use PG TDE when a copy of a selected PostgreSQL relation on disk must be unreadable without its principal key. PostgreSQL decrypts pages as it reads them, so authorized SQL users continue to see the data. Plan for two separate assets from the outset: a physical backup and access to all keys required to read it.
- Enable the extension and verify a table in a new database.
- Choose a key provider and decide whether to encrypt WAL. WAL encryption covers the whole cluster.
- Restore a backup into a separate instance before relying on it.
For SQL Server clients, configure the key in the physical PG database and create and use the tables in the TDS logical database. Create encrypted tables over TDS · T-SQL temporary objects and plaintext on disk
Mimus pairs Percona’s pg_tde 2.3 with its PG19 kernel and tools. Installing the extension in a database registers a cluster-wide recovery requirement. The 100 / 101 patch pair describes what the kernel checks. Percona documentation
Percona pg_tde 2.3.0 manual
The full upstream manual covers what is encrypted, key providers, SQL functions, settings and command-line tools. The upstream release is 2.3.0. Mimus uses SQL extension version 2.3 plus the paired source changes. For an existing Mimus data directory, follow the Mimus recovery and migration procedure.
3.1 - Enable TDE and encrypt a table
Prepare a new database
Use a matching Mimus 19.0.1 installation containing the pg_tde library, extension SQL and control file. On a new test cluster add pg_tde to shared_preload_libraries in postgresql.conf, retaining other required libraries. Restart with the matching server. Connect with psql as an administrator to the database in which you will create the table.
For this exercise, create a directory outside PGDATA named /var/lib/mimus-keys on the server, owned by the database service account with mode 0700. Use a fresh file name. The server will manage the keyring. File providers are suitable for local exercises; anyone who takes the backup and the readable keyring can recover the data.
Create and verify
Expect row (1,100), two true values, and tde in the feature list. To convert an existing heap table use ALTER TABLE ... SET ACCESS METHOD tde_heap after configuring its database key. This rewrites storage. Allow for the table lock, disk space and backup window.
Which objects are protected?
The encrypted table’s data, indexes and out-of-line TOAST values are covered. For a partitioned table, check each physical partition that stores rows. Native PG CREATE TEMP TABLE can use tde_heap. Babelfish table variables, # tables and temporary SELECT INTO use heap with enforcement off for the runtime login. T-SQL temporary objects and plaintext on disk
System catalogs, statistics, object names and query spill files remain readable. A normal heap table stays plaintext. Logical exports return readable data, so protect their storage and transport separately. Enable WAL encryption separately if WAL must also be protected. Key and WAL configuration
To reorganize an encrypted table on Mimus, use native PostgreSQL 19 REPACK and verify the resulting table, index and TOAST storage. The external pg_repack extension is unsupported. Storage compatibility
3.2 - Keys and WAL encryption
Where the keys live
Relation keys are stored wrapped in the data directory. A database principal key from its provider unwraps them. The provider can be database-scoped or global. In the file example the provider lives outside the data directory. For a deployment, choose a supported KMS such as Vault or KMIP and test its reachability and authentication from every intended recovery host. Record provider identity, key names and versions. Keep credentials, certificates and file keyrings recoverable independently of the database host. Percona key management
Encrypt the WAL stream
WAL encryption applies to all databases, including ordinary heap tables. Establish the restore procedure on every backup and standby host before enabling it. On the test cluster, with the key directory from the previous page, configure a dedicated server principal key:
Restart the server and run SHOW pg_tde.wal_encrypt. Expect on. Earlier WAL and backups retain their original requirements. Turning the switch off leaves historical encrypted segments in the recovery chain. For continuous archiving use Percona’s pg_tde_archive_decrypt and pg_tde_restore_encrypt as documented for the chosen archive system. Protect the decrypted archive independently.
Rotation
Schedule rotation outside all backup jobs. Retain every principal/server key version needed from the oldest retained backup through its recovery targets. After rotation, take a fresh full backup and restore it on another host. A new key with the old name cannot decrypt data wrapped with the lost key. Backup and recovery
3.3 - Back up, restore and migrate
Choose the physical backup path
Use the binaries paired with the source revision. Set PGHOST, PGPORT and PGUSER for a replication-authorized connection. Choose a new BACKUP path on protected storage. Use data checksums on the source, keep the default online page verification enabled and suspend key rotation until the backup finishes. These examples assume the default tablespace layout. With encrypted WAL, r4 excludes cascading physical replication and a restarted standby receiving WAL again from the start of a segment (RISK-36).
Only relations encrypted, WAL always plaintext. With no server WAL key history, the paired ordinary client can stream a plain-format backup:
Encrypted WAL or a source referred to the TDE client. The current switch alone is insufficient if WAL keys were configured previously. For the local example, run the following with read access to the source PGDATA. On a separate backup host securely stage the same pg_tde metadata from the source. Supply the configured provider files, credentials and historical keys there so the server key can be opened. The file provider in the example uses an absolute path; make that path available to the backup and restore accounts. For providers with relative paths, retain their locations relative to the target. Use the plain directory format with streamed WAL:
Read the backup independently
Before starting a restored copy, verify the backup manifest and all its WAL ranges with the matching reader and keys. Keep an independent inventory of the expected encrypted objects and mappings. Reject a backup with a missing mapping even if both online and manifest checks pass.
- On an isolated host, make a working copy of the complete backup owned by the database service account. Keep the original backup intact. Supply the same-major Mimus server, matching preloads and the original provider material. For a file keyring, restore its protected copy separately. If external tablespaces were used, restore their files and mappings.
- Set the restore host’s port and socket directory so your client can only reach the copy. Keep it isolated from replication peers and shared archive destinations. Start the copy with
pg_ctl -D "$RESTORE" -l "$RESTORE_LOG" -w start. For PITR, provision the continuous WAL archive, restore command, recovery target andrecovery.signalbefore the first start. - Connect explicitly to the restored database. For the ledger example, run the following. Expect the committed row
1,100, encryption on table and index, and thetderequirement. For a real backup also compare an out-of-line value, row counts and application invariants with the backup-time baseline.
Compare the heap, indexes and TOAST storage with the saved encryption inventory. Shut down the restored copy cleanly and run pg_tde_checksums --check -D "$RESTORE". Require exit code 0 and Bad checksums of 0.
Installing pg_tde can create recovery dependencies before the first encrypted user table exists. An older backup may cross this activation point during replay. Equip the recovery host before replay and retain the original marker and key metadata. A missing historical key makes the affected backup unreadable even with intact relation files.
Cross-major migration
Use logical dump and restore into a new cluster for a major upgrade. Prepare roles, the target extension and its own keys before loading encrypted objects. Review the dump’s extension entries, table access methods and ownership. Use the target major’s pg_dump -Fc and pg_restore --exit-on-error, then verify constraints, sequences, rows and encryption on the target. Protect the logical archive as plaintext. Keep the source until the checks pass. Physical pg_upgrade of a TDE-marked cluster is outside the 19.0.1 path. Percona backup procedure
3.4 - Percona pg_tde 2.3.0 upstream manuals
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The pg_tde documentation follows the path a production PostgreSQL deployment takes: understand the encryption model, install the extension, configure key custody, validate encrypted tables, then operate WAL, backups, recovery, and upgrades.
The current release is pg_tde 2.3.0, adding PostgreSQL 19 support and pg_tde-aware WAL record inspection. The Chinese edition includes these reviewed incremental changes.
- Overview — understand TDE, pg_tde, supported deployments, and limitations.
- Get started — install the package and create the extension.
- Key management — configure KMS providers and principal keys.
- Technical reference — architecture, functions, GUC variables, and replication.
- Operations — backup, restore, enforcement, multi-tenancy, and upgrades.
- Release notes — follow compatibility and change history.
3.4.1 - Overview
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.1.1 - About Transparent Data Encryption
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Transparent Data Encryption (TDE) protects your data at rest by ensuring that even if the underlying storage is compromised, the data remains unreadable without the correct decryption keys. This is especially critical for environments handling sensitive, regulated, or high-value information.
This process runs transparently in the background, with minimal impact on database operations.
Use the links below to explore how pg_tde helps secure your PostgreSQL deployments:
Discover the benefits of pg_tde Understand pg_tde limitations View the full feature list Get started with installation
3.4.1.2 - How pg_tde works
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
To encrypt the data, two types of keys are used:
- Internal encryption keys to encrypt user data. They are stored internally, near the data that they encrypt.
- The principal key to encrypt database keys. It is kept separately from the database keys and is managed externally in the key management store.
For more information on managing and storing principal keys externally, including supported key management systems and the local keyring option, see Key management overview.
The encryption process works as follows:

When a user creates an encrypted table using pg_tde, a new random key is generated internally for that table and is encrypted using the AES-CBC cipher algorithm. This key is used to encrypt all data the user inserts in that table. Eventually the encrypted data gets stored in the underlying storage.
The internal key itself is encrypted using the principal key. The principal key is stored externally in the key management store.
Similarly when the user queries the encrypted table, the principal key is retrieved from the key store to decrypt the internal key. Then the same unique internal key for that table is used to decrypt the data, and unencrypted data gets returned to the user. So, effectively, every TDE table has a unique key, and each table key is encrypted using the principal key.
3.4.1.3 - Benefits of pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The benefits of using pg_tde are outlined below for different users and organizations.
Benefits for organizations
- Data safety: Prevents unauthorized access to stored data, even if backup files or storage devices are stolen or leaked.
- Enterprise-ready Architecture: Supports both single and multi-tenancy, giving flexibility for SaaS providers or internal multi-user systems.
Benefits for DBAs and engineers
- Granular control: Encrypt specific tables or databases instead of the entire system, reducing performance overhead.
- Operational simplicity: Works transparently without requiring major application changes.
- Defense in depth: Adds another layer of protection to existing controls like TLS (encryption in transit), access control, and role-based permissions.
When combined with the external Key Management Systems (KMS), pg_tde enables centralized control, auditing, and rotation of encryption keys—critical for secure production environments.
You can find more information on Transparent Data Encryption (TDE) in this article.
3.4.1.4 - Encrypted data scope
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde encrypts the following components:
- User data in tables using the extension, including associated TOAST data. The table metadata (column names, data types, etc.) is not encrypted.
- Temporary tables created during the query execution, for data tables created using the extension.
- Write-Ahead Log (WAL) data for the entire database cluster. This includes WAL data in encrypted and non-encrypted tables.
- Indexes on encrypted tables.
3.4.1.5 - Table access methods and pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
A table access method is the way how PostgreSQL stores the data in a table. The default table access method is heap. PostgreSQL organizes data in a heap structure, meaning there is no particular order to the rows in the table. Each row is stored independently and identified by its unique row identifier (TID).
How the heap access method works
Insertion: When a new row is inserted, PostgreSQL finds a free space in the tablespace and stores the row there.
Deletion: When a row is deleted, PostgreSQL marks the space occupied by the row as free, but the data remains until it is overwritten by a new insertion.
Updates: PostgreSQL handles updates by deleting the old row and inserting a new row with the updated values.
Custom access method
Custom access methods allow you to implement and define your own way of organizing data in PostgreSQL. This is useful if the default table access method doesn’t meet your needs.
Custom access methods are typically available with PostgreSQL extensions. When you install an extension and enable it in PostgreSQL, a custom access method is created.
An example of such an approach is the tde_heap access method. It is automatically created only for the databases where you enabled the pg_tde extension and configured the key provider, enabling you to encrypt the data.
To use a custom access method, specify the USING clause for the CREATE TABLE command:
How tde_heap works with pg_tde
The tde_heap access method works on top of the default heap access method and is a marker to point which tables require encryption. It uses the custom storage manager TDE SMGR, which becomes active only after you installed the pg_tde extension.
Every data modification operation is first sent to the Buffer Manager, which updates the buffer cache. Then, it is passed to the storage manager, which then writes it to disk. When a table requires encryption, the data is sent to the TDE storage manager, where it is encrypted before written to disk.
Similarly, when a client queries the database, the PostgreSQL core sends the request to the Buffer Manager which checks if the requested data is already in the buffer cache. If it’s not there, the Buffer Manager requests the data from the storage manager. The TDE storage manager reads the encrypted data from disk, decrypts it and loads it to the buffer cache. The Buffer Manager sends the requested data to the PostgreSQL core and then to the client.
Thus, the encryption is done at the storage manager level.
Changing the default table access method
You can change the default table access method so that every table in the entire database cluster is created using the custom access method. For example, you can enable data encryption by default by defining the tde_heap as the default table access method.
However, consider the following before making this change:
- This is a global setting and applies across the entire database cluster and not just a single database.
We recommend setting it with caution because all tables and materialized views created without an explicit access method in their
CREATEstatement will default to the specified table access method. - You must create the
pg_tdeextension and configure the key provider for all databases before you modify the configuration. Otherwise PostgreSQL won’t find the specified access method and will throw an error.
Here is how you can set the new default table access method:
Add the access method to the
default_table_access_methodparameter:Use
ALTER SYSTEM, it requires superuser orALTER SYSTEMprivileges.Edit the
postgresql.confconfiguration file and add the value for thedefault_table_access_methodparameter.You can use the SET command to change the default table access method temporarily, for the current session.
Unlike modifying the
postgresql.conffile or using theALTER SYSTEMcommand, the changes you make via theSETcommand don’t persist after the session ends.You also don’t need to have the superuser privileges to run the
SETcommand.You can run the SET command anytime during the session.
Reload the configuration to apply the changes:
3.4.1.6 - Impact of pg_tde on database operations
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page summarizes how pg_tde interacts with core PostgreSQL operations.
| Area | Affected | Notes / Actions |
|---|---|---|
| Backups | ❌ Yes | Encrypted backups require pg_tde-aware tools. See Backup with WAL encryption. |
| Restore | ❌ Yes | Restored data remains encrypted; pg_tde transparently handles decryption. See Restore encrypted backups. |
| Streaming replication | ⚠️ Partial | Replicas must load the pg_tde shared library (shared_preload_libraries = ‘pg_tde’). Without it, the replica will fail on operations involving tde_heap. |
| Logical replication | ✅ No | Not affected. |
| Monitoring and statistics | ✅ No | Not affected, including pg_stat_monitor. |
| Performance | ⚠️ Slight | Minor CPU overhead due to enabling encryption, most noticeable on random write workloads. |
3.4.1.7 - Supported PostgreSQL deployments
The packages and support matrix below belong to Percona PostgreSQL. Build pg_tde against the matching Mimus installation before enabling it. Mimus procedure
The pg_tde extension is available for Percona Server for PostgreSQL 17.5 and later versions, an open source, drop-in replacement for PostgreSQL Community. These versions provide the tde_heap access method and offer full encryption capabilities, including encryption of tables, indexes and WAL data.
For users who need pg_tde in PostgreSQL 16, a build is available as a Tech Preview. It is not officially supported, is not recommended for production, and does not follow the same release cadence as the supported PostgreSQL 17.5 and later versions.
The extension is tightly integrated with Percona Server for PostgreSQL to deliver enhanced encryption functionality that is not available in community builds.
Why choose Percona Server for PostgreSQL?
By using our PostgreSQL distribution, you get:
- Full encryption support through the
tde_heapaccess method, including tables, indexes and WAL data. - Enhanced performance and enterprise-ready features not available in community builds.
- Regular updates and security patches backed by Percona’s expert support team.
- Professional support and guidance for secure PostgreSQL deployments.
Support for earlier or limited versions of pg_tde (such as tde_heap_basic) has been deprecated.
Still unsure which deployment fits your needs? Contact our experts to find the best solution for your environment.
3.4.1.8 - Limitations of pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Known incompatibilities in Percona Server for PostgreSQL
Some PostgreSQL extensions may not work with Percona Server for PostgreSQL due to internal changes required by pg_tde.
These incompatibilities may occur even if pg_tde is not installed or enabled.
Distributed and extension-based systems
Percona Server for PostgreSQL is not compatible with distributed PostgreSQL extensions such as Citus or time-series extensions such as TimescaleDB.
This limitation is caused by internal PostgreSQL changes related to pg_tde and is not dependent on enabling the extension.
Limitations when using pg_tde
Limitations of pg_tde 2.3.0:
- PostgreSQL’s internal system tables, which include statistics and metadata, are not encrypted.
- Temporary files created when queries exceed
work_memare not encrypted. These files may persist during long-running queries or after a server crash which can expose sensitive data in plaintext on disk.
Recovery without pg_tde in shared_preload_libraries
When recovering a PostgreSQL cluster that contains encrypted tables, the pg_tde extension must be loaded through the shared_preload_libraries configuration parameter.
ALTER DATABASE ... SET TABLESPACE
pg_tdeThe ALTER DATABASE ... SET TABLESPACE command bypasses PostgreSQL’s storage manager (SMGR), which pg_tde relies on to enforce encryption.
- If encrypted objects exist in the database’s default tablespace, the operation is refused.
- If no encrypted objects are present in the default tablespace, the operation is allowed.
Only objects in the default tablespace are checked. Objects in other tablespaces are not evaluated by pg_tde.
To move encrypted tables individually, use ALTER TABLE ... SET TABLESPACE, which operates through SMGR and is compatible with pg_tde.
Currently unsupported WAL tools
The following tools are currently unsupported with pg_tde WAL encryption:
pg_createsubscriberpg_receivewalBarmanpg_verifybackupby default fails with checksum or WAL key size mismatch errors. As a workaround, use-s(skip checksum) and-n(--no-parse-wal) to verify backups.- pgBackRest without
pg_tde_archive_decryptandpg_tde_restore_encrypt, or witharchive-async,archive-header-check, orchecksum-pageenabled.
Supported WAL tools
The following tools have been tested and verified by Percona to work with pg_tde WAL encryption:
- Patroni, for an example configuration see the following Patroni configuration file
pg_tde_basebackup(with--wal-method=streamor--wal-method=none), for details on usingpg_tde_basebackupwith WAL encryption, see Backup with WAL encryption enabledpg_tde_resetwalpg_tde_rewindpg_tde_upgradepg_tde_waldump- pgBackRest, when
pg_tde_archive_decryptandpg_tde_restore_encryptare configured andarchive-async,archive-header-check, andchecksum-pageare disabled
Example Patroni configuration
The following is a Percona-tested example configuration.
The above example is Percona-tested, but Patroni versions differ, especially with discovery backends such as etcd. Ensure you adjust the configuration to match your environment, version, and security requirements.
Next steps
Check which PostgreSQL versions and deployment types are compatible with pg_tde before planning your installation.
View the versions and supported deployments
Begin the installation process when you’re ready to set up encryption.
3.4.2 - pg_tde documentation
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Percona Transparent Data Encryption for PostgreSQL (pg_tde) is an open source, community driven and futureproof PostgreSQL extension that provides Transparent Data Encryption (TDE) to protect data at rest. pg_tde ensures that the data stored on disk is encrypted, and that no one can read it without the proper encryption keys, even if they gain access to the physical storage media.
pg_tde is bundled as a component of Percona Server for PostgreSQL and requires its patches to function. It is packaged with Percona Distribution for PostgreSQL 17+ to ensure compatibility and proper operation. For more information, see the Percona Distribution for PostgreSQL 18 documentation .
Installation guide
Get started quickly with the step-by-step installation instructions.
🚀 Features
Explore what features Percona’s pg_tde extension brings to PostgreSQL.
Check what you can do with pg_tde
Architecture
Understand how pg_tde integrates into PostgreSQL with Percona’s architecture. Learn how keys are managed, how encryption is applied, and how our design ensures performance and security.
Check what’s under the hood for pg_tde
📢 What’s new?
Learn about the releases and changes in pg_tde.
3.4.3 - Features
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde is available for Percona Server for PostgreSQL
The Percona Server for PostgreSQL provides an extended Storage Manager API that allows integration with custom storage managers.
The following features are available for the extension:
- Table encryption, including:
- Data tables
- Index data for encrypted tables
- TOAST tables
- Temporary tables
Metadata of those tables is not encrypted.
- Single-tenancy support via a global keyring provider
- Multi-tenancy support
- Table-level granularity for encryption and access control
- Multiple Key management options
Next steps
Learn more about how pg_tde implements Transparent Data Encryption:
3.4.4 - Install pg_tde
The packages and support matrix below belong to Percona PostgreSQL. Build pg_tde against the matching Mimus installation before enabling it. Mimus procedure
You can select from multiple easy-to-follow installation options to install pg_tde, however we strongly recommend using a Package Manager for a convenient and quick installation.
pg_tde availability by PostgreSQL version:
| PostgreSQL version | Is pg_tde installed automatically? | Action Required |
|---|---|---|
| 17.x - 17.6 (minor updates) | Yes | None |
| 17.7 (and later) | No | Install the package manually |
| 18.x (and later) | No | Install the package manually |
Starting with PPG 17.7, pg_tde is no longer bundled with the Percona server for PostgreSQL package. It is now delivered as a separate package named percona-pg-tde(pg-version) for Debian or Ubuntu and percona-pg_tde(pg-version) for Red Hat Enterprise Linux and Derivatives.
Specific information on the supported platforms, products, and versions is described in the Percona Software and Platform Lifecycle page.
Percona provides installation packages in DEB and RPM formats for 64-bit Linux distributions.
If you are on Debian or Ubuntu, use apt for installation.
If you are on Red Hat Enterprise Linux or compatible derivatives, use yum for installation.
pg_tde is a part of the Percona Distribution for PostgreSQL Docker image. Use this image to enjoy full encryption capabilities. Check below to get access to a detailed step-by-step guide.
You can enable pg_tde when deploying Percona Server for PostgreSQL in Kubernetes using the Percona Operator.
pg_tde is included in the Percona Distribution for PostgreSQL tarball. Select the below link to access the step-by-step guide.
Next steps
After finishing the installation, you can proceed with:
Set up pg_tde Learn about key management Validate your encryption setup Enable WAL encryption
3.4.5 - Install pg_tde on Debian or Ubuntu
The packages and support matrix below belong to Percona PostgreSQL. Build pg_tde against the matching Mimus installation before enabling it. Mimus procedure
This page explains how to install pg_tde for Percona Distribution for PostgreSQL .
Check the list of supported platforms before continuing.
Preconditions
- Remove any upstream PostgreSQL packages (postgresql-*) that may already be installed on Debian or other apt-based systems. These packages conflict with Percona Server for PostgreSQL and with the standalone
pg_tdepackage. - Ensure you enable the Percona APT repository using the repository management tool
percona-release. This ensures the correct Percona Server for PostgreSQL and pg_tde packages are available for installation.
Install percona-release
You need the following dependencies to install
percona-release:wgetgnupg2curllsb-release
Install the dependencies:
Fetch the
percona-releasepackageInstall
percona-releaseEnable the Percona Distribution for PostgreSQL repository
Update the local cache
Install pg_tde
After all preconditions are met, install the pg_tde package:
Example for PostgreSQL 18
Next steps
3.4.6 - Install pg_tde on Red Hat Enterprise Linux and Derivatives
The packages and support matrix below belong to Percona PostgreSQL. Build pg_tde against the matching Mimus installation before enabling it. Mimus procedure
This tutorial shows how to install pg_tde with Percona Distribution for PostgreSQL.
Check the list of supported platforms before continuing.
Install percona-release
You need the percona-release repository management tool that enables the desired Percona repository for you.
Install
percona-release:Enable the repository:
Install pg_tde
Install pg_tde:
Example for PostgreSQL 18
Next steps
3.4.7 - Configure pg_tde
The packages and support matrix below belong to Percona PostgreSQL. Build pg_tde against the matching Mimus installation before enabling it. Mimus procedure
Before you can use pg_tde for data encryption, you must enable the extension and configure PostgreSQL to load it at startup. This setup ensures that the necessary hooks and shared memory are available for encryption operations.
To learn how to configure multi-tenancy, refer to the Configure multi-tenancy guidelines.
The pg_tde extension requires additional shared memory. You need to configure PostgreSQL to preload it at startup.
1. Configure shared_preload_libraries
You can configure the shared_preload_libraries parameter in two ways:
Add the following line to the
postgresql.conffile:Use the ALTER SYSTEM command. Run the following command in
psqlas a superuser:
2. Restart the PostgreSQL cluster
Restart the postgresql cluster to apply the configuration.
On Debian and Ubuntu:
```sh sudo systemctl restart postgresql.service ```On RHEL and derivatives:
```sh sudo systemctl restart postgresql-17 ```
3. Create the extension
After restarting PostgreSQL, connect to psql as a superuser or database owner and run:
See CREATE EXTENSION for more details.
The pg_tde extension is created only for the current database. To enable it for other databases, you must run the command in each individual database.
4. (Optional) Enable pg_tde by default
To automatically have pg_tde enabled for all new databases, modify the template1 database:
It’s recommended to use an external key provider (KMS) to manage encryption keys. For configuration instructions, see Next steps.
Next steps
3.4.8 - Validate Encryption with pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
After enabling the pg_tde extension for a database, you can begin encrypting data using the tde_heap table access method.
Encrypt data in a new table
Create a table in the database for which you have enabled
pg_tdeusing thetde_heapaccess method as follows:Warning: Example for testing purposes only:
Learn more about table access methods and how you can enable data encryption by default in the Table Access Methods and TDE section.
To check if the data is encrypted, run the following function:
The function returns
trueorfalse.(Optional) Rotate the principal key.
To re-encrypt the data using a new key, see Principal key management.
Encrypt existing table
You can encrypt an existing table. It requires rewriting the table, so for large tables, it might take a considerable amount of time.
Run the following command:
Using SET ACCESS METHOD drops hint bits which can impact query performance. To restore performance, run:
This forces PostgreSQL to check every tuple for visibility and reset the hint bits.
Want to remove encryption later? See how to decrypt your data.
Next steps
3.4.9 - Key management
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.9.1 - Key management overview
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This overview retains an older qualification of Vault KMIP. The 2.2.2 release notes explicitly announce Vault Enterprise KMIP support; consult those notes for the version-specific status. See site errata.
In production environments, storing encryption keys locally on the PostgreSQL server can introduce security risks. To enhance security, pg_tde supports integration with external Key Management Systems (KMS) through a Global Key Provider interface.
This section describes how you can configure pg_tde to use the local and external key providers.
To use an external KMS with pg_tde:
- Configure a Key Provider
- Set the Global Principal Key
While key files may be acceptable for local or testing environments, KMS integration is the recommended approach for production deployments.
When using HashiCorp Vault, KV v2 is the recommended and supported integration method.
The KMIP engine in Vault is not a validated configuration for pg_tde and is not recommended for production deployments.
Do not rotate encryption keys while a backup is running. This may result in an inconsistent backup and restore failure. This applies to all backup tools.
Schedule key rotations outside backup windows. After rotating keys, take a new full backup.
For more details, see Limitations of pg_tde.
pg_tde has been tested with the following key providers:
| KMS Provider | Description | Documentation |
|---|---|---|
| KMIP | Standard Key Management Interoperability Protocol. | Configure KMIP → |
| Vault | HashiCorp Vault integration (KV v2 API). | Configure Vault → |
| Fortanix | Fortanix DSM key management. | Configure Fortanix → |
| Thales | Thales CipherTrust Manager and DSM. | Configure Thales → |
| OpenBao | Community fork of Vault, supporting KV v2. | Configure OpenBao → |
| Akeyless | A cloud-based secrets management platform for securely storing and accessing credentials and encryption keys. | Configure Akeyless → |
| Keyring file (not recommended) | Local key file for dev/test only. | Configure keyring file → |
3.4.9.2 - Keyring file configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The inspection example now uses the table it creates and the current database key-info function. See site errata.
This setup is intended for development and stores the keys, unencrypted, in a data file you specify.
While keyring files may be acceptable for local or testing environments, proper KMS providers are the recommended approach for production deployments.
You can configure key providers either at the database level (for development and testing) or at the global level (for production).
The steps below provide an example on how to add a database-scoped key provider:
Create a database-scoped file key provider (
file-keyringin this example) in the/tmp/pg_tde_test_local_keyring.perfile:Create a key (
my_default_keyin this example) inside the newly createdfile-keyringprovider:Set the key (
my_default_key) from the key provider (file-keyring):TipYou can check the current database key information (such as the date and time of creation). Run:
Now, create a table using tde_heap:
The newly created table is encrypted with the database key you have set (
my_default_key).TipTo check if your created table is encrypted with tde_heap, run:
If
Access method: tde_heap, then your table is encrypted.Example outputpostgres=# \d+ customer_table Table “public.customer_table” Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description ——–+———+———–+———-+———+———+————-+————–+————- a | integer | | | | plain | | | Access method: tde_heap
Further reading
Next, for production deployments, configure a global principal key using a proper KMS provider.
Alternatively, you can skip directly to validating encryption with pg_tde or configuring WAL encryption.
You can also review the available pg_tde functions in Functions.
3.4.9.3 - Vault configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
You can configure pg_tde to use HashiCorp Vault as a global key provider for managing encryption keys securely. Both the open source and enterprise editions are supported.
Configure Vault with pg_tde in Docker
This example setup describes how to run HashiCorp Vault and Percona PostgreSQL with pg_tde side by side using Docker, configure Vault policies, and connect it as a global key provider for TDE encryption.
For production deployments, follow your organization’s security standards.
1. Create the docker-compose.yaml file
The following docker-compose.yaml file is an example on how to run both Vault and PostgreSQL with a shared secrets volume:
2. Enable the KV v2 secrets engine
In the Vault container, enable a KV v2 storage engine for pg_tde:
This creates a tde/ mount for storing encrypted keys.
If you are using Vault Enterprise namespaces, you don’t need a separate
namespace parameter when configuring pg_tde.
You can include the namespace directly in the mount path. For example:
This is equivalent to configuring a namespace separately and works with both:
- Vault OSS
- Vault Enterprise (with namespaces)
3. Create a Vault policy for pg_tde
Define a Vault policy that grants pg_tde access to read, write, and list keys.
This allows pg_tde to:
- read, create, and update encryption keys
- list and access metadata for the
tde/path
If you encounter the following error:
Ensure your Vault policy includes the following path:
This allows pg_tde to read the mount metadata from Vault.
4. Create an Authentication Method and Token
Enable the AppRole authentication method:
Generate a token associated with the tde-policy:
Example output:
5. Share the token with PostgreSQL
Copy the generated token into the shared secrets directory (shared secrets volume) so PostgreSQL can use it:
You can access this file in PostgreSQL at /etc/postgresql/secrets/vault_token.txt.
6. Register Vault as a global key provider in PostgreSQL
In the PostgreSQL container, connect pg_tde to Vault using:
7. Create and set the global master key
Create the global master key:
Then set it:
8. Test encryption with a sample table
Create a sample table:
Then insert data into the table:
Query the table and confirm that the encryption is functioning:
Example global key provider usage
Parameter descriptions
provider-nameis the name to identify this key providersecret_token_pathis a path to the file that contains an access token with read and write access to the above mount pointurlis the URL of the Vault servermountis the mount point where the keyring should store the keys- [optional]
ca_pathis the path of the CA file used for SSL verification
The following example is for testing purposes only. Use secure tokens and proper SSL validation in production environments:
For more information on related functions, see Function Reference.
Required permissions
The PostgreSQL instance requires the following Vault API capabilities to manage and read encryption keys:
sys/mounts/<mount>/*- read permissions<mount>/data/*- create, read permissions<mount>/metadata/*- list permissions
For more information on Vault permissions, see the following documentation.
Next steps
3.4.9.4 - Using OpenBao as a key provider
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
You can configure pg_tde to use OpenBao as a global key provider for managing encryption keys securely.
This guide assumes that your OpenBao server is already set up and accessible. OpenBao configuration is outside the scope of this document, see OpenBao’s official documentation for more information.
Example usage
To register an OpenBao server as a global key provider:
Parameter descriptions
provider-nameis the name to identify this key providersecret_token_pathis a path to the file that contains an access token with read and write access to the above mount pointurlis the URL of the OpenBao servermountis the mount point where the keyring should store the keys- [optional]
ca_pathis the path of the CA file used for SSL verification - [optional]
namespaceis the namespace within the OpenBao server. Read more about the namespace support in OpenBao` (NOTE: You can use a namespace without ca_path. In this case, specify NULL as the ca_path value)
The following example is for testing purposes only. Use secure tokens and proper SSL validation in production environments:
For more information on related functions, see the link below:
Percona pg_tde Function Reference
Next steps
3.4.9.5 - KMIP configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This overview retains an older qualification of Vault KMIP. The 2.2.2 release notes explicitly announce Vault Enterprise KMIP support; consult those notes for the version-specific status. See site errata.
To use a Key Management Interoperability Protocol (KMIP) server with pg_tde, you must configure it as a global key provider. This setup enables pg_tde to securely fetch and manage encryption keys from a centralized key management appliance.
When using HashiCorp Vault as a KMIP server, this configuration is not a validated deployment model for pg_tde and is not recommended for production use.
For Vault-based key management, use the KV v2 integration instead.
You need the root certificate of the KMIP server and a client key/certificate pair with permissions to create and read keys on the server.
For testing purposes, you can use a Eviden KMS server, which enables easy certificate generation and basic KMIP behavior. If you’re using a production-grade KMIP server, ensure you obtain valid, trusted certificates from the key management appliance.
Example usage
Parameter descriptions
provider-nameis the name of the provider. You can specify any name, it’s for you to identify the providerkmip-IPis the IP address of a domain name of the KMIP serverportis the port to communicate with the KMIP server. Typically used port is 5696server-certificateis the path to the certificate file for the KMIP serverclient_certis the path to the client certificate.client_keyis the path to the client key.
The following example is for testing purposes only.
For more information on related functions, see the link below:
Percona pg_tde Function Reference
Next steps
3.4.9.6 - Thales KMIP server configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde is compatible with the Thales CipherTrust Manager via the KMIP protocol. For a full setup guide, see the Thales documentation.
For more information on adding or modifying the provider, see the Adding or modifying KMIP providers topic.
3.4.9.7 - Fortanix KMIP server configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde is compatible with Fortanix Data Security Manager (DSM) via the KMIP protocol. For a full setup guide, see the Fortanix KMIP documentation here.
For more information on adding or modifying the provider, see the Adding or modifying KMIP providers topic.
3.4.9.8 - Akeyless KMIP server configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde is compatible with the Akeyless CipherTrust Manager via the KMIP protocol. For a full setup guide, see the Akeyless documentation .
For more information on adding or modifying the provider, see the Add or modify KMIP providers topic.
Next steps
3.4.9.9 - Default principal key configuration
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
You can configure a default principal key for the server using a global key provider. This key is used by all databases that do not have their own encryption keys configured.
Configuring the default principal key is a multi-step process that uses the following functions:
- pg_tde_add_global_key_provider_
() adds a global key provider - pg_tde_create_key_using_global_key_provider() creates a principal key at a global key provider
- pg_tde_set_default_key_using_global_key_provider() sets the default principal key and rotates the internal encryption key if one is already configured
Add a global key provider
To add a global key provider, see the Key provider management topic.
Create a default principal key
The sample output below is for demonstration purposes only. Be sure to replace the key name and provider with your actual values.
To create a global principal key, run:
Set a default principal key
To set a default principal key, run:
Parameter description
key-nameis the name under which the principal key is stored in the provider.global_vault_provideris the name of the global key provider you previously configured.
If no error is reported, the action completed successfully.
How key generation works
The key material (actual cryptographic key) is auto-generated by pg_tde and stored securely by the configured provider.
This process sets the default principal key for the entire server. Any database without a key explicitly configured will fall back to this key.
Next steps
To confirm that encryption is working as expected, follow the validation steps:
3.4.10 - Architecture
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.10.1 - Architecture overview
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde is a customizable, complete, data at rest encryption extension. Extension means that pg_tde is delivered as a PostgreSQL extension.
pg_tde relies on extensibility changes in the PostgreSQL core. It currently runs only with Percona Server for PostgreSQL , which includes those changes.
The following sections break down the key architectural components of this design.
a. Customizable means that pg_tde supports many different use cases:
- Encrypting all tables in all databases, or only selected ones
- Storing encryption keys in different external key storage servers, for a list of these see Key management overview
- Using a single key for a clusters, or different keys for different clusters
- Centralizing all keys in one provider, or splitting them across providers
- Controlling permissions: who manages keys and who can create encrypted or unencrypted tables
b. Complete means that pg_tde aims to encrypt data at rest.
c. Data at rest means everything written to the disk. This includes the following:
- Table data files
- Indexes
- Sequences
- Temporary tables
- Write Ahead Log (WAL)
Main components
The main components of pg_tde are:
Core server changes focus on making the server more extensible, allowing the main logic of
pg_tdeto remain separate, as an extension. Core changes also add encryption-awareness to some command line tools that have to work directly with encrypted tables or encrypted WAL files.You can find the source code here .
The
pg_tdeextension implements the encryption code by hooking into the extension points introduced in the core changes, and the already existing extension points in the PostgreSQL server.Everything is controllable with GUC variables and SQL statements, similar to other extensions.
The keyring API and libraries implement the key storage logic with different key providers. The API is internal only, the keyring the libraries are currently part of the main codebase but could be separated into shared libraries in the future.
3.4.10.2 - Encryption architecture
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This section explains how pg_tde implements encryption inside PostgreSQL. It covers the key hierarchy, supported encryption algorithms, encryption workflow, and the core changes that make it possible to encrypt tables, WAL, and other database files.
Together, these components form the foundation of data-at-rest encryption in pg_tde.
Two-key hierarchy
pg_tde uses two kinds of keys for encryption:
- Internal keys to encrypt the data. They are stored in PostgreSQL’s data directory under
$PGDATA/pg_tde - Principal keys, which encrypt internal keys, are stored externally in a Key Management System (KMS) using the key provider API
pg_tde uses one principal key per database. Every internal key for the given database is encrypted using this principal key.
Internal keys are used for specific database files: each file with a different Object Identifier (OID) has a different internal key.
Example:
A table with 4 indexes will have at least 5 internal keys, one for the table and one for each index. Additional associated relations, such as sequences or a TOAST table, also have their own keys.
Encryption algorithm
pg_tde currently uses the following encryption algorithms:
AES-128-CBC,AES-256-CBCfor encrypting database files; encrypted with internal keysAES-128-CTR,AES-256-CTRfor WAL encryption; encrypted with internal keysAES-128-GCM,AES-256-GCMfor encrypting internal keys; encrypted with the principal key
Encryption workflow
You can use pg_tde to encrypt entire databases or only selected tables.
To support this without metadata changes, encrypted tables are labeled with the tde_heap access method marker.
The tde_heap access method is functionally identical to the heap access method. This allows pg_tde to distinguish between encrypted (tde_heap) and non-encrypted (heap) tables.
The initial decision about encryption is made using the postgres event trigger mechanism:
- When the
tde_heapclause is used forCREATE TABLEorALTER TABLEstatements, then the newly created data files are marked as encrypted - After this, the file operations encrypt or decrypt the data
Subsequent decisions are done using a slightly modified Storage Manager (SMGR) API:
- When a database file is re-created with a different ID as a result of a
TRUNCATEor aVACUUM FULLcommand, the newly created file inherits the encryption information - The file is then either encrypted or left unencrypted based on that inheritance
WAL encryption functionality
You can control WAL encryption globally via the pg_tde.wal_encrypt GUC variable, which requires a server restart.
WAL keys also contain the LSN of the first WAL write after key creation. This allows pg_tde to know which WAL ranges are encrypted or not and with which key.
See the Configure WAL encryption chapter for more information.
The setting only controls writes so that only WAL writes are encrypted when WAL encryption is enabled. This means that WAL files can contain both encrypted and unencrypted data, depending on what the status of this variable was when writing the data.
pg_tde keeps track of the encryption status of WAL records using internal keys. When the server is restarted it writes a new internal key if WAL encryption is enabled, or if it is disabled and was previously enabled it writes a dummy key signaling that WAL encryption ended.
With this information the WAL reader code can decide if a specific WAL record has to be decrypted or not and which key it should use to decrypt it.
Encrypting other access methods
Currently pg_tde only encrypts heap tables and other files such as indexes, TOAST tables, sequences that are related to the heap tables.
Indexes include any kind of index that goes through the SMGR API, not just the built-in indexes in PostgreSQL.
Other table access methods that use the SMGR API could also be encrypted. This requires adding a marker access method and extending the event triggers, using the same approach as with heap tables.
Storage Manager (SMGR) API
pg_tde relies on a slightly modified version of the SMGR API. These modifications include:
- Making the API generally extensible, where extensions can inject custom code into the storage manager
- Adding tracking information for files. When a new file is created for an existing relation, references to the existing file are also passed to the SMGR functions
With these modifications, pg_tde implements an additional layer on top of the normal Magnetic Disk SMGR API: if the related table is encrypted, pg_tde encrypts a file before writing it to the disk and, similarly, decrypts it after reading when needed.
WAL encryption
WAL encryption is implemented through a separate, server-wide mechanism that extends PostgreSQL WAL-related APIs. Similar to the SMGR integration, this relies on additional extensions to PostgreSQL core APIs to support encryption of WAL records.
For configuration details, see Configure WAL encryption.
3.4.10.3 - Key and key provider management
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde uses a hierarchy of principal and internal keys to encrypt database files. This chapter covers how to manage these keys, including rotation, regeneration, storage, and key provider configuration, so you can keep your encrypted data secure and accessible.
Principal key rotation
You can rotate principal keys to comply with common policies and to handle situations with potentially exposed principal keys.
Rotation means that pg_tde generates a new version of the principal key, and re-encrypts the associated internal keys with the new key. The old principal key is kept as is at the same location, because it may still be needed to decrypt backups or other databases.
Internal key regeneration
Internal keys for tables, indexes and other data files are generated once a file is created. There’s no way to re-encrypt a file.
There are workarounds for this, because operations that move the table data to a new file, such as VACUUM FULL or an ALTER TABLE that rewrites the file will create a new key for the new file, essentially rotating the internal key. This however means taking an exclusive lock on the table for the duration of the operation, which might not be desirable for huge tables.
WAL internal keys are fixed once created. Every time the server (re)starts, a new WAL key is generated. If WAL encryption is enabled (using pg_tde.wal_encrypt), all WAL writes following the creation of the new key are encrypted with it until another key is generated at the next restart. This ensures that each WAL segment uses a consistent encryption key, without requiring you to manage key rotation manually.
Internal key storage
Internal keys and pg_tde metadata in general are kept in a single $PGDATA/pg_tde directory. This directory stores separate files for each database, such as:
- Encrypted internal keys and internal key mapping to tables
- Information about the key providers
Also, the $PGDATA/pg_tde directory has a special global section marked with the OID 1664, which includes the global key providers and global internal keys.
The global section is used for WAL encryption. Specific databases can use the global section too, for scenarios where users configure individual principal keys for databases but use the same global key provider. For this purpose, you must enable the global provider inheritance.
The global default principal key uses the special OID 1663.
Key providers (principal key storage)
In pg_tde, a Key Management System (KMS) is treated as an external key provider. Key providers store and serve the principal keys that pg_tde uses for encryption and decryption.
When you configure a key provider, pg_tde:
- Uploads new principal keys when they are created
- Retrieves principal keys from the provider when needed for decryption (for example, at startup or restart)
- Caches retrieved keys to reduce repeated lookups
Each key provider requires a detailed configuration, including the service address and authentication information.
For a complete list of supported providers and their configuration steps, see the Key management overview.
Key provider management
Key provider configuration or location may change. For example, a service is moved to a new address or the principal key must be moved to a different key provider type. pg_tde supports both these scenarios enabling you to manage principal keys using simple SQL functions.
In certain cases you can’t use SQL functions to manage key providers. For example, if the key provider changed while the server wasn’t running and is therefore unaware of these changes. The startup can fail if it needs to access the encryption keys.
For such situations, pg_tde also provides command line tools to recover the database.
Sensitive key provider information
Authentication details for key providers are sensitive and must be protected.
Do not store these credentials in the $PGDATA directory alongside the database. Instead, ensure they are stored in a secure location with strict file system permissions to prevent unauthorized access.
3.4.11 - Operations
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.11.1 - Encryption enforcement
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
For pg_tde, encryption enforcement ensures that only encrypted storage is allowed for specific operations, tables, or the entire database. It prevents the accidental creation of unencrypted tables or indexes in environments where encryption is required for compliance, security, or policy enforcement.
What does enforcement do?
When enabled, encryption enforcement:
- Prevents creation of unencrypted tables or indexes
- Enforces consistent encryption usage across tenants, databases, or users
- Can be scoped globally, per database, or per role
Enforce encryption usage
Use the following techniques to enforce the secure use of pg_tde.
1. Enforce encryption across the server
To enforce encryption cluster-wide, set the pg_tde.enforce_encryption variable in postgresql.conf:
Only superusers can set or change this variable.
This ensures that no user, including superusers, can create unencrypted tables. Superusers can however explicitly override the variable in their session.
2. Enforce encryption for a specific database
To apply encryption enforcement only within a specific database, run:
This ensures encryption is enforced only when connected to that database.
3. Enforce encryption for a specific user
You can also enforce encryption on a per-user basis, run:
This ensures that the user example_user cannot create unencrypted tables, regardless of which database they connect to.
Override enforcement for trusted sessions
Superusers can override the variable at the session level:
This allows temporary creation of unencrypted tables in special cases, such as:
- Loading trusted, public reference datasets
- Benchmarking and test environments
- Migration staging before re-encryption
While superusers can disable enforcement in their session, they must do so explicitly. Enforcement defaults remain active to protect from accidental misconfiguration.
3.4.11.2 - Configure multi-tenancy
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The steps below describe how to set up multi-tenancy with pg_tde. Multi-tenancy allows you to encrypt different databases with different keys. This provides granular control over data and enables you to introduce different security policies and access controls for each database so that only authorized users of specific databases have access to the data.
If you don’t need multi-tenancy, use the global key provider. See the configuration steps from the Configure pg_tde section.
For how to enable WAL encryption, refer to the Configure WAL Encryption section.
Considerations
You can use external key providers to manage encryption keys. The recommended approach is to use the Key Management Store (KMS). For more information, see Configure Key Management (KMS) .
If no error is reported when running the commands below, the operation completed successfully.
Enable extension
Load the pg_tde at startup time. The extension requires additional shared memory; therefore, add the pg_tde value for the shared_preload_libraries parameter and restart the postgresql cluster.
Use the ALTER SYSTEM command from
psqlterminal to modify theshared_preload_librariesparameter. This requires superuser privileges.Start or restart the
postgresqlcluster to apply the changes.On Debian and Ubuntu:
On RHEL and derivatives
Create the extension using the CREATE EXTENSION command. You must have the privileges of a superuser or a database owner to use this command. Connect to
psqlas a superuser for a database and run the following command:The
pg_tdeextension is created for the currently used database. To enable data encryption in other databases, you must explicitly run theCREATE EXTENSIONcommand against them.TipYou can have the
pg_tdeextension automatically enabled for every newly created database. Modify the templatetemplate1database as follows:
Key provider configuration
You must do these steps for every database where you have created the extension. For more information on configurations, please see the Configure Key Management (KMS) topic.
Set up a key provider.
The KMIP server setup is out of scope of this document.
Make sure you have obtained the root certificate for the KMIP server and the keypair for the client. The client key needs permissions to create / read keys on the server. Find the configuration guidelines for the HashiCorp Vault Enterprise KMIP Secrets Engine .
For testing purposes, you can use the Eviden KMS server which enables you to set up required certificates. To use a real KMIP server, make sure to obtain the valid certificates issued by the key management appliance.
where:
provider-nameis the name of the provider. You can specify any name, it’s for you to identify the provider.kmip-addris the IP address of a domain name of the KMIP serverportis the port to communicate with the KMIP server. Typically used port is 5696.server-certificateis the path to the certificate file for the KMIP server.client-certis the path to the client certificate.client-keyis the path to the client key.
Warning: This example is for testing purposes only:
The Vault server setup is out of scope of this document.
where:
urlis the URL of the Vault servermountis the mount point where the keyring should store the keyssecret_token_pathis a path to the file that contains an access token with read and write access to the above mount point- [optional]
ca_pathis the path of the CA file used for SSL verification
Warning: This example is for testing purposes only:
This setup is intended for development and stores the keys unencrypted in the specified data file.
**Warning:** This example is for testing purposes only: ```sql SELECT pg_tde_add_database_key_provider_file( 'file-keyring', '/tmp/pg_tde_test_local_keyring.per' ); ```Create a key
where:
name-of-the-keyis the name of the principal key. You will use this name to identify the key.provider-nameis the name of the key provider you added before. The principal key is associated with this provider and it is the location where it is stored and fetched from.
Warning: This example is for testing purposes only:
NoteThe key is auto-generated.
Use the key as principal key
where:
name-of-the-keyis the name of the principal key. You will use this name to identify the key.provider-nameis the name of the key provider you added before. The principal key will be associated with this provider.
Warning: This example is for testing purposes only:
3.4.11.3 - Backup with WAL encryption enabled
For Mimus, choose the backup client by WAL key history and use the client paired with the kernel. See the tested physical backup and restore sequence. Mimus procedure
Do not rotate encryption keys while a backup is running. This may result in an inconsistent backup and restore failure. This applies to all backup tools.
For more details, see Limitations of pg_tde.
To create a backup with WAL encryption enabled:
Copy the
pg_tdedirectory from the source server’s data directory, for example/var/lib/postgresql/data/pg_tde/, including thewal_keysand1664_providersfiles, to the backup destination directory wherepg_tde_basebackupwill write the backup.Also copy any external files referenced by your providers configuration (such as certificate or key files) into the same relative paths under the backup destination, so that they are located and validated by
pg_tde_basebackup -E.Run:
Where:
-D /path/to/backupspecifies the backup location where you have to copypg_tde.-E(or--encrypt-wal) enables WAL encryption and validates that the copiedpg_tdeand provider files are present and that the server key is accessible (required). The-Eoption accepts a cipher argument. The currently supported values areaes_128andaes_256. If-Eis not specified,pg_tde_basebackupattempts to determine the cipher from the server’s key. If no cipher can be determined,pg_tde_basebackupdefaults toaes_128.
- The
-Eflag only works with the-X streamoption (default). It is not compatible with-X noneor-X fetch. For more information, see the backup method compatibility with WAL encryption. - The
-Eflag is only supported with the plain output format (-F p). It cannot be used with the tar output format (-F t).
Key rotation during backups
Do not rotate encryption keys while a backup is in progress. This applies to all backup tools.
Backups created during key rotation may fail to start during WAL replay and may lead to corruption of encrypted data (tables, indexes, and other relations).
For example, you may see errors such as:
To ensure standby recoverability, plan key rotations outside backup windows or take a new full backup after rotation completes.
Restore a backup created with WAL encryption
When you want to restore a backup created with pg_tde_basebackup -E:
- Ensure all external files referenced by your providers configuration (such as certificates or key files) are also present and accessible at the same relative paths.
- Start PostgreSQL with the restored data directory.
Backup method compatibility with WAL encryption
Tar format (-F t):
- Works with
-X fetch. - Does not support
-X streamwhen WAL encryption is enabled. Usingpg_tde_basebackup -F t -X streamwill create a broken replica.
Streaming mode (-X stream):
- Must specify
-E(--encrypt-wal). - Without
-E, backups may contain decrypted WAL whilewal_encryption=onremains inpostgresql.confandpg_tde/wal_keysare copied. This leads to startup failures and compromised data in the backup.
Fetch mode (-X fetch):
- Compatible with encrypted WAL without requiring any additional flags.
None (-X none):
- Excludes WAL from the backup and is unaffected by WAL encryption.
If the source server has pg_tde/wal_keys, running pg_tde_basebackup with -X none or -X fetch produces warnings such as:
You can safely ignore the warnings with -X none or -X fetch, since no WAL streaming occurs.
3.4.11.4 - Restore encrypted backups
For Mimus, restore the matching kernel, startup libraries, provider metadata and historical keys along with the backup. Mimus procedure
To restore an encrypted backup created with an earlier key, ensure the key is still available in your Key Management System (KMS). The backup remains encrypted on disk, pg_tde uses the correct key to transparently access the data.
How pg_tde uses old keys to load backups
- KMS: stores the principal key(s) that were active when the backup was made.
- Encrypted backup: contains data encrypted with the key available at that time.
- Current server:
pg_tdeautomatically loads the backup if the key is accessible through the KMS.
The table (internal) keys are stored within the backup. At runtime, pg_tde retrieves the principal key(s) from the configured KMS and uses them to decrypt the internal keys, enabling access to the encrypted table data.
If the required key(s) get deleted or are missing, the backup cannot be read.
If the key(s) still exists but the KMS configuration has changed, you can use pg_tde_change_key_provider to update the configuration.
However, if the key(s) got deleted from all accessible KMS sources, the encrypted backup is unrecoverable.
3.4.11.5 - Upgrade pg_tde
Percona’s package upgrade steps apply to Percona PostgreSQL. For a major upgrade of a TDE-marked Mimus cluster use logical dump and restore.
The version of pg_tde available to you depends on your version of Percona Distribution for PostgreSQL.
To use a newer pg_tde release, first ensure that your Percona Distribution for PostgreSQL version includes it.
This document describes upgrading the pg_tde extension within the same PostgreSQL major version. For PostgreSQL major version upgrades on clusters that use pg_tde, use pg_tde_upgrade.
Before you start
pg_tde 2.2.0 is not compatible with Percona Distribution for PostgreSQL older than 17.10 or 18.4. Upgrade your distribution first before upgrading pg_tde.
Using pg_upgrade on an encrypted cluster is not supported and will result in data corruption. The server may start successfully but queries against encrypted tables will fail.
Procedure
Take a full backup before upgrading.
Upgrade the
pg_tdepackage via your package manager.Restart the
postgresqlservice.Connect to each database where
pg_tdeis installed and run:NoteThe catalog version of
pg_tdemay not change between patch releases. You can runALTER EXTENSION pg_tde UPDATEsafely regardless.Verify the upgrade:
3.4.11.6 - Remove encryption from an encrypted table
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Method 1. Change the access method
If you encrypted a table with the tde_heap access method and need to remove the encryption from it, run the following command against the desired table (mytable in the example below):
Note that the SET ACCESS METHOD command drops hint bits and this may affect performance. Running a plain SELECT count(*) or VACUUM command on the entire table will check every tuple for visibility and set its hint bits. Therefore, after executing the ALTER TABLE command, run a simple count(*) on your tables:
Check that the table is not encrypted:
The output returns f meaning that the table is no longer encrypted.
Method 2. Create a new not encrypted table on the base of the encrypted one
Alternatively, you can create a new not encrypted table with the same structure and data as the initial table. For example, the original encrypted table is EncryptedCustomers. Use the following command to create a new table Customers:
The new table Customers inherits the structure and the data from EncryptedCustomers.
(Optional) If you no longer need the EncryptedCustomers table, you can delete it.
3.4.11.7 - Uninstall pg_tde
Mimus records TDE in the data directory. Retain the matching preload, tools and historical keys for recovery, including after dropping the SQL extension. To retire the dependency, migrate into a fresh cluster. Mimus procedure
If you no longer wish to use Transparent Data Encryption (TDE) in your deployment, you can remove the pg_tde extension.
To proceed, you must have one of the following privileges:
- Superuser privileges (to remove the extension globally), or
- Database owner privileges (to remove it from a specific database only)
To uninstall pg_tde, follow the steps below.
Step 1. Remove pg_tde from all databases
Before uninstalling, you must remove the extension from every database where it is loaded. If pg_tde was installed in templates, new databases inherit it. You must drop it from the templates first or future restores/creates will break.
a. Rewrite encrypted tables:
To rewrite an encrypted table back to its default storage method:
b. Remove the extension once all encrypted tables have been rewritten or dropped:
If there are any encrypted objects that were not previously decrypted or deleted, this command will fail and you have to follow the steps above for these objects.
Repeat step 1 for every database in your cluster.
Step 2. Turn off WAL encryption
If you are using WAL encryption, you need to turn it off before you uninstall the pg_tde library:
a. Run:
b. Restart the PostgreSQL cluster to apply the changes:
- On Debian and Ubuntu:
- On RHEL and derivatives:
Step 3. Uninstall the pg_tde shared library
This process removes the extension, but does not decrypt data automatically. Only uninstall the shared library after all encrypted data has been removed or decrypted and WAL encryption has been disabled.
Encrypted WAL pages will not be decrypted, so any postgres cluster needing to read them will need the pg_tde library loaded, and the WAL encryption keys available and in use.
At this point, the shared library is still loaded but no longer active. To fully uninstall pg_tde, complete the steps below.
a. Run SHOW shared_preload_libraries to view the current configuration of preloaded libraries.
For example:
b. Remove pg_tde from the list and apply the new setting using ALTER SYSTEM SET shared_preload_libraries=<your list of libraries>.
For example:
Your list of libraries will most likely be different than the above example. Take care not to remove other required extensions. Only delete pg_tde from the list.
If pg_tde is the only shared library in the list, and it was set via postgresql.conf you cannot disable it using the ALTER SYSTEM SET ... command. Instead:
- Remove the
shared_preload_librariesline frompostgresql.conf - Run
ALTER SYSTEM RESET shared_preload_libraries;
c. Restart the postgresql cluster to apply the changes:
On Debian and Ubuntu:
On RHEL and derivatives:
NoteThe service name may differ depending on your distribution and PostgreSQL version.nod
Step 4. (Optional but recommended) Clean up configuration
At this point it is safe to remove any configuration related to pg_tde from postgresql.conf and postgresql.auto.conf. Look for any configuration parameters prefixed with pg_tde. and remove or comment them out, as needed.
Troubleshooting: PANIC checkpoint not found on restart
This can happen if WAL encryption was not properly disabled before removing pg_tde from shared_preload_libraries, when the PostgreSQL server was not restarted after disabling WAL encryption (see step 3.c).
You might see this when restarting the PostgreSQL cluster:
This error means PostgreSQL is trying to read encrypted WAL without pg_tde loaded.
To resolve it follow these steps:
- Re-add
pg_tdetoshared_preload_libraries - Restart the PostgreSQL cluster
- Follow the instructions for turning off WAL encryption before uninstalling the shared library again
Two restarts are required to uninstall properly if WAL encryption was enabled:
- First to disable WAL encryption
- Second to remove the
pg_tdelibrary
3.4.12 - Configure WAL encryption
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
WAL encryption requires a principal key. You can satisfy this requirement in one of the following ways:
A deployment with WAL encryption is not supported unless you use both of the following tools for WAL archiving and recovery:
pg_tde_archive_decryptinarchive_commandpg_tde_restore_encryptinrestore_command
If you use pgBackRest, you must also disable its asynchronous archiving, WAL header checks, and page checksum validation. Add these settings to the applicable pgBackRest configuration section:
Option 1: Use the default principal key
If a default principal key is already configured for the server, WAL encryption uses it automatically. No additional server key configuration is required.
If you have not yet configured a default principal key, see Default Principal Key configuration.
Option 2: Configure a dedicated server principal key for WAL
For a comprehensive list of supported pg_tde WAL encryption tools see Limitations of pg_tde.
Create the
pg_tdeextension if it does not exist:Configure a global key provider
Before creating the server (principal) key for WAL encryption, you must first configure a global key provider. See Key management overview for detailed instructions on configuring supported key providers.
Create the server (principal) key using the global key provider
The server key (also referred to as the principal key) is the key used by PostgreSQL to encrypt WAL data. See pg_tde_create_key_using_global_key_provider for more detailed instructions.
Set the server (principal) key
This step sets the previously created server (principal) key as the active key used by PostgreSQL for WAL encryption. See pg_tde_set_server_key_using_global_key_provider for more detailed instructions.
Enable WAL encryption using the
ALTER SYSTEMcommand. You need the privileges of the superuser to run this command:Restart the server to apply the changes.
- On Debian and Ubuntu:
- On RHEL and derivatives
(Optional) Verify that WAL encryption is enabled:
Now WAL files start to be encrypted for both encrypted and unencrypted tables.
For more technical references related to architecture, variables or functions, see: Technical Reference
💬 Need help customizing this for your infrastructure? Contact Percona support
3.4.13 - Streaming replication with tde_heap
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Creating a key and assigning the server key are separate operations. See site errata.
This section outlines how to set up PostgreSQL streaming replication when the pg_tde extension, specifically the tde_heap access method, is enabled on the primary server.
Before you begin, ensure you have followed the pg_tde setup instructions.
You do not need to run CREATE EXTENSION on the standby. It will be replicated automatically.
1. Configure the Primary
Create a principal key
First create a key on the configured global provider using pg_tde_create_key_using_global_key_provider. Then assign it as the server key with pg_tde_set_server_key_using_global_key_provider.
Create the replication role
Create a replication role on the primary:
Configure pg_hba.conf
To allow the replica to connect to the primary server, add the following line in pg_hba.conf:
Ensure that it is placed before the other host rules for replication and then reload the configuration:
2. Configure the Standby
Perform a database backup
Run the base backup from your standby machine to pull the encrypted base backup:
Configure postgresql.conf
After the base backup completes, add the following line to the standby’s postgresql.conf file:
3. Start and validate replication
Assuming that the primary and the standby are running on separate hosts, start the PostgreSQL service:
If you’re using a KMS provider, such as Vault or KMIP, make sure that both the primary and the standby have access to the same key management configuration, and that the paths to the configuration files are identical on both systems.
For example:
- If you configure Vault with a secret path:
/path/to/secret.file, then that file must exist at the same path on both the primary and the standby. - If you use the
keyring_fileprovider, be aware that it stores key material in a local file and it is not designed for shared or concurrent use across multiple servers. It is not recommended in replication setups.
- On primary:
- On standby:
Want to verify that everything is working? After creating an encrypted table on the primary, run the following command on the standby to confirm that the encryption is active and the keys are resolved:
3.4.14 - Technical reference
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.14.1 - Technical reference overview
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This section covers the internal components and tools that power pg_tde.
Use it to understand how encryption is implemented, fine-tune a configuration, leverage advanced CLI tools and functions for diagnostics and customization.
Usage reference
A description of the main pg_tde operations available, including configuring key providers, managing principal keys, setting permissions, and encrypting tables.
Functions
Use built-in functions to manage key providers, create and rotate principal keys, and verify encryption status. Includes commands for Vault, KMIP, and local providers, plus utilities to inspect or validate keys.
GUC Variables
Configure how pg_tde behaves with PostgreSQL. Control WAL encryption, enforce encryption for new tables, and manage global provider inheritance. Includes scope levels, defaults, and permission requirements.
Streaming replication
Learn how to configure PostgreSQL streaming replication with pg_tde using the tde_heap access method. Covers primary and standby setup, key management requirements, and validation steps.
3.4.14.2 - Usage reference
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Obsolete GUC names and invalid server/default function variants are corrected against the pinned source code. See site errata.
This chapter describes the main pg_tde operations available, including configuring key providers, managing principal keys, setting permissions, and encrypting tables.
Use this chapter as a reference when performing specific pg_tde tasks.
Prerequisites
Before using pg_tde, complete the setup steps as described in Install pg_tde.
Add providers
You can add key providers to either the global or database specific scope.
If pg_tde.inherit_global_providers is on, global providers are visible for all databases, and can be used.
If pg_tde.inherit_global_providers is off, global providers are only used for WAL encryption.
To add a global provider:
To add a database specific provider:
Change providers
To change a value of a global provider:
To change a value of a database specific provider:
These functions also allow changing the type of a provider but do not migrate any data. They are expected to be used during infrastructure migration, for example when the address of a server changes.
Change providers from the command line
To change a provider from a command line, pg_tde provides the pg_tde_change_key_provider command line tool.
This tool works similarly to the above functions, with the following syntax:
Since this tool is intended to be run while the PostgreSQL server is stopped, it bypasses all permission checks. For this reason, it requires a database OID (dbOid) instead of a database name, as it cannot access the system catalogs.
This tool does not validate any parameters.
Delete providers
Providers can be deleted by using the following functions:
For database specific providers, the function first checks if the provider is used or not, and the provider is only deleted if it’s not used.
For global providers, the function checks if the provider is used anywhere, WAL or any specific database, and returns an error if it is.
List/query providers
pg_tde provides 2 functions to show providers:
pg_tde_list_all_database_key_providers()pg_tde_list_all_global_key_providers()
These functions return a list of provider names, type and configuration.
Provider permissions
pg_tde implements access control based on execution rights on the administration functions.
For keys and providers administration, it provides two functions:
These functions take a role name as a string argument, for example 'user1'.
Create and rotate keys
Principal keys can be created using the following functions:
Principal keys can be used or rotated using the following functions:
Default principal key
With pg_tde.inherit_global_providers, it is also possible to set up a default global principal key, which will be used by any database which has the pg_tde extension enabled, but doesn’t have a database specific principal key configured using pg_tde_set_key_using_(global/database)_key_provider.
With this feature, it is possible for the entire database server to easily use the same principal key for all databases, completely disabling multi-tenancy.
Manage a default key
You can manage a default key with the following functions:
pg_tde_create_key_using_global_key_provider('key-name','provider-name')pg_tde_set_default_key_using_global_key_provider('key-name','provider-name')pg_tde_delete_default_key()
pg_tde_delete_default_key() is only possible if there’s no database currently using the default principal key.
Changing the default principal key will rotate the encryption of internal keys for all databases using the current default principal key.
Delete a key
The pg_tde_delete_key() function unsets the principal key for the current database. If the current database has any encrypted tables, and there isn’t a default principal key configured, it reports an error instead. If there are encrypted tables, but there’s also a default principal key, internal keys will be encrypted with the default key.
WAL keys cannot be unset, as server keys are managed separately.
Current key details
pg_tde_key_info() returns the name of the current principal key, and the provider it uses.
pg_tde_server_key_info() does the same for the server key.
pg_tde_default_key_info() does the same for the default key.
pg_tde_verify_key() checks that the key provider is accessible, that the current principal key can be downloaded from it, and that it is the same as the current key stored in memory - if any of these fail, it reports an appropriate error.
Key permissions
Users with management permissions to a specific database (pg_tde_(grant/revoke)_(global/database)_key_management_(to/from)_role) can change the keys for the database, and use the current key functions. This includes creating keys using global providers, if pg_tde.inherit_global_providers is enabled.
Also the pg_tde_(grant/revoke)_database_key_management_to_role function deals with only the specific permission for the above function: it allows a user to change the key for the database, but not to modify the provider configuration.
Create an encrypted table
To create an encrypted table, use the following command:
Alter an encrypted table
To alter or modify an encrypted table, use the following command:
Change the pg_tde.inherit_global_providers setting
It is possible to use pg_tde with pg_tde.inherit_global_providers = on, refer to the global keys or keyrings in databases, and then change this setting to off.
In this case, existing references to global providers or the global default principal key keep working as before, but new references to the global scope cannot be made.
3.4.15 - GUC Variables
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The pg_tde extension provides GUC variables to configure the behaviour of the extension:
pg_tde.wal_encrypt
Type - boolean
Default - off
A boolean variable that controls if WAL writes are encrypted or not.
Changing this variable requires a server restart, and can only be set at the server level.
WAL encryption is controlled globally. If enabled, all WAL writes are encrypted in the entire PostgreSQL cluster.
This variable only controls new writes to the WAL, it doesn’t affect existing WAL records.
pg_tde is always capable of reading existing encrypted WAL records, as long as the keys used for the encryption are still available.
Enabling WAL encryption requires a configured global principal key. Refer to the WAL encryption configuration topic for more information.
pg_tde.enforce_encryption
Type - boolean
Default - off
A boolean variable that controls if the creation of new, not encrypted tables is allowed.
If enabled, CREATE TABLE statements will fail unless they use the tde_heap access method.
Similarly, ALTER TABLE <x> SET ACCESS METHOD is only allowed, if the access method is tde_heap.
Other DDL operations are still allowed. For example other ALTER commands are allowed on unencrypted tables, as long as the access method isn’t changed.
You can set this variable at the following levels:
- global - for the entire PostgreSQL cluster
- database - for specific databases
- user - for specific users
- session - for the current session
Setting or changing the value requires superuser permissions. For examples, see the Encryption Enforcement topic.
pg_tde.inherit_global_providers
Type - boolean
Default - on
A boolean variable that controls if databases can use global key providers for storing principal keys.
If disabled, functions that change the key providers can only work with database local key providers.
In this case, the default principal key, if set, is also disabled.
You can set this variable at the following levels:
- global - for the entire PostgreSQL cluster
- database - for specific databases
- user - for specific users
- session - for the current session
Setting this variable doesn’t affect existing uses of global keys. It only prevents the creation of new principal keys using global providers.
pg_tde.cipher
Type - string
Default - aes_128
A string variable that selects the cipher (encryption algorithm). Currently, the supported values are aes_128 and aes_256, corresponding to AES 128-bit and 256-bit key lengths, respectively.
The setting applies only to objects created after the value is set, including principal keys, internal keys, and data encrypted by those keys. Existing objects are not re-encrypted.
3.4.16 - Functions
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Parameter names and key scopes are corrected against the pinned source code. See site errata.
The pg_tde extension provides functions for managing different aspects of its operation:
If no error is reported when running the commands below, the operation completed successfully.
Key provider management
A key provider is a system or service responsible for managing encryption keys. For more information on the key providers pg_tde supports see the Key management overview.
Key provider management includes the following operations:
Add a key provider
You can add a new key provider using the provided functions, which are implemented for each provider type.
There are two functions to add a key provider: one function adds it for the current database and another one - for the global scope.
pg_tde_add_database_key_provider_<type>('provider-name', <provider specific parameters>)pg_tde_add_global_key_provider_<type>('provider-name', <provider specific parameters>)
When you add a new provider, the provider name must be unique in the scope. But a local database provider and a global provider can have the same name.
Change an existing provider
You can change an existing key provider using the provided functions, which are implemented for each provider type.
There are two functions to change existing providers: one to change a provider in the current database, and another one to change a provider in the global scope.
pg_tde_change_database_key_provider_<type>('provider-name', <provider specific parameters>)pg_tde_change_global_key_provider_<type>('provider-name', <provider specific parameters>)
When you change a provider, the referred name must exist in the database local or a global scope.
The change functions require the same parameters as the add functions. They overwrite the setting for every parameter except for the name, which can’t be changed.
Provider specific parameters differ for each implementation. Refer to the respective subsection for details.
The updated provider must be able to retrieve the same principal keys as the original configuration. If the new configuration cannot access existing keys, encrypted data and backups will become unreadable.
Add or modify Vault providers
The Vault provider connects to a HashiCorp Vault or an OpenBao server, and stores the keys on a key-value store version 2.
Use the following functions to add the Vault provider:
These functions change the Vault provider:
where:
provider-nameis the name of the key providerurlis the URL of the Vault servermountis the mount point on the Vault server where the key provider should store the keyssecret_token_pathis a path to the file that contains an access token with read and write access to the above mount point- [optional]
ca_pathis the path of the CA file used for SSL verification - [namespace]
namespaceis the path of the namespace when using Vault with namespaes
Add or modify KMIP providers
The KMIP provider uses a remote KMIP server.
Use these functions to add a KMIP provider:
These functions change the KMIP provider:
where:
provider-nameis the name of the providerkmip-addris the IP address or domain name of the KMIP serverportis the port to communicate with the KMIP server. Most KMIP servers use port 5696.server-certificateis the path to the certificate file for the KMIP server.client-certificateis the path to the client certificate.client-keyis the path to the client key.
The specified access parameters require permission to read and write keys at the server.
Add or modify local key file providers
This provider manages database keys using a local key file.
This function is intended for development or quick testing, and stores the keys unencrypted in the specified data file.
Local key file providers are not recommended for production environments, they lack the security and manageability of external key management systems.
Add a local key file provider:
Change a local key file provider:
where:
provider-nameis the name of the provider. You can specify any name, it’s for you to identify the provider./path/to/the/key/provider/data.fileis the path to the key provider file.
Delete a provider
These functions delete an existing provider in the current database or in the global scope:
pg_tde_delete_database_key_provider('provider-name')pg_tde_delete_global_key_provider('provider-name')
You can only delete key providers that are not currently in use. An error is returned if the current principal key is using the provider you are trying to delete.
If the use of global key providers is enabled via the pg_tde.inherit_global_providers GUC, you can delete a global key provider only if it isn’t used anywhere, including any databases. If it is used in any database, an error is returned instead.
List key providers
These functions list the details of all key providers for the current database or for the global scope, including all configuration values:
pg_tde_list_all_database_key_providers()pg_tde_list_all_global_key_providers()
Principal key management
Use these functions to create a new principal key at a given keyprover, and to use those keys for a specific scope such as a current database, a global or default scope. You can also use them to start using a different existing key for a specific scope.
Principal keys are stored on key providers by the name specified in this function - for example, when using the Vault provider, after creating a key named “foo”, a key named “foo” will be visible on the Vault server at the specified mount point.
pg_tde_create_key_using_database_key_provider
Creates a principal key using the database-local key provider with the specified name. Use this key later with pg_tde_set_key_using_database_key_provider().
pg_tde_create_key_using_global_key_provider
Creates a principal key at a global key provider with the given name. Use this key later with the pg_tde_set_* series of functions.
pg_tde_set_key_using_database_key_provider
Sets the principal key for the current database, using the specified local key provider. It also rotates internal encryption keys to use the specified principal key.
This function is typically used when working with per-database encryption through a local key provider.
pg_tde_set_key_using_global_key_provider
Sets or rotates the principal key for the current database, using the specified global key provider. For WAL encryption, use pg_tde_set_server_key_using_global_key_provider.
pg_tde_set_server_key_using_global_key_provider
Sets or rotates the server principal key using the specified global key provider. Use this function to set a principal key for WAL encryption.
pg_tde_set_default_key_using_global_key_provider
Sets or rotates the default principal key for the server using the specified global key provider.
The default key is automatically used as a principal key by any database that doesn’t have an individual key provider and key configuration.
pg_tde_delete_key
Unsets the principal key for the current database. If the current database has any encrypted tables, and there isn’t a default principal key configured, it reports an error instead. If there are encrypted tables, but there’s also a default principal key, internal keys will be encrypted with the default key.
pg_tde_delete_default_key
Unsets default principal key. It’s possible only if no database uses default principal key.
Encryption status check
pg_tde_is_encrypted
Tells if a relation is encrypted using the pg_tde extension or not. Returns
NULL if a relation lacks storage like views, foreign tables, and partitioned
tables and indexes.
To verify that a table is encrypted, run the following statement:
You can also verify if the table in a custom schema is encrypted. Pass the schema name for the function as follows:
This can additionally be used to verify that indexes and sequences are encrypted.
pg_tde_key_info
Displays information about the principal key for the current database, if it exists.
pg_tde_server_key_info
Displays information about the principal key for the server scope, if exists.
pg_tde_default_key_info
Displays the information about the default principal key, if it exists.
pg_tde_verify_key
This function checks that the current database has a properly functional encryption setup, which means:
- A key provider is configured
- The key provider is accessible using the specified configuration
- There is a principal key for the database
- The principal key can be retrieved from the remote key provider
- The principal key returned from the key provider is the same as cached in the server memory
If any of the above checks fail, the function reports an error.
pg_tde_verify_server_key
This function checks that the server scope has a properly functional encryption setup, which means:
- A key provider is configured
- The key provider is accessible using the specified configuration
- There is a principal key for the global scope
- The principal key can be retrieved from the remote key provider
- The principal key returned from the key provider is the same as cached in the server memory
If any of the above checks fail, the function reports an error.
pg_tde_verify_default_key
This function checks that the default key is properly configured, which means:
- A key provider is configured
- The key provider is accessible using the specified configuration
- There is a principal key that can be used for any scope
- The principal key can be retrieved from the remote key provider
- The principal key returned from the key provider is the same as cached in the server memory
If any of the above checks fail, the function reports an error.
3.4.17 - Command-line tools
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
3.4.17.1 - Overview of pg_tde CLI tools
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The pg_tde extension provides a set of command-line utilities designed specifically for operating on encrypted data and clusters. These utilities exist in parallel with the standard PostgreSQL utilities but you must use them when working with data encrypted by pg_tde.
The standard PostgreSQL tools cannot operate on pg_tde-encrypted WAL or tables.
New pg_tde specific tools
These tools are introduced exclusively by pg_tde to support key rotation and WAL encryption workflows:
- pg_tde_change_key_provider: change the encryption key provider for a database
- pg_tde_archive_decrypt: decrypts WAL before archiving
- pg_tde_restore_encrypt: a custom restore command for making sure the restored WAL is encrypted
Tools for working with pg_tde-encrypted data
These tools are modified versions of standard PostgreSQL utilities that include pg_tde support. You must use the pg_tde_* variants when working with encrypted WAL or tables:
- pg_tde_checksums: verify data checksums
- pg_tde_waldump: inspect and decrypt WAL files
- pg_tde_basebackup: create base backups that include encrypted data
- pg_tde_resetwal: reset the WAL for clusters using
pg_tde - pg_tde_rewind: rewind clusters that use encrypted WAL
- pg_tde_upgrade: perform major version upgrades of clusters with
pg_tde
3.4.17.2 - pg_tde_archive_decrypt
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The pg_tde_archive_decrypt tool wraps an archive command and decrypts WAL files before archiving. It allows external tools to access unencrypted WAL data, which is required because WAL encryption keys in the two-key hierarchy are host-specific and may not be available on the replay host.
For more information on the encryption architecture and key hierarchy, see Architecture.
This tool is often used in conjunction with pg_tde_restore_encrypt to support WAL archive.
How it works
- Decrypts the WAL segment to a temporary file on a RAM disk (
/dev/shm) - Replaces
%pand%fin the archive command with the path and name of the decrypted file - Executes the archive command
To ensure security, encrypt the files stored in your WAL archive using tools like PgBackRest.
Usage
Parameter descriptions
DEST-NAME: name of the WAL file to send to the archiveSOURCE-PATH: path to the original encrypted WAL fileARCHIVE-COMMAND: archive command to wrap.%pand%fare replaced with the decrypted WAL file path and WAL file name, respectively.
Options
-V, --version: show version information, then exit-?, --help: show help information, then exit
Any %f or %p parameter in ARCHIVE-COMMAND has to be escaped as %%f or %%p respectively if used as archive_command in postgresql.conf.
Examples
Using cp
Using PgBackRest
A deployment with WAL encryption is not supported unless archive_command uses pg_tde_archive_decrypt and restore_command uses pg_tde_restore_encrypt.
Disable the following pgBackRest features in the applicable pgBackRest configuration section:
3.4.17.3 - pg_tde_restore_encrypt
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The placeholder descriptions now match the tool’s built-in help. See site errata.
The pg_tde_restore_encrypt tool wraps a normal restore command from the WAL archive and writes them to disk in a format compatible with pg_tde.
This command is often use together with pg_tde_archive_decrypt.
How it works
- Replaces
%fand%pin the restore command with the WAL file name and temporary file path (in/dev/shm) - Runs the restore command to fetch the unencrypted WAL from the archive and write it to the temp file
- Encrypts the temp file and writes it to the destination path in PostgreSQL’s data directory
Usage
Parameter descriptions
SOURCE-NAME: name of the WAL file to retrieve from the archiveDEST-PATH: path where the encrypted WAL file should be writtenRESTORE-COMMAND: restore command to wrap;%fand%pare replaced with the WAL file name and path to write the unencrypted WAL, respectively
Options
-V, --version: show version information, then exit-?, --help: show help information, then exit
Any %f or %p parameter in RESTORE-COMMAND has to be escaped as %%f or %%p respectively if used as restore_command in postgresql.conf.
Examples
Using cp
Using PgBackRest
A deployment with WAL encryption is not supported unless archive_command uses pg_tde_archive_decrypt and restore_command uses pg_tde_restore_encrypt.
Disable the following pgBackRest features in the applicable pgBackRest configuration section:
3.4.17.4 - pg_tde_change_key_provider
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
A tool for modifying the configuration of a key provider, possibly also changing its type.
This tool edits the configuration files directly, ignoring permissions or running postgres processes.
Its only intended use is to fix servers that can’t start up because of inaccessible key providers.
For example, you restore from an old backup and the address of the key provider changed in the meantime. You can use this tool to correct the configuration, allowing the server to start up.
Warning: Use this tool only when the server is offline. To modify the key provider configuration when the server is up and running, use the pg_tde_change_(global/database)_key_provider_<type> SQL functions.
Example usage
To modify the key provider configuration, specify all parameters depending on the provider type in the same way as you do when using the pg_tde_change_(global/database)_key_provider_<type> SQL functions.
The general syntax is as follows:
Parameter description
- [optional]
<datadir>is the data directory.pg_tdeuses the$PGDATAenvironment variable if this is not specified <provider_name>is the name you assigned to the key provider<new_provider_type>can be afile,vaultorkmip<dbOid>
Depending on the provider type, the additional parameters are:
3.4.17.5 - pg_tde_checksums
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde_checksums is a PostgreSQL command-line utility used to enable, disable, or verify data checksums on a PostgreSQL data directory. The tool is modified to add support for working with encrypted tables.
3.4.17.6 - pg_tde_waldump
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
pg_tde_waldump displays a human-readable rendering of the Write-Ahead Log (WAL) for a PostgreSQL database cluster.
To read encrypted WAL records, pg_tde_waldump provides the following additional option:
-k, --keyring-path=PATHis the path to the directory containing the WAL keyring configuration files. This is typically thepg_tde/directory inside the PostgreSQL data directory. The following files are included:wal_keys1664_providers
pg_tde_waldump cannot read encrypted WAL unless --keyring-path is specified.
Since pg_tde 2.3.0, pg_tde_waldump recognizes the pg_tde custom resource manager, prints its WAL records correctly, and accepts it in the --rmgr filter.
3.4.17.7 - pg_tde_upgrade
This physical upgrade procedure applies to Percona PostgreSQL. For a major upgrade of a TDE-marked Mimus cluster, use logical dump and restore into a new cluster. Mimus procedure
pg_tde_upgrade is the supported method for performing PostgreSQL major version upgrades on clusters that use pg_tde.
Use this tool instead of pg_upgrade whenever the cluster uses pg_tde, including clusters with encrypted tables or encrypted WAL.
pg_tde_upgrade wraps pg_upgrade to simplify upgrading clusters with encrypted relations or WAL. It can also be run safely on clusters without pg_tde enabled.
When to use which upgrade procedure
| Scenario | Procedure |
|---|---|
Upgrade Percona PostgreSQL from one major version to another (for example from 17 to 18) on a cluster that uses pg_tde | Use this pg_tde_upgrade procedure |
Upgrade the pg_tde extension or package version within the same PostgreSQL major version | Follow the pg_tde upgrade procedure |
Upgrade PostgreSQL from one major version to another on a cluster that does not use pg_tde | Use pg_upgrade and follow the major upgrade procedure |
| Upgrade Percona PostgreSQL to a newer minor version within the same major version (for example from 18.3 to 18.4) | Follow the minor upgrade procedure |
Implementation
pg_tde_upgrade copies the pg_tde subdirectory from the old data directory to the new data directory and then runs pg_upgrade as normal except for using pg_tde_resetwal instead of pg_resetwal.
Ensure that pg_tde is included in shared_preload_libraries and that you have the right setting for pg_tde.wal_encrypt in the new cluster.
Usage
Use pg_tde_upgrade in place of pg_upgrade when performing a PostgreSQL major version upgrade on a cluster that uses pg_tde.
pg_tde_upgrade accepts the same command-line arguments as pg_upgrade.
Example:
For more information on how to perform the upgrade for minor versions, see Minor Upgrade of Percona Distribution for PostgreSQL .
For more information on how to perform the upgrade for the pg_tde package version, see Upgrade pg_tde.
3.4.18 - Release notes
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Latest: pg_tde 2.3.0, published on November 17, 2026.
3.4.18.1 - pg_tde 2.3.0 (2026-11-17)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The 2.3.0 tag was published on November 17, 2026. The upstream documentation date variable was still TBD at this pinned revision.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
pg_tde 2.3.0 adds support for PostgreSQL 19 and makes pg_tde_waldump aware of the pg_tde custom resource manager. For more details, see the Changelog.
Known issues
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
Changes introduced in pg_tde 2.3.0:
New Features
Improvements
- PG-2754 -
pg_tde_waldumpnow recognises thepg_tdecustom resource manager, prints proper data for its records and accepts it in the--rmgrfilter
3.4.18.2 - pg_tde 2.2.2 (2026-08-20)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
pg_tde 2.2.2 focuses on fixing an issue with performance of WAL encryption and adding support for KMIP with HashiCorp Vault Enterprise. Vault Enterprise was already supported via the Vault V2 protocol, but now KMIP can be used too.
pg_tde 2.2.2 is not compatible with Percona Distribution for PostgreSQL older than 17.10.2 or 18.4.2.
Known issues
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
Changes introduced in pg_tde 2.2.2:
New Features
- PG-2125 - Support using HashiCorp Vault Enterprise with KMIP
- PG-2473 - Basic support for building on Windows with Microsoft Visual C++
Improvements
- PG-2494 - Improved performance of WAL encryption
Bug Fixes
- PG-2492 - Fixed crash when empty certificate parameters are passed to
pg_tde_add_global_key_provider_kmip()orpg_tde_add_database_key_provider_kmip() - PG-2608 - Fixed a race condition in the Vault key provider that could occur when multiple processes accessed the same cURL handle after a fork.
- PG-2609 - Fixed WAL archiving (
pg_tde_archive_decryptandpg_tde_restore_encrypt) when pg_wal dir is a symlink. - Include bugfixes for frontend tools from PostgreSQL 16.15, 17.11 and 18.5
3.4.18.3 - pg_tde 2.2.1 (2026-07-06)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
pg_tde 2.2.1 focuses on stability and compatibility improvements. This release improves pg_rewind reliability. For more details, see the Changelog.
pg_tde 2.2.1 is not compatible with Percona Distribution for PostgreSQL older than 17.10.2 or 18.4.2.
Known issues
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
Changes introduced in pg_tde 2.2.1:
New Features
- PG-2398 - PostgreSQL 16 support
Bug Fixes
- PG-2407 - Fixed multiple issues affecting
pg_rewindforpg_tdeclusters, improving reliability during rewind and recovery operations. - PG-2258 - Fixed “could not find server principal key” error from
pg_tde_basebackup
Changes
- Remove support for building
pg_tdewithmake, now it can only be built with Meson
3.4.18.4 - pg_tde 2.2.0 (2026-05-20)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
pg_tde now supports 256-bit AES encryption and introduces pg_tde_upgrade, a utility that simplifies the upgrades of encrypted clusters. For more details, see the Changelog.
pg_tde 2.2.0 is not compatible with Percona Distribution for PostgreSQL older than 17.10 or 18.4.
Documentation updates
- The Limitations of pg_tde topic is updated to include a new section on known incompatibilities with Citus and TimescaleDB, and a clarification of the
ALTER DATABASE ... SET TABLESPACEbehavior, the command can be used but with restrictions whenpg_tdeis active. - The Backup with WAL encryption enabled topic is updated with a clearer description of the key rotation limitation during backups.
Known issues
pg_rewindandpg_tde_rewindUsing
pg_rewindorpg_tde_rewindbetween diverged nodes in clusters that usepg_tdemay lead to corrupted tables or indexes due to internal encryption key differences between clusters.Queries may fail with:
This behavior is a known issue.
For more information, see pg_tde limitations.
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
Changes introduced in pg_tde 2.2.0:
New Features
- PG-1968 - AES-256 encryption support,
pg_tdenow supports 256-bit AES encryption, providing stronger cryptographic protection for encrypted tablespaces. - PG-2017 - AES-256 compatibility for
pg_tde_resetwal, thepg_tde_resetwalutility has been updated to work correctly with AES-256 encrypted data. - PG-2018 - AES-256 compatibility for
pg_tde_basebackup, thepg_tde_basebackuputility now fully supports AES-256 encryption, ensuring consistent backup and restore behavior for databases using the new cipher. - PG-2240 - Introducing
pg_tde_upgrade, a utility that automates the steps required to upgrade apg_tde-enabled cluster, making the upgrade process more convenient.
Improvements
- PG-2278 - Storage manager (SMGR) encryption has been optimized to reuse OpenSSL cipher contexts, reducing overhead and improving throughput for encrypted I/O operations.
Bug Fixes
- PG-2240 - Fixed an issue where
pg_upgradewould fail when run against databases containing encrypted data. - PG-1895 - Resolved a bug where performing WAL key rotation or SMGR key rotation during a
pg_basebackupoperation could prevent the secondary server from starting successfully. - PG-2125 - Fixed key creation failures that occurred when
pg_tdewas configured to use HashiCorp Vault via the KMIP protocol.
3.4.18.5 - pg_tde 2.1.2 (2026-03-02)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
Documentation updates
- The Architecture documentation is redesigned for improved clarity and readability. The chapter is now split into smaller, more focused sections.
- The Technical reference overview is updated with quick-skim cards for quick topic access.
- A dedicated Usage reference topic is introduced which describes the main
pg_tdeoperations available.
Known issues
pg_rewindandpg_tde_rewindUsing
pg_rewindorpg_tde_rewindbetween diverged nodes in clusters that usepg_tdemay lead to corrupted tables or indexes due to internal encryption key differences between clusters.Queries may fail with:
This behavior is a known issue.
For more information, see pg_tde limitations.
pg_upgradeis currently unsupported whenpg_tdeis enabledPostgreSQL clusters that use
pg_tdecannot currently be upgraded usingpg_upgrade.Do not create, change, or rotate global key providers (or their keys) while
pg_tde_basebackupis running. Doing so may cause standbys or clusters initialized from the backup to fail during WAL replay and may result in corruption of encrypted data (tables, indexes, and other relations).Using
pg_tde_basebackupwith--wal-method=fetchproduces warnings.This behavior is expected and will be addressed in a future release.
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice bigger than the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
Improvements
- PG-2088 , PG-2179 - Improved handling of Vault/OpenBao KV v2 mount point validation in
pg_tde. The extension no longer fails when configured with tokens that lack access to mount metadata endpoints and now works correctly with tokens that have only the required KV v2 read/write permissions.
Bugs Fixed
- Updated
pg_tdeCLI tools to include upstream bug fixes and stability improvements from PostgreSQL 18.2 and 17.8.
3.4.18.6 - pg_tde 2.1.1 (2026-01-22)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde extension, provided by Percona, adds Transparent Data Encryption (TDE) to PostgreSQL and helps protect sensitive data at rest.
Release Highlights
Integrated Hashicorp Vault namespace
The namespace of Hashicorp vault is integrated with pg_tde through the pg_tde_add_global_key_provider_vault_v2 parameter.
Documentation updates
Updated the Global Principal Key configuration and Configure WAL encryption chapters with updated installation steps and removed outdated KMS configuration information.
Known issues
Creating, changing, or rotating global key providers (or their keys) while
pg_tde_basebackupis running may cause standbys or standalone clusters initialized from the backup to fail during WAL replay and may also lead to the corruption of encrypted data (tables, indexes, and other relations).Avoid making these actions during backup windows. Run a new full backup after completing a rotation or provider update.
Using
pg_tde_basebackupwith--wal-method=fetchproduces warnings.This behavior is expected and will be addressed in a future release.
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice bigger than the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
New Features
- PG-1959 - Namespace of Hashicorp vault is integrated with
pg_tde
3.4.18.7 - pg_tde 2.1.0 (2025-11-28)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde by Percona extension brings Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
Release Highlights
Added support for PostgreSQL 18.1
pg_tde is fully supported with the Postgres 18.1 version.
Packaging changes for PostgreSQL 18
Starting with PostgreSQL 18, pg_tde is distributed as a standalone package for RPM and DEB installations.
It is no longer bundled with the main PostgreSQL server package.
If your PostgreSQL 18 deployment uses pg_tde, make sure to install the matching pg_tde package separately.
Percona’s PostgreSQL Docker images continue to include pg_tde by default, so no additional action is required for container-based deployments.
For more information on the availability by PostgreSQL version, please see Install pg_tde.
Added support for AIO
Added support for asynchronous I/O (AIO) which is now the default I/O mechanism.
Added namespace support for Vault Enterprise and OpenBao
Added support for HashiCorp Vault and OpenBao namespaces. The namespace parameter is now documented in Add or modify Vault providers and fully supported.
Repository split for multi-version PostgreSQL support
Reorganized the project into a multi-repository structure to support several PostgreSQL versions more efficiently.
Tooling changes
The standard PostgreSQL command-line utilities can no longer operate on clusters encrypted with pg_tde. To manage encrypted data safely, use the pg_tde_ equivalents provided by Percona:
- pg_basebackup to pg_tde_basebackup
- pg_checksums to pg_tde_checksums
- pg_resetwal to pg_tde_resetwal
- pg_rewind to pg_tde_rewind
- pg_waldump to pg_tde_waldump
The non-pg_tde_* versions will not work on encrypted clusters and may fail with errors if used. Always use the pg_tde_ variants when working with TDE-enabled data.
Added Akeyless support
pg_tde is now compatible with the Akeyless CipherTrust Manager via the KMIP protocol. For more information, see the Key management overview topic.
Added support for Vault and OpenBao namespaces
Implemented support for the “namespace” feature in Vault Enterprise and OpenBao, available both on the CLI and on the HTTP interface using the X-Vault-Namespace header.
Documentation updates
- Added the Akeyless topic
- Added the Impact of pg_tde on database operations topic which summarizes how
pg_tdeinteracts with core PostgreSQL operations - Updated the FAQ with an answer to logical replication keeping data encrypted on subscribers
- Updated Install pg_tde with a table for the
pg_tdeavailability by PostgreSQL version - Updated Add or modify Vault providers to include the
namespaceparameter.
Known issues
Creating, changing, or rotating global key providers (or their keys) while
pg_tde_basebackupis running may cause standbys or standalone clusters initialized from the backup to fail during WAL replay and may also lead to the corruption of encrypted data (tables, indexes, and other relations).Avoid making these actions during backup windows. Run a new full backup after completing a rotation or provider update.
Using
pg_tde_basebackupwith--wal-method=fetchproduces warnings.This behavior is expected and will be addressed in a future release.
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice bigger than the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
3.4.18.8 - pg_tde 2.0.0 (2025-09-01)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde by Percona extension brings Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
Release Highlights
WAL encryption is now generally available
The WAL (Write-Ahead Logging) encryption feature is now fully supported and production-ready, it adds secure write-ahead logging to pg_tde, expanding Percona’s PostgreSQL encryption coverage by enabling secure, transparent encryption of write-ahead logs using the same key infrastructure as data encryption.
WAL encryption upgrade limitation
Clusters that used WAL encryption in the beta release (pg_tde 1.0 or older) cannot be upgraded to pg_tde 2.0. The following error indicates that WAL encryption was enabled:
Clusters that did not use WAL encryption in beta can be upgraded normally.
Documentation updates
- Updated the Limitations topic, it now includes WAL encryption limitations and both supported and unsupported WAL tools
- PG-1858 - Added a new topic for Backup with WAL encryption enabled that includes restoring a backup created with WAL encryption
- PG-1832 - Added documentation for using the
pg_tde_archive_decryptandpg_tde_restore_encryptutilities. These tools are now covered in CLI Tools to guide users on how to archive and restore encrypted WAL segments securely - PG-1740 - Updated documentation for uninstalling
pg_tdewith WAL encryption enabled and improved the uninstall instructions to cover cases where TDE is disabled while WAL encryption remains active
Known issues
Creating, changing, or rotating global key providers (or their keys) while
pg_basebackupis running may cause standbys or standalone clusters initialized from the backup to fail during WAL replay and may also lead to the corruption of encrypted data (tables, indexes, and other relations).Avoid making these actions during backup windows. Run a new full backup after completing a rotation or provider update.
Using
pg_basebackupwith--wal-method=fetchproduces warnings.This behavior is expected and will be addressed in a future release.
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice bigger than the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
Changelog
New Features
- PG-1497 WAL encryption is now generally available (GA)
- PG-1037 - Added support for
pg_rewindwith encrypted WAL - PG-1411 - Added support for
pg_resetwalwith encrypted WAL - PG-1603 - Added support for
pg_basebackupwith encrypted WAL - PG-1710 - Added support for WAL archiving with encrypted WAL
- PG-1711 - Added support for incremental backups with encrypted WAL, compatibility has been verified with
pg_combinebackupand the WAL summarizer tool. - PG-1712 - Added support for
pg_createsubscriberwith encrypted WAL - PG-1833 - Added verified support for using
pg_waldumpwith encrypted WAL - PG-1834 - Verified
pg_upgradewith encryption
Improvements
- PG-1661 - Added validation for key material received from providers
- PG-1667 - Validated Vault keyring engine type
Bugs Fixed
- PG-1391 - Fixed unencrypted checkpoint segment on replica with encrypted key
- PG-1412 – Fixed an issue where
XLogFileCopyfailed with encrypted WAL during PITR andpg_rewind - PG-1452 - Fixed an issue where
pg_tde_change_key_providerdid not work without the-Dflag even ifPGDATAwas set - PG-1485 - Fixed an issue where streaming replication failed with an invalid magic number in WAL when
wal_encryptionwas enabled - PG-1604 - Fixed a crash during standby promotion caused by an invalid magic number when replaying two-phase transactions from WAL
- PG-1658 - Fixed an issue where the global key provider could not be deleted after server restart
- PG-1835 - Fixed an issue where
pg_resetwalcorrupted encrypted WAL, causing PostgreSQL to fail at startup with an invalid checkpoint - PG-1842 - Fixed a delay in replica startup with encrypted tables in streaming replication setups
- PG-1843 - Fixed performance issues when creating encrypted tables
- PG-1863 - Fixed an issue where unnecessary WAL was generated when creating temporary tables
- PG-1866 - Fixed an issue where automatic restart after crash sometimes failed with WAL encryption enabled
- PG-1867 - Fixed archive recovery with encrypted WAL
3.4.18.9 - pg_tde 1.0.0 (2025-06-30)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The pg_tde by Percona extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
Release Highlights
pg_tde1.0 is now GA (Generally Available)
And stable for encrypting relational data in PostgreSQL using Transparent Data Encryption (TDE) . This milestone brings production-level data protection to PostgreSQL workloads.
- WAL encryption is still in Beta
The WAL encryption feature is currently still in beta and is not effective unless explicitly enabled. It is not yet production ready. Do not enable this feature in production environments.
Upgrade considerations
pg_tde 1.0 is not backward compatible with previous pg_tde versions, like Release Candidate 2, due to significant changes in code. This means you cannot directly upgrade from one version to another. You must do a clean installation of pg_tde.
Known issues
- The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.
To prevent this, you can change the mlock limit to be at least twice bigger than the memory page size:
- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
Changelog
New Features
- PG-1257 – Added SQL function to remove the current principal key
Improvements
- PG-1617 – Removed relation key cache
- PG-1635 – User-facing TDE functions now return void
- PG-1605 – Removed undeclared dependencies for
pg_tde_grant_database_key_management_to_role()
Bugs Fixed
- PG-1581 – Fixed PostgreSQL crashes on table access when KMIP key is unavailable after restart
- PG-1583 – Fixed a crash when dropping the
pg_tdeextension with CASCADE after changing the key provider file - PG-1585 – Fixed the vault provider re-addition that failed after server restart with a new token
- PG-1592 – Improve error logs when Server Key Info is requested without being created
- PG-1593 – Fixed runtime failures when invalid Vault tokens are allowed during key provider creation
- PG-1600 – Fixed Postmaster error when dropping a table with an unavailable key provider
- PG-1606 – Fixed missing superuser check in role grant function leads to misleading errors
- PG-1607 – Improved CA parameter order and surrounding documentation for clearer interpretation
- PG-1608 – Updated and fixed global key configuration parameters in documentation
- PG-1613 – Tested and improved the
pg_tde_change_key_providerCLI utility - PG-1637 – Fixed unused keys in key files which caused issues after OID wraparound
- PG-1651 – Fixed the CLI tool when working with Vault key export/import
- PG-1652 – Fixed when the server fails to find encryption keys after CLI-based provider change
- PG-1662 – Fixed the creation of inconsistent encryption status when altering partitioned tables
- PG-1663 – Fixed the indexes on partitioned tables which were not encrypted
- PG-1700 – Fixed the error hint when the principal key is missing
3.4.18.10 - pg_tde Release Candidate 2 (2025-05-29)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
pg_tde extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
Release Highlights
This release provides the following features and improvements:
Restricted key provider configuration to superusers
The database owners can no longer configure key providers directly. Instead, they must refer to the superuser who manages the provider setup. This security improvement clearly separates the responsibilities between users and administrators.
WAL encryption supports Vault.
pg_tdenow supports using the Vault keyring for secure storage and management of WAL encryption keys.Automatic WAL internal key generation at server startup.
On each server start, a new internal key is generated for encrypting subsequent WAL records (assuming WAL encryption is enabled). The existing WAL records and their keys remain unchanged, this ensures continuity and secure key management without affecting historical data.
Proper removal of relation-level encryption keys on table drop
Previously, encrypted relation keys persisted even after dropping the associated tables, potentially leaving orphaned entries in the map file. This is now corrected, when an encrypted table is dropped, its corresponding key is also removed from the key map.
Fixed external tablespace data loss with encrypted partitions
An issue was fixed where data could be lost when the encrypted partitioned tables were moved to external tablespaces.
New visibility and verification functions for default principal keys
Added additional functions to help you verify and inspect the state of default principal keys more easily.
Fixed SQL failures caused by inconsistent key provider switching
An issue was resolved where SQL queries could fail after switching key providers while the server was running. This occurred because principal keys became inaccessible when spread across multiple keyring backends, triggering the single-provider-at-a-time design constraint.
pg_tdenow enforces consistency during provider changes to prevent a corrupted key state and query errors.
Upgrade considerations
pg_tde Release Candidate 2 is not backward compatible with pg_tde Beta2 due to significant changes in code. This means you cannot directly upgrade from one version to another. You must uninstall pg_tde Beta2 first and then install and configure the new Release Candidate version.
Known issues
- The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.
To prevent this, you can change the mlock limit to be at least twice bigger than the memory page size:
- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
Changelog
New Features
- PG-817 – Added fuzz testing to
pstressto strengthen validation and resilience. - PG-824 – Ensured fsync is called on
pg_tde.map,pg_tde.dat, and FS key provider files. - PG-830 – Implemented full WAL encryption using Vault keyring.
- PG-831 – Tested WAL recovery and both streaming and logical replication compatibility.
- PG-855 – Added a contributor guide to help new developers engage with pg_tde.
- PG-938 – Evaluated use of
pg_basebackupfor automated backup validation with pg_tde. - PG-962 – Automated test cases to validate data integrity after PostgreSQL restart.
- PG-1001 – Verified encryption behavior of temporary tables.
- PG-1099 – Developed automation for bare-metal performance benchmarking.
- PG-1289 – Added test cases for verifying compatibility with different PostgreSQL versions.
- PG-1444 – Implemented support for removing relation-level encryption keys when dropping tables.
- PG-1455 – Introduced random base numbers in encryption IVs for enhanced security.
- PG-1458 – Added visibility and verification functions for default principal keys.
- PG-1460 – Enabled automatic rotation of WAL internal keys on server start.
- PG-1461 – Implemented random IV initialization for WAL keys.
- PG-1506 – Added parameter support for client certificates in KMIP provider configuration.
Improvements
- PG-826 – Documented how to encrypt and decrypt existing tables using pg_tde.
- PG-827 – Fixed CI pipeline tests on the smgr branch.
- PG-834 – Resolved issues with
CREATE ... USING pg_tdeon the smgr branch. - PG-1427 – Tested and fixed KMIP implementation for Thales support.
- PG-1507 – Handled ALTER TYPE operations in the TDE event trigger.
- PG-1508 – Fixed encryption state inconsistencies when altering inherited tables.
- PG-1550 – Restricted database owners from creating key providers to improve security.
- PG-1586 – Verified and fixed KMIP compatibility with Fortanix HSM.
Bugs Fixed
- PG-1397 – Fixed segmentation fault during replication with WAL encryption enabled.
- PG-1413 – Resolved invalid WAL magic number errors after toggling encryption.
- PG-1416 – Fixed SQL query failures caused by inconsistent key provider switching.
- PG-1468 – Fixed WAL read failures on replicas after key rotation.
- PG-1491 – Corrected
pg_tde_is_encrypted()behavior for partitioned tables. - PG-1493 – Fixed data loss when encrypted partitioned tables were moved to external tablespaces.
- PG-1503 – Blocked deletion of global key providers still associated with principal keys.
- PG-1504 – Ensured correct encryption inheritance in partitioned
tde_heaptables. - PG-1510 – Used different keys and IVs for PostgreSQL forks to prevent conflicts.
- PG-1530 – Fixed inability to read WAL after toggling WAL encryption.
- PG-1532 – Resolved errors rewriting owned sequences when pg_tde isn’t in the default schema.
- PG-1535 – Prevented server crash on calling
pg_tde_principal_key_info(). - PG-1537 – Fixed crash on NULL input in user-facing functions.
- PG-1539 – Handled principal key header verification errors gracefully.
- PG-1540 – Ensured sequences are assigned correct encryption status.
- PG-1541 – Resolved WAL decryption failure after key rotation.
- PG-1543 – Fixed validation error when multiple server keys exist.
- PG-1545 – Resolved error from
pg_tde_grant_grant_management_to_role()execution. - PG-1546 – Fixed incorrect behavior in role grant function.
- PG-1551 – Improved handling of short reads and errors in WAL storage code.
- PG-1571 – Fixed WAL decryption failure due to corrupted or mismatched principal keys.
- PG-1573 – Prevented crash during WAL replay when lock was not held.
- PG-1574 – Ensured encrypted WAL is readable by streaming replica.
- PG-1576 – Resolved crash from malformed JSON in user-facing functions.
3.4.18.11 - pg_tde Release Candidate 1 (2025-03-27)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
pg_tde extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
Release Highlights
This release provides the following features and improvements:
Improved performance with redesigned WAL encryption.
The approach to WAL encryption has been redesigned. Now,
pg_tdeencrypts entire WAL files starting from the first WAL write after the server was started with the encryption turned on. The information about what is encrypted is stored in the internal key metadata. This change improves WAL encryption flow with native replication and increases performance for large scale databases.Default encryption key for single-tenancy.
The new functionality allows you to set a default principal key for the entire database cluster. This key is used to encrypt all databases and tables that do not have a custom principal key set. This feature simplifies encryption configuration and management in single-tenant environments where each user has their own database instance.
Ability to change key provider configuration
You no longer need to configure a new key provider and set a new principal key if the provider’s configuration changed. Now can change the key provider configuration both for the current database and the entire PostgreSQL cluster using functions. This enhancement lifts existing limitations and is a native and common way to operate in PostgreSQL.
Key management permissions
The new functions allow you to manage permissions for global and database key management separately. This feature provides more granular control over key management operations and allows you to delegate key management tasks to different roles.
Additional information about principal keys and providers
The new functions allow you to display additional information about principal keys and providers. This feature helps you to understand the current key configuration and troubleshoot issues related to key management.
tde_heap_basicaccess method deprecationThe
tde_heap_basicaccess method has limitations in encryption capabilities and affects performance. Also, it poses a potential security risk when used in production environments due to indexes remaining unencrypted. Considering all the above, we decided to deprecate this access method and remove it in future releases. Use thetde_heapaccess method instead that is available with Percona Server for PostgreSQL 17 - a drop-in replacement for PostgreSQL Community.
Upgrade considerations
pg_tde Release Candidate is not backward compatible with pg_tde Beta2 due to significant changes in code. This means you cannot directly upgrade from one version to another. You must uninstall pg_tde Beta2 first and then install and configure the new Release Candidate version.
Known issues
The default
mlocklimit on Rocky Linux 8 for ARM64-based architectures equals the memory page size and is 64 Kb. This results in the child process withpg_tdefailing to allocate another memory page because the max memory limit is reached by the parent process.To prevent this, you can change the
mlocklimit to be at least twice bigger than the memory page size:- temporarily for the current session using the
ulimit -l <value>command. - set a new hard limit in the
/etc/security/limits.conffile. To do so, you require the superuser privileges.
Adjust the limits with caution since it affects other processes running in your system.
- temporarily for the current session using the
You can now delete global key providers even when their associated principal key is still in use. This known issue will be fixed in the next release. For now, avoid deleting global key providers.
Changelog
New Features
PG-1234 - Added functions for separate global and database key management permissions.
PG-1255 - Added functionality to delete key providers.
PG-1256 - Added single-tenant support via the default principal key functionality.
PG-1258 - Added functions to display additional information about principal keys / providers.
PG-1294 - Redesigned WAL encryption.
PG-1303 - Deprecated tde_heap_basic access method.
Improvements
PG-858 - Refactored internal/principal key LWLocks to make local databases inherit a global key provider.
PG-1243 - Investigated performance issues at a specific threshold and large databases and updated documentation about handling hint bits.
PG-1310 - Added access method enforcement via the GUC variable.
PG-1361 - Fixed pg_tde relocatability.
PG-1380 - Added support for
pg_tde_is_encrypted()function on indexes and sequences.
Bugs Fixed
PG-821 - Fixed the issue with
pg_basebackupfailing when configuring replication.PG-847 - Fixed the issue with
pg_basebackupandpg_checksumthrowing an error on files created bypg_tdewhen the checksum is enabled on the database cluster.PG-1004 - Fixed the issue with
pg_checksumsutility failing during checksum verification onpg_tdetables. Nowpg_checksumskips encrypted relations by looking if the relation has a custom storage manager (SMGR) key.PG-1373 - Fixed the issue with potential unterminated strings by using the
memcpy()orstrlcpy()instead of thestrncpy()function.PG-1378 - Fixed the issue with toast tables created by the
ALTER TABLEcommand not being encrypted.PG-1379 - Fixed sequence and alter table handling in the event trigger.
PG-1222 - Fixed the bug with confused relations with the same
RelFileNumberin different databases.PG-1400 - Corrected the pg_tde_change_key_provider naming in help.
PG-1401 - Fixed the issue with inheriting an encryption status during the ALTER TABLE SET access method command execution by basing a new encryption status only on the new encryption setting.
PG-1414 - Fixed the error message wording when configuring WAL encryption by referencing to a correct function.
PG-1450 - Fixed the
pg_tde_delete_key_provider()function behavior when called multiple times by ignoring already deleted records.PG-1451 -Fixed the issue with the repeating error message about inability to retrieve a principal key even when a user creates non-encrypted tables by checking the current transaction ID in both the event trigger start function and during a file creation. If the transaction changed during the setup of the current event trigger data, the event trigger is reset.
PG-1473 - Allowed only users with key viewer privileges to execute
pg_tde_verify_principal_key()andpg_tde_verify_global_principal_key()functions.PG-1474 - Fixed the issue with the principal key reference corruption when reassigning it to a key provider with the same name by setting the key name in vault/kmip getters.
[PG-1476](https://perconadev.atlassian.net
3.4.18.12 - pg_tde Beta 2 (2024-12-16)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
pg_tde extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
This version of Percona Transparent Data Encryption extension is not recommended for production environments yet. We encourage you to test it and give your feedback.
This will help us improve the product and make it production-ready faster.
Release Highlights
With this release, pg_tde extension offers two database specific versions:
- PostgreSQL Community version provides only the
tde_heap_basicaccess method using which you can introduce table encryption and WAL encryption for data in the encrypted tables. Index data remains unencrypted. - Version for Percona Server for PostgreSQL provides the
tde_heapaccess method. using this method you can encrypt index data in encrypted tables thus increasing the safety of your sensitive data. For backward compatibility, thetde_heap_basicmethod is available in this version too.
Changelog
The Beta 2 version introduces the following features and improvements:
New Features
- Added the
tde_heapaccess method with which you can now enable index encryption for encrypted tables and global WAL data encryption. To use this access method, you must install Percona Server for PostgreSQL. Check the installation guide - Added event triggers to identify index creation operations on encrypted tables and store those in a custom storage.
- Added support for secure transfer of keys using the OASIS Key Management Interoperability Protocol (KMIP). The KMIP implementation was tested with the PyKMIP server and the HashiCorp Vault Enterprise KMIP Secrets Engine.
Improvements
WAL encryption improvements:
- Added a global key to encrypt WAL data in global space
- Added WAL key management
Keyring improvements:
- Renamed functions to point their usage for principal key management
- Improved keyring provider management across databases and the global space.
- Keyring configuration now uses common JSON API. This simplifies code handling and enables frontend tools like
pg_waldumpto read the code thus improving debugging.
The
pg_tde_is_encryptedfunction now supports custom schemas in the format ofpg_tde_is_encrypted('schema.table');Changed the location of internal TDE files: instead of the database directory, now all files are stored in
$PGDATA/pg_tdeImproved error reporting when
pg_tdeis not added to theshared_preload_librariesImproved memory usage of
tde_heap_basicduring sequential readsImproved
tde_heap_basicfor select statementsAdded encryption support for (some) command line utilities
Bugs fixed
- Fixed multiple bugs with
tde_heap_basicand TOAST records - Fixed various memory leaks
3.4.18.13 - pg_tde Beta (2024-06-30)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
pg_tde extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
This version of Percona Transparent Data Encryption extension is not recommended for production environments yet. We encourage you to test it and give your feedback.
This will help us improve the product and make it production-ready faster.
Release Highlights
Starting with pg_tde Beta, the access method for pg_tde extension is renamed tde_heap_basic. Use this access method name to create tables. Find guidelines in Test TDE tutorial.
Changelog
Fixed the issue with
pg_tderunning out of memory used for decrypted tuples. The fix introduces the new componentTDEBufferHeapTupleTableSlotthat keeps track of the allocated memory for decrypted tuples and frees this memory when the tuple slot is no longer needed.Fixed the issue with adjusting a current position in a file by using raw file descriptor for the
lseekfunction. (Thanks to user rainhard for providing the fix)Enhanced the init script to consider a custom superuser for the POSTGRES_USER parameter when
pg_tdeis running via Docker (Thanks to Alejandro Paredero for reporting the issue)
3.4.18.14 - pg_tde Alpha 1 (2024-03-28)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
pg_tde extension brings in Transparent Data Encryption (TDE) to PostgreSQL and enables you to keep sensitive data safe and secure.
This version of Percona Transparent Data Encryption extension is not recommended for production environments yet. We encourage you to test it and give your feedback.
This will help us improve the product and make it production-ready faster.
Release Highlights
The Alpha1 version of the extension introduces the following key features:
You can now rotate principal keys used for data encryption. This reduces the risk of long-term exposure to potential attacks and helps you comply with security standards such as GDPR, HIPAA, and PCI DSS.
You can now configure encryption differently for each database. For example, encrypt specific tables in some databases with different encryption keys while keeping others non-encrypted.
Keyring configuration has undergone several improvements, namely:
- You can define separate keyring configuration for each database
- You can change keyring configuration dynamically, without having to restart the server
- The keyring configuration is now stored in a catalog separately for each database, instead of a configuration file
- Avoid storing secrets in the unencrypted catalog by configuring keyring parameters to be read from external sources (file, http(s) request)
Improvements
- Renamed the repository and Docker image from
postgres-tde-exttopg_tde. The extension name remains unchanged - Changed the Initialization Vector (IV) calculation of both the data and internal keys
Bugs fixed
- Fixed toast related crashes
- Fixed a crash with the DELETE statement
- Fixed performance-related issues
- Fixed a bug where
pg_tdesent many 404 requests to the Vault server - Fixed сompatibility issues with old OpenSSL versions
- Fixed сompatibility with old Curl versions
3.4.18.15 - pg_tde MVP (2023-12-12)
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
The Minimum Viable Product (MVP) version of pg_tde introduces the following functionality:
- Encryption of heap tables, including TOAST
- Encryption keys are stored either in Hashicorp Vault server or in local keyring file (for development)
- The key storage is configurable via separate JSON configuration files
- Replication support
3.4.18.16 - Percona Transparent Data Encryption for PostgreSQL release notes index
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This page describes this release at publication time. For current deployment requirements, read the supported versions and limitations.
This page lists all release notes for pg_tde, organized by year and version. Use it to track new features, fixes, and updates across major and minor versions.
2026
- 2.3.0 (2026-11-17; upstream date variable pending)
- 2.2.2 (2026-08-20)
- 2.2.1 (2026-07-06)
- 2.2.0 (2026-05-20)
- 2.1.2 (2026-03-02)
- 2.1.1 (2026-01-22)
2025
- 2.1.0 (2025-11-28)
- 2.0.0 (2025-09-01)
- 1.0.0 (2025-06-30)
- Release Candidate 2 (RC2) (2025-05-29)
- Release Candidate 1 (RC1) (2025-03-27)
2024
2023
- MVP (2023-12-12)
3.4.19 - FAQ
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
The temporary-file scope and internal-key rotation guidance have been clarified using the current limitations and architecture documentation. Compliance-related statements below reflect the upstream document, not a certification of a particular deployment. See site errata.
Why do I need TDE?
Using TDE provides the following benefits:
- Compliance to security and legal regulations like General Data Protection Regulation (GDPR), Payment Card Industry Data Security Standard (PCI DSS), California Consumer Privacy Act (CCPA), Data Protection Act 2018 (DPA 2018) and others
- Encryption of backups. Even when an authorized person gets physical access to a backup, encryption ensures that the data remains unreadable and secure.
- Granular encryption of specific data sets and reducing the performance overhead that encryption brings.
- Additional layer of security to existing security measures
When and how should I use TDE?
If you are dealing with Personally Identifiable Information (PII), data encryption is crucial. Especially if you are involved in areas with strict regulations like:
- financial services where TDE helps to comply with PCI DSS
- healthcare and insurance - compliance with HIPAA, HITECH, CCPA
- telecommunications, government and education to ensure data confidentiality.
Using TDE helps you avoid the following risks:
- Data breaches
- Identity theft that may lead to financial fraud and other crimes
- Reputation damage leading to loss of customer trust and business
- Legal consequences and financial losses for non-compliance with data protection regulations
- Internal threats by misusing unencrypted sensitive data
For pg_tde, the encrypted scope includes tables using tde_heap and WAL when WAL encryption is enabled. Temporary tables can use tde_heap, but temporary files from operations that exceed work_mem are not encrypted. See the current limitations.
pg_tde does not encrypt system catalogs yet. This means that statistics data and database metadata are not encrypted.
Will logical replication work with pg_tde?
Yes, logical replication works with the encrypted tables.
Does logical replication keep data encrypted on subscribers?
Logical replication does not preserve encryption state. If the publisher uses pg_tde but the subscriber does not, the replicated data will be stored in plain text on the subscriber.
Encryption is not propagated to the data-block level due to how logical replication operates.
This means encrypted publishers do not guarantee encrypted logical replicas.
I use disk-level encryption. Why should I care about TDE?
Encrypting a hard drive encrypts all data, including system, application, and temporary files.
Full disk encryption protects your data from people who have physical access to your device and even if it is lost or stolen. However, it doesn’t protect the data after system boot-up: the data is automatically decrypted when the system runs or when an authorized user requests it.
Another point to consider is PCI DSS compliance for Personal Account Numbers (PAN) encryption.
PCI DSS 3.4.1 standards might consider disk encryption sufficient for compliance if you meet these requirements:
Separate the logical data access from the operating system authentication.
Ensure the decryption key is not linked to user accounts.
Note that PCI DSS 3.4.1 is retiring on March 31, 2025. Therefore, consider switching to PCI DSS 4.0.
PCI DSS 4.0 standards consider using only disk and partition-level encryption not enough to ensure PAN protection. It requires an additional layer of security that
pg_tdecan provide.
pg_tde focuses specifically on data files and offers more granular control over encrypted data. The data remains encrypted on disk during runtime and when you move it to another directory, another system or storage. An example of such data is backups. They remain encrypted when moved to the backup storage.
Thus, to protect your sensitive data, consider using TDE to encrypt it at the table level. Then use disk-level encryption to encrypt a specific volume where this data is stored, or the entire disk.
Is TDE enough to ensure data security?
No. Transparent Data Encryption (TDE) adds an extra layer of security for data at rest. You should also consider implementing the following additional security features:
- Access control and authentication
- Strong network security like TLS
- Disk encryption
- Regular monitoring and auditing
- Additional data protection for sensitive fields (e.g., application-layer encryption)
How does pg_tde make my data safe?
pg_tde uses two keys to encrypt data:
- Internal encryption keys to encrypt the data. These keys are stored internally in an encrypted format, in a single
$PGDATA/pg_tdedirectory. - Principal keys to encrypt internal encryption keys. These keys are stored externally, in the Key Management System (KMS).
You can use the following KMSs:
- HashiCorp Vault.
pg_tdesupports the KV secrets engine v2 of Vault, for more information see Vault Configuration. - OpenBao implementation of Vault
- KMIP-compatible servers, KMIP is a standardized protocol for handling cryptographic workloads and secrets management, for more information see KMIP configuration.
HashiCorp Vault can also act as a KMIP server, managing cryptographic keys for clients that use the KMIP protocol. (KMIP functionality is available in Vault’s enterprise edition.)
Let’s break the encryption down into two parts:
Encryption of data files
First, data files are encrypted with internal keys. Each file that has a different Object Identifier (OID) has an internal key. For example, a table with 4 indexes will have 5 internal keys - one for the table and one for each index.
The initial decision on what file to encrypt is based on the table access method in PostgreSQL. When you run a CREATE or ALTER TABLE statement with the USING tde_heap clause, the newly created data files are marked as encrypted, and then file operations encrypt or decrypt the data. Later, if an initial file is re-created as a result of a TRUNCATE or VACUUM FULL command, the newly created file inherits the encryption information and is either encrypted or not.
The principal key is used to encrypt the internal keys. The principal key is stored in the key management store. When you query the table, the principal key is retrieved from the key store to decrypt the table. Then the internal key for that table is used to decrypt the data.
WAL encryption
WAL encryption is done globally for the entire database cluster. All modifications to any database within a PostgreSQL cluster are written to the same WAL to maintain data consistency and integrity and ensure that PostgreSQL cluster can be restored to a consistent state. Therefore, WAL is encrypted globally.
When you turn on WAL encryption, pg_tde encrypts entire WAL files starting from the first WAL write after the server was started with the encryption turned on.
The same 2-key approach is used with WAL as with the table data: WAL pages are first encrypted with the internal key. Then the internal key is encrypted with the global principal key.
You can turn WAL encryption on and off so WAL can contain both encrypted and unencrypted data. The WAL encryption GUC variable influences only writes.
Whenever the WAL is being read (by the recovery process or tools), the decision on what should be decrypted is based solely on the metadata of WAL encryption keys.
Should I encrypt all my data?
It depends on your business requirements and the sensitivity of your data. Encrypting all data is a good practice but it can have a performance impact.
Consider encrypting only tables that store sensitive data. You can decide what tables to encrypt and with what key. The Set up multi-tenancy section in the documentation focuses on this approach.
We advise encrypting the whole database only if all your data is sensitive, like PII, or if there is no other way to comply with data safety requirements.
What cipher mechanisms are used by pg_tde?
pg_tde currently uses the following encryption algorithms:
AES-128-CBC,AES-256-CBCfor encrypting database files; encrypted with internal keysAES-128-CTR,AES-256-CTRfor WAL encryption; encrypted with internal keysAES-128-GCM,AES-256-GCMfor encrypting internal keys; encrypted with the principal key
Is post-quantum encryption supported?
No, it’s not yet supported. In our implementation we reply on OpenSSL libraries that don’t yet support post-quantum encryption.
Can I encrypt an existing table?
Yes, you can encrypt an existing table. Run the ALTER TABLE command as follows:
Since the SET ACCESS METHOD command drops hint bits and this may affect the performance, we recommend to run the SELECT count(*) command. It checks every tuple for visibility and sets its hint bits. Read more in the Changing existing table section.
Do I have to restart the database to encrypt the data?
You must restart the database in the following cases to apply the changes:
- after you enabled the
pg_tdeextension - when enabling WAL encryption
After that, no database restart is required. When you create or alter the table using the tde_heap access method, the files are marked as those that require encryption. The encryption happens at the storage manager level, before a transaction is written to disk. Read more about how tde_heap works.
What happens to my data if I lose a principal key?
If you lose encryption keys, especially, the principal key, the data is lost. That’s why it’s critical to back up your encryption keys securely and use the Key Management service for key management.
Can I use pg_tde in a multi-tenant setup?
Multi-tenancy is the type of architecture where multiple users, or tenants, share the same resource. It can be a database, a schema or an entire cluster.
In pg_tde, multi-tenancy is supported via a separate principal key per database. This means that a database owner can decide what tables to encrypt within a database. The same database can have both encrypted and non-encrypted tables.
To control user access to the databases, you can use role-based access control (RBAC).
Are my backups safe? Can I restore from them?
pg_tde encrypts data at rest. This means that data is stored on disk in an encrypted form. During a backup, already encrypted data files are copied from disk onto the storage. This ensures the data safety in backups.
Since the encryption happens on the database level, it makes no difference for your tools and applications. They work with the data in the same way.
To restore from an encrypted backup, you must have the same principal encryption key, which was used to encrypt files in your backup.
I’m using OpenSSL in FIPS mode and need to use pg_tde. Does pg_tde comply with FIPS requirements? Can I use my own FIPS-mode OpenSSL library with pg_tde?
Yes. pg_tde works with the FIPS-compliant version of OpenSSL, whether it is provided by your operating system or if you use your own OpenSSL libraries. If you use your own libraries, make sure they are FIPS certified.
How do I rotate internal encryption keys in pg_tde?
We don’t have a dedicated function to rotate internal keys, because a key is effectively rotated any time a table’s data file is completely rewritten. Operations like VACUUM FULL, TRUNCATE, or some but not all ALTER TABLE commands automatically generate a new internal key.
A table rewrite with VACUUM FULL generates a new internal key. Ordinary VACUUM does not rewrite the whole table. Plan for the exclusive lock and disk space required by VACUUM FULL.
What tools are supported with pg_tde WAL encryption?
For a comprehensive list of supported pg_tde WAL encryption tools see Limitations of pg_tde.
3.4.20 - Contributing Guide
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Welcome to pg_tde - the Transparent Data Encryption extension for PostgreSQL!
We’re glad that you would like to become a community member and contribute to this project.
You can contribute in one of the following ways:
- Reach us on our Forums.
- Submit a bug report or a feature request
- Submit a pull request (PR) with the code patch
- Contribute to documentation
Prerequisites
Before submitting code contributions, we ask you to complete the following prerequisites.
1. Sign the CLA
Before you can contribute, we kindly ask you to sign our Contributor License Agreement (CLA). You can do this in on click using your GitHub account.
Note: You can sign it later, when submitting your first pull request. The CLA assistant validates the PR and asks you to sign the CLA to proceed.
2. Code of Conduct
Please make sure to read and agree to our Code of Conduct.
Submitting a pull request
All bug reports, enhancements and feature requests are tracked in Jira. Though not mandatory, we encourage you to first check for a bug report among the issues and in the PR list: perhaps the bug has already been addressed.
For feature requests and enhancements, we do ask you to create a GitHub issue, describe your idea and discuss the design with us. This way we align your ideas with our vision for the product development.
If the bug hasn’t been reported / addressed, or we’ve agreed on the enhancement implementation with you, do the following:
Fork this repository
Clone this repository on your machine.
Create a separate branch for your changes. If you work on a Jira issue, please follow this pattern for a branch name:
<PG-123>-name. This makes it easier to track your contribution.Make your changes. Please follow the following guidelines to improve code readability according to the order listed:
Write the documentation for your changes. See the Write the docs cheat sheet for details.
Commit the changes. The commit message guidelines will help you with writing great commit messages
Open a pull request to Percona.
Our team will review your code and documentation. If everything is correct, will merge it. Otherwise, we will contact you for additional information or with the request to make changes.
Run local tests
When you work, you should periodically run tests to check that your changes don’t break existing code.
To run the tests, use the following command:
You can run tests on your local machine with whatever operating system you have. After you submit the pull request, we will check your patch on multiple operating systems.
Contribute to documentation
pg_tde documentation is written in Markdown language, so you can write the docs for your code changes or
edit the existing documentation online via GitHub. If you wish to have more control over the doc process, jump to how to edit documentation locally.
Before you start, learn what Markdown is and how to write it. For your convenience, there’s also a Markdown cheat sheet to help you with the syntax.
The doc files are in the documentation/docs directory.
Write the docs
When you write code, make sure to write documentation that explains it for users. As the author, you know best how your code works. To explain your feature or improvement, use the following key points:
Feature Description: What is the feature about, and why does a user need it?
User Tasks: What tasks can a user solve with this feature?
Functionality: How does the feature work?
Setup Requirements: How do you set it up? Are there any preconditions for it to work, such as existing setups or external configurations (e.g., what should be configured in a new Key Management Service - KMS)?
Setup Steps: What are the setup steps? Explain the commands and parameters used in functions. Give examples of using them. Provide sample outputs for commands.
Limitations and Breaking Changes: Are there any known limitations or breaking changes this feature introduces?
Edit documentation online via GitHub
- Click the Edit this page icon next to the page title. The source
.mdfile of the page opens in GitHub editor in your browser. If you haven’t worked with the repository before, GitHub creates a fork of it for you. - Edit the page. You can check your changes on the Preview tab.
- Commit your changes.
- In the Commit changes section, describe your changes.
- Select the Create a new branch for this commit and start a pull request option
- Click Propose changes.
- GitHub creates a branch and a commit for your changes. It loads a new page on which you can open a pull request to Percona. The page shows the base branch - the one you offer your changes for, your commit message and a diff - a visual representation of your changes against the original page. This allows you to make a last-minute review. When you are ready, click the Create pull request button.
- Someone from our team reviews the pull request and if everything is correct, merges it into the documentation. Then it gets published on the site.
Edit documentation locally
This option is for users who prefer to work from their computer and / or have the full control over the documentation process.
The steps are the following:
- Fork this repository
- Clone the repository on your machine:
- Change the directory to
contrib/pg_tdeand add the remote upstream repository:
- Pull the latest changes from upstream
- Create a separate branch for your changes
Make changes
Commit your changes. The commit message guidelines will help you with writing great commit messages
Open a pull request to Percona
Building the documentation
To verify how your changes look, generate the static site with the documentation. This process is called building. You can do it in these ways:
Use Docker
- Get Docker
- We use our Docker image to build documentation. Run the following command:
If Docker can’t find the image locally, it first downloads the image, and then runs it to build the documentation.
- Go to the
sitedirectory and open theindex.htmlfile to see the documentation.
If you want to see the changes as you edit the docs, use this command instead:
Wait until you see INFO - Start detecting changes, then enter 0.0.0.0:8000 in the browser’s address bar. The documentation automatically reloads after you save the changes in source files.
Install MkDocs and build locally
Install Python.
Install MkDocs and required extensions:
Build the site:
Open
site/index.html
Or, to run the built-in web server:
View the site at http://0.0.0.0:8000
Build PDF file
To build a PDF version of the documentation, do the following:
Disable displaying the last modification of the page:
Build the PDF file:
The PDF document is in the
site/pdffolder.
3.4.21 - Get Help from Percona
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Our documentation guides are packed with information, but they can’t cover everything you need to know about pg_tde. They also won’t cover every scenario you might come across. Don’t be afraid to try things out and ask questions when you get stuck.
Percona’s Community Forum
Be a part of a space where you can tap into a wealth of knowledge from other database enthusiasts and experts who work with Percona’s software every day. While our service is entirely free, keep in mind that response times can vary depending on the complexity of the question. You are engaging with people who genuinely love solving database challenges.
We recommend visiting our Community Forum. It’s an excellent place for discussions, technical insights, and support around Percona database software. If you’re new and feeling a bit unsure, our FAQ and Guide for New Users ease you in.
If you have thoughts, feedback, or ideas, the community team would like to hear from you at Any ideas on how to make the forum better?. We’re always excited to connect and improve everyone’s experience.
Percona experts
Percona experts bring years of experience in tackling tough database performance issues and design challenges.
We understand your challenges when managing complex database environments. That’s why we offer various services to help you simplify your operations and achieve your goals.
| Service | Description |
|---|---|
| 24/7 Expert Support | Our dedicated team of database experts is available 24/7 to assist you with any database issues. We provide flexible support plans tailored to your specific needs. |
| Hands-On Database Management | Our managed services team can take over the day-to-day management of your database infrastructure, freeing up your time to focus on other priorities. |
| Expert Consulting | Our experienced consultants provide guidance on database topics like architecture design, migration planning, performance optimization, and security best practices. |
| Comprehensive Training | Our training programs help your team develop skills to manage databases effectively, offering virtual and in-person courses. |
We’re here to help you every step of the way. Whether you need a quick fix or a long-term partnership, we’re ready to provide your expertise and support.
3.4.22 - Legal notice
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This is the notice for the upstream Percona AI chatbot. This independent documentation site does not embed that chatbot. See site errata.
You are interacting with an AI-powered chatbot that provides automated responses for general information about our IT services and software. Responses may be inaccurate or incomplete and do not constitute professional or contractual advice. Do not submit personal data, confidential information, credentials, or other sensitive information through this chat. Conversations may be logged and processed to improve our services in accordance with our Privacy Policy and applicable laws, including the GDPR. If you require assistance, please contact a human representative.
3.4.23 - Blog
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Release notes, architecture explainers, and operational guidance derived from the pg_tde documentation.
3.4.23.1 - Release notes
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Version announcements and focused upgrade notes for pg_tde.
3.4.23.1.1 - pg_tde 2.2.2: Vault Enterprise KMIP and faster WAL encryption
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
An editorial reading note by PGSTY, based on the upstream documentation.
pg_tde 2.2.2 focuses on two operator-facing changes: KMIP support for HashiCorp Vault Enterprise and better WAL encryption performance.
The upstream release notes state that pg_tde 2.2.2 is incompatible with Percona Distribution for PostgreSQL versions older than 17.10.2 or 18.4.2.
What changed
- Add support for HashiCorp Vault Enterprise through KMIP. Vault Enterprise was already supported through the Vault V2 protocol.
- Improve WAL encryption performance.
- Fix empty certificate parameters passed to
pg_tde_add_global_key_provider_kmip()andpg_tde_add_database_key_provider_kmip(). - Fix a Vault provider race after a process fork.
- Fix WAL archiving with
pg_tde_archive_decryptandpg_tde_restore_encryptwhenpg_walis a symlink. - Include frontend tool fixes from PostgreSQL 16.15, 17.11, and 18.5.
Before you upgrade
- Confirm the Percona PostgreSQL package version is compatible.
- Review the key provider configuration and ensure the server can read existing principal keys.
- Test WAL archive and restore in a disposable environment.
- Keep the backup and WAL encryption procedure with the change record.
For the complete upstream changelog, read the pg_tde 2.2.2 release note.
3.4.23.1.2 - pg_tde 2.2.1: PostgreSQL 16 support and safer rewind
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
An editorial reading note by PGSTY, based on the upstream documentation.
pg_tde 2.2.1 is a compatibility and reliability release.
Highlights
- Add PostgreSQL 16 support.
- Improve
pg_rewindbehavior for pg_tde clusters. - Fix the
could not find server principal keyerror frompg_tde_basebackup. - Build pg_tde with Meson; the upstream release no longer supports building it with
make.
Upgrade checks
Before upgrading, verify that the target Percona PostgreSQL package and the configured provider can read all existing principal keys. Test rewind, recovery, and backup restore in a staging cluster before changing a production primary.
Read the full 2.2.1 release note.
3.4.23.2 - Guides
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Short, practical guides for designing and operating pg_tde deployments.
3.4.23.2.1 - A production checklist for pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
An editorial reading note by PGSTY, based on the upstream documentation.
Before enabling encryption, make the key provider and recovery path as concrete as the database configuration.
Checklist
- Confirm the Percona PostgreSQL and pg_tde versions are compatible.
- Load
pg_tdethroughshared_preload_librariesand create the extension in every database that needs it. - Use an external KMS or KMIP-compatible provider for production; keep keyring files for development and testing.
- Create and verify a principal key before creating encrypted tables.
- Test
tde_heapon a new table and on a disposable copy of an existing table. - If WAL encryption is enabled, use the pg_tde-aware archive and restore tools.
- Back up the provider configuration and document how the server obtains historical keys.
- Test restore, replica creation, major upgrade, and provider outage procedures.
- Record which objects are outside the encryption scope, including temporary files and statistics.
Related documentation
3.4.23.2.2 - How pg_tde keeps data encrypted through PostgreSQL storage
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
An editorial reading note by PGSTY, based on the upstream documentation.
Encryption only helps when it follows the real storage path. pg_tde marks the tables that need encryption with tde_heap, then uses PostgreSQL’s Storage Manager to encrypt pages before they reach disk and decrypt them before they enter the buffer cache.
The two-key hierarchy
Each encrypted data file has an internal key. The principal key protects the internal keys and lives in a key provider. This separation lets pg_tde rotate protection without rewriting every data page immediately.
Where WAL fits
WAL encryption is cluster-wide. The WAL pages use internal keys, and those keys are protected by the server principal key. A WAL reader uses key metadata to decide which records need decryption.
Operator consequence
A table can be readable while its key provider is available and unreadable when the provider or credentials are missing. The key management guide and recovery limits belong in the same runbook as the database configuration.
3.4.23.3 - From the Percona blog
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Editorial notes and links to original Percona articles. Read the complete articles at the source.
3.4.23.3.1 - Questions from the PostgreSQL TDE webinar
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Original author: Michal Nosek · Published: 2025-08-13 · Source: Percona Blog. Reading note by PGSTY.
The webinar follow-up discusses external key custody, table-level encryption, and the PostgreSQL patches required by pg_tde at the time. It is a useful starting point for separating data encryption from the surrounding access controls and recovery responsibilities.
Read the complete Percona article.
This article reflects its publication date. For current instructions, consult the related documentation and supported versions.
3.4.23.3.2 - The road to the pg_tde release candidate
tde_heap_basic to storage-manager integration and the redesign of WAL encryption. It captures a transition: table encryption was approaching GA, while WAL encryption remained a technology preview.This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Original author: Jan Wieremjewicz · Published: 2025-03-28 · Source: Percona Blog. Reading note by PGSTY.
The release-candidate announcement explains the move from tde_heap_basic to storage-manager integration and the redesign of WAL encryption. It captures a transition: table encryption was approaching GA, while WAL encryption remained a technology preview.
Read the complete Percona article.
This article reflects its publication date. For current instructions, consult the related documentation and supported versions.
3.4.23.3.3 - An early look at pg_tde
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
Original author: David Stokes · Published: 2024-01-30 · Source: Percona Blog. Reading note by PGSTY.
This early project update invites testing of an experimental pg_tde and discusses checking whether a table is encrypted. Read it as project history: the access method and SQL interfaces have changed since this prototype.
Read the complete Percona article.
This article reflects its publication date. For current instructions, consult the related documentation and supported versions.
3.4.24 - About
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This site combines the upstream pg_tde documentation with a bilingual Oink reading experience. See the attribution record.
3.4.24.1 - Attribution and copyright
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
This is an independent documentation and translation site maintained by PGSTY. It is not Percona’s official documentation and does not imply Percona’s endorsement. The official documentation and upstream project remain the primary sources.
Documentation source
The English edition was updated on November 21, 2026 to pg_tde 2.3.0, at percona/pg_tde@5dd7a9e4e3599d88546f5de67ff0f4ef3fe51a9a. It adds the 2.3.0 release notes to the previously imported 66 articles, with section indexes and PGSTY editorial guides. The Chinese edition includes the reviewed 2.3.0 incremental changes. The original authors are Percona and the pg_tde contributors.
Read the source manifest for file paths, hashes, supporting assets, and pinned source URLs. Each adapted page links to its original. The errata records corrections checked against this snapshot.
Upstream copyright and licence
The repository’s COPYRIGHT contains the pg_tde licence, with PostgreSQL-style grants and warranty disclaimers. Its full, unmodified text is preserved in pg_tde-COPYRIGHT.txt. It names:
- PostgreSQL Global Development Group — portions © 1996–2024.
- The Regents of the University of California — portions © 1994.
- Percona LLC and/or its affiliates — © 2024–2025.
The local identifier LicenseRef-pg-tde refers to that exact text. Permission covers use, copying, modification, and distribution of the software and its documentation subject to the stated notices and disclaimers. Percona and PostgreSQL names and logos remain the property of their respective holders.
Downstream work
PGSTY converts MkDocs formatting to Hugo/Oink, maintains paired English and Chinese pages, and adds navigation, an original key-hierarchy diagram, a homepage and editorial reading notes. SQL, examples and heading IDs are compared between languages. Corrections are disclosed separately; the source manifest retains the original hashes.
Percona blog entries are short editorial reading notes linking to the original articles. They retain the original author and publication date. The pg_tde repository licence is not asserted to cover the Percona website’s blog articles.
Site licence
The original standalone Percona documentation site’s configuration, styles, scripts, diagrams and original editorial text use the MIT License. Oink 1.5.1 supplies the theme under its own licence. Neither changes the upstream documentation licence.
3.4.24.2 - Documentation errata
This is the Percona pg_tde 2.3.0 manual. For the paired build, backup tools and major upgrades, see PG TDE on Mimus.
These corrections apply to the 1660e66a6a30 snapshot. They are downstream editorial changes, not an assertion that the upstream repository has merged them. Original files remain identifiable by the source manifest.
| Page | Correction | Evidence |
|---|---|---|
| Functions and usage reference | Use pg_tde.inherit_global_providers; remove obsolete parameter names. | GUC declarations |
| Functions | pg_tde_set_key_using_global_key_provider sets the current database key. The separate server function sets the WAL key. | Key implementation |
| Usage reference | Server/default key setters use global providers; the (global/database) notation is invalid for those two functions. | SQL definitions |
| Restore tool | %f is the WAL file name; %p is the destination for the unencrypted WAL segment. | Built-in help |
| Replication | Create the principal key before assigning it as the server key. | SQL definitions |
| FAQ | work_mem spill files are not encrypted; ordinary VACUUM does not rotate a file’s internal key. Use a table rewrite such as VACUUM FULL. | Limitations and architecture |
| Keyring example | Inspect customer_table, the table actually created; use pg_tde_key_info() for the current database key. | Function reference |
| KMIP overview | Preserve the older verification wording but flag its difference from the 2.2.2 announcement of Vault Enterprise KMIP support. | 2.2.2 release notes |
We also close a missing SQL quote, remove a duplicated RC changelog fragment, repair Markdown links and anchors, and replace MkDocs tabs/callouts with Oink components. Historical releases are labelled by their period. The upstream chatbot and feedback embed are not included.
The reproducible English transformations are recorded in scripts/import_upstream.py and scripts/upstream_edits.json; Chinese counterparts are maintained alongside them. Translation review is a self-review, not an independent certification or a runtime test of pg_tde.
4 - pgEdge · Spock
Spock 5.0.15 replicates selected tables between writable PostgreSQL databases. Each node can commit locally and receive the other node’s changes asynchronously. Plan how to identify rows, arbitrate concurrent writes and recover each node before you put a table in a replication set.
- Create two nodes and two subscriptions. Start with one copy of the initial data.
- Choose a conflict policy and monitor apply. Check both directions.
- Prepare standbys, PITR and rollback. Some conflict resolutions generate WAL that older kernels cannot replay.
The integrated replication component is Spock. The Mimus tests exercised two nodes, including encrypted tables and access through the MySQL and TDS clients. Deployment automation, routing and other pgEdge products require their own evaluation. 200 / 201 kernel changes · Upstream Spock
pgEdge extension manuals
The PG.CENTER collection covers four extensions. The r4 image uses Spock 5.0.15 at e710faa6fe21. It also includes LOLOR 1.2.3 and Snowflake 2.6.1. Use the three Mimus guides above to operate that version.
| Manual | Upstream reference | Purpose |
|---|---|---|
| Spock | 6.0.0-beta.2 plus 5.0 maintenance notes | Multi-master replication, conflicts, SQL API |
| LOLOR | 1.3.0 development snapshot | Logical replication of large objects |
| SafeSession | 1.1 | Enforce read-only sessions by role |
| Snowflake | 2.6.1 | Generate distributed 64-bit identifiers |
4.1 - Start two writable nodes
Prepare the instances
Start with two fresh Mimus 19.0.1 clusters on one host, A on loopback port 5541 and B on 5542. Install the paired Spock extension and output plugin in both prefixes. Configure the following on both, merging any existing required preloads. Each cluster needs its own data directory and port. Restart both and create a database named lab in each. For separate hosts replace the loopback addresses with peer-reachable addresses.
Configure pg_hba.conf and service-account libpq credentials so both servers can connect to both lab databases using the named administrative role. The example uses postgres. Test each DSN from the database service account, including reconnect after restart. Connect psql to lab separately on A and B. Install the extension on both, then register each node with its own address.
Define the tables and copy the seed
On both nodes create the same empty table, column options and replication-set membership:
Seed A only. On B, subscribe to A and confirm the seed arrived. Then subscribe A to B without copying data a second time. The empty origin list limits forwarding to locally originated changes.
Check both writers
On each read, poll until the row arrives before moving to the next step. A should finally return (2,from_b,52). Check SELECT subscription_name, status FROM spock.sub_show_status() on both nodes. Both should say replicating. A local COMMIT may return before the peer sees the row. Operate the pair
4.2 - Conflicts, monitoring and catch-up
Design for concurrent writers
With last_update_wins and commit-timestamp tracking, a conflicting ordinary value follows the newer commit timestamp. Synchronize the node clocks. A later timestamp can discard a business change. Assign writers disjoint keys when possible and use a non-deferrable primary key for updates and deletes. Two independent sequences can allocate the same ID. Additional unique constraints can also reject an incoming row.
The balance column in the example logs its previous value. Delta Apply combines the remote change with the current local balance. In the two-node test, both sides started at 100 and committed increments of 7 and 13 while disconnected from apply. Both finished at 120. Ordinary text columns retained the winning writer’s value. Choose this policy for additive quantities. Test domain constraints such as overdraft limits separately. Spock conflict handling
Observe each direction
A subscription reports its receiver state; the provider slot shows whether a consumer is attached and how much WAL is being retained. Compare successive LSNs while generating known writes. Use spock.resolutions (with save_resolutions on) to inspect resolved conflicts and the exception log and server log to investigate apply errors. Verify the row values on both databases.
A subscriber in the integration test stopped, restarted and caught up from retained WAL. If progress stalls, check connectivity, receiver logs, slot validity, schema equality and available disk space. Preserve a needed slot while diagnosing it. An invalidated slot or missing WAL may require a new consistent copy of the data. Coordinate the authoritative copy and reconcile writes on both sides before reseeding.
Schema changes
This setup uses matching, manually created objects with automatic DDL replication off. Pause writes on both nodes, let subscriptions catch up and coordinate schema changes. Temporary and unlogged tables are outside the replication set. Evaluate dialect-specific DDL, sequence allocation and multi-subscription recovery in the application’s own rehearsal. Spock limitations
The upstream 6.0 manual introduces spock.node_report() and spock.event_history_size. The 5.0.15 extension sources used by Mimus do not define either interface. Use spock.sub_show_status() and the replication-slot queries above on this build. Upstream 6.0 monitoring changes
4.3 - Recovery, failover and rollback
Before the first subscription
Upgrade physical standbys, failover hosts and PITR environments first. A new standby was able to follow a pre-Spock primary. Verify replay and the matching backup tools and keys, then switch the primary. Take a restorable base backup and record a pre-activation recovery point. Archive continuously. A backup of one node preserves that database’s physical state at its recovery point. Writes committed only on a disconnected peer require a separate reconciliation.
Restore and verify
Recover a separate, network-isolated copy using a kernel with the 200 / 201 changes. Keep subscriptions from reconnecting to live peers during the drill. With TDE, follow the key and backup procedure. Restore through the target WAL, pause at the chosen target and check pg_is_in_recovery() and pg_get_wal_replay_pause_state(). Compare representative rows, xmin and pg_xact_commit_timestamp(xmin) against values recorded at the target. Verify the table and index encryption status, and the absence of a transaction committed after the target.
The test restored ordinary and encrypted tables to a named point after Delta Apply, with both plaintext and encrypted WAL on the full kernel. Before promoting a physical standby to serve both writers, verify slots, origins, subscriptions and convergence with the other node. On Debian 13 amd64, r4 passed all seven Spock checks. After standby catch-up and promotion, row values, commit timestamps and origins matched the primary. The concurrent test verified two subscription apply workers.
How far can an older reader go?
| Situation | Operational decision |
|---|---|
| Before Spock activation | A prior same-major reader handled ordinary WAL in the tested combination. Preserve a pre-activation backup and target for a rollback drill. |
Replay crosses CommitTs/SUBTRANS_TS | Keep the matching RC2 recovery environment for archives with the old 0x20 record. At cutover, quiesce writes and subscriptions and shut down cleanly. Equip the primary and recovery hosts with r4, take a new full backup and rebuild physical standbys from it before resuming replication. |
| Return to an older system and keep later writes | Recover first with the matching kernel. Quiesce or reconcile writers, migrate representable application data logically and compare the rows. The fallback test moved one business table. Rebuild and validate roles, sequences, keys and topology separately. |
In the earlier physical-reader test the old kernel reached a pre-conflict point with balance 113. The new kernel restored the same backup through the conflict and read 120. A marked directory also enforces its kernel requirements at startup. Keep the feature marker intact. Control-file version and a successful clean start alone cannot qualify a recovery reader. How Spock changes replay
4.4 - pgEdge upstream manuals
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Four extensions address concrete tasks in distributed PostgreSQL. Start with Spock replication, then add identifiers, large-object replication, and session protection as your application needs them.
- Spock — Multi-master replication and conflicts
- Snowflake — Distributed unique IDs
- LOLOR — Large object logical replication
- SafeSession — Read-only sessions by role
The English source set is Spock v6.0.0-beta.2, LOLOR 1.3.0 development, SafeSession v1.1, and Snowflake v2.6.1. All 118 English pages have Chinese counterparts. See sources and versions.
Start reading
4.4.1 - Quick start
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Read the installation prerequisites, then follow the complete two-node procedure. Spock requires PostgreSQL server patches, compatible table definitions, and authenticated connections between nodes.
4.4.2 - Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The English source is v6.0.0-beta.2 (pre-release), pinned at d05e2e2b6a82. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
The Spock extension provides multi-master (active-active) replication for pgEdge Distributed and Enterprise Postgres, versions 15, 16, 17, 18, and 19. The extension leverages the pgLogical open-source project as a solid foundation to build upon for this enterprise-class extension.
Continue reading
- Frequently Asked Questions
- Configuring Spock
- Conflict Types
- Conflict-Free Delta-Apply Columns (Conflict Avoidance)
- Creating a Spock Cluster: End-to-End Installation Guide
- Installing and Configuring the Spock Extension
- Limitations and Restrictions
- Logical Slot Failover
- pglogical to Spock function names
- Sizing Postgres Resources for Spock
- Spock Release Notes
- Troubleshooting Spock
- Using Spock to Create a Two-Node Cluster
- Upgrading the Spock Extension
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.1 - Installing and Configuring the Spock Extension
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension can be installed with pgEdge Postgres packages or built from source. pgEdge Postgres deployments provide a simplified upgrade path that allows you to take advantage of important new features quickly and easily.
Spock is open-source, with code available for review at GitHub.
Spock uses files stored in the spock schema to provide replication
functionality. Do not delete, create, or modify files in the spock
schema directly; use Spock functions and procedures to manage
replication.
For detailed information about using Spock to create a two-node cluster, see Creating a Two-Node Cluster.
Installing Spock with pgEdge Enterprise Postgres
The latest Spock extension is automatically installed with any pgEdge Enterprise Postgres installation. A pgEdge deployment provides quick and easy access to the following features:
- the latest minor version of your preferred Postgres version.
- Spock functions and procedures.
- ACE consistency monitoring.
- Snowflake sequences.
- pgBackRest for simplified backup and restore capabilities.
- LOLOR large object support.
- management tools for your active-active distributed cluster.
Building the Extension from Source
Spock is available as an open-source project
that you can build from source code distributed at the GitHub project page.
The Spock extension must be built on a version-specific build of Postgres
that is patched to provide hooks so spock can access the Postgres engine.
To patch the Postgres source code, download the source code from the
Postgres project, and move into
the source directory. Then, clone the spock directory:
Then, apply the .diff files from the spock/patches/version directory
that match your build version. To apply a patch, use the command:
After applying version-specific patches, you can configure, make, and
make install the Postgres server as described in the
Postgres documentation.
When the build completes, add the location of your pg_config file to your
PATH variable:
Before invoking make and make install, install the
jansson library to meet
Spock prerequisites.
Then, move into the spock directory, and use a build process much like
any other Postgres extension:
Configuring Postgres for Spock Replication
After installing Postgres on each node that will host a spock instance, use initdb to initialize a Postgres cluster. After initializing the cluster, you can connect with psql, and query the server for file locations and cluster details:
Then, use your choice of editor to update the postgresql.conf file, adding
required Postgres parameters to the end of the file:
The values above are a working starting point for a small cluster (two or
three nodes, one replicated database). They are not one-size-fits-all: Spock
launches a supervisor, a slot sync worker, one background worker per database
in the instance, and one per subscription; subscription counts scale with node count multiplied by the number of
replicated databases, and max_worker_processes is shared with parallel query
workers. See
Sizing Postgres Resources for Spock for the formulas and
per-cluster recommendations before going to production.
Set output_plugin_libraries only if your server has that parameter — it was
added by a 2026 security fix and, without spock_output listed there, logical
decoding fails with library "spock_output" may not be used as an output plugin. The check runs every time decoding starts, so it stops established
clusters after a minor-version upgrade too, and it applies to every node. On
older releases the parameter does not exist and setting it stops the server
from starting. See Configuring Spock for how to check.
Note on replication origin states:
- PostgreSQL 15-17: The
max_replication_slotsparameter controls both the number of replication slots and the number of replication origin states; when sizing this parameter, account for both slots and origins (one origin per subscription, and subscriptions are counted per replicated database). - PostgreSQL 18+: A new parameter
max_active_replication_originswas introduced to separately control the number of replication origin states; the default value is 10, which may be insufficient for clusters with many subscriptions; set this to at least the number of subscriptions this node applies -(nodes - 1) x replicated databasesin a full mesh - plus some headroom (similar sizing tomax_replication_slots).
After modifying the Postgres parameters, use your OS-specific command to restart the Postgres server:
Then, connect to the psql command line, and create the spock extension:
On each node that will host spock, modify the pg_hba.conf
file and
allow connections between n1 and n2. The following snippet is provided
as an example only, and is not recommended for a production system as it
will open your system for connection from any client:
Creating a Replication Scenario
After configuring the nodes, connect to the psql command line of the first
provider node, and use the spock.node_create command to create the
provider node:
Then, add the tables in the public schema to the default replication
set:
Once the provider node is configured, you can add subscribers. First, create the subscriber node:
Then, create the subscription which will start synchronization and replication on the subscriber node:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.2 - Creating a Spock Cluster: End-to-End Installation Guide
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This guide walks you through installing Spock and creating a two-node active-active replication cluster.
Before you begin, ensure you have met the following prerequisites:
- Each node must be a physical or virtual machine with network connectivity.
- You must have administrative access to both nodes.
- A basic familiarity with PostgreSQL and command-line operations is required.
The installation process follows these steps.
- Add the pgEdge repository and install pgEdge Postgres with Spock.
- Configure PostgreSQL parameters for logical replication.
- Create the Spock extension on both nodes.
- Set up node definitions and bidirectional subscriptions.
- Enable automatic DDL replication across the cluster.
- Test the cluster to verify bidirectional replication works correctly.
Install pgEdge Enterprise Postgres (Recommended Path)
This section describes how to install pgEdge Enterprise Postgres with Spock using the pgEdge repository.
First, on each node, add the pgEdge repository to your system.
For RHEL/Rocky Linux/AlmaLinux 10, first install EPEL:
On RHEL 10, also enable the CodeReady Builder repository:
On Rocky Linux 10 or AlmaLinux 10, enable the equivalent CRB repository instead:
Version-specific commands for RHEL, OEL, Alma, and Rocky are available in the pgEdge Enterprise Postgres documentation.
For Ubuntu/Debian:
Before configuring local access to the pgedge repository, you should ensure that your system does not contain any community Postgres packages. Then, install the platform-specific prerequisites for your system with the commands:
Then, create the repository with the commands:
For detailed information about using the pgEdge repository, see the pgEdge Enterprise Postgres documentation.
After creating the repository, install your preferred PostgreSQL version. The examples use PostgreSQL 18. If you switch to 15, 16, 17, or 19, update every versioned package, path, and service name in the snippets below.
For RHEL/Rocky Linux/AlmaLinux:
For Ubuntu/Debian:
On each node, initialize the PostgreSQL database cluster.
For RHEL/Rocky Linux/AlmaLinux:
For Ubuntu/Debian:
In the following example, the psql command connects to PostgreSQL to
verify the installation:
Once connected, confirm that you can see the configuration file locations.
In the following example, the SHOW commands display the PostgreSQL
configuration file locations:
The pgEdge Enterprise Postgres installation automatically includes the following components:
- The latest minor version of your chosen Postgres version.
- The Spock extension (pre-installed, ready to enable).
- Spock functions and procedures.
- ACE consistency monitoring.
- Snowflake sequences.
- pgBackRest for simplified backup and restore.
- LOLOR large object support.
- Management tools for active-active distributed clusters.
Install from Source (Alternative Path)
If you need to build Spock from source instead of using pgEdge Enterprise Postgres, follow these steps.
Download PostgreSQL source code from the Postgres project and navigate to the source directory.
Clone the Spock repository with the following command:
Apply the version-specific patches with the following command:
Configure, build, and install PostgreSQL as described in the Postgres documentation.
Add the
pg_configfile location to your PATH with this command:Install the jansson library (required for Spock).
Build and install Spock with the following commands:
Repeat the installation process on both nodes.
After building from source, use initdb to initialize a PostgreSQL cluster on each node.
Configure PostgreSQL for Spock Replication
On each node, edit the postgresql.conf file and add the required
parameters to the end of the file.
In the following example, the configuration parameters enable logical replication and load the Spock extension:
max_worker_processesThis parameter covers more than one worker per node: Spock runs a
supervisor, a slot sync worker (present on every node, primary or
standby), a manager for every connectable database in the instance
(including postgres and template1), an apply worker per subscription,
and a sync worker per subscription during table synchronization.
Subscriptions are created per database, so their count is the number of
other nodes multiplied by the number of replicated databases. The pool
is also shared with parallel query workers. See
Sizing Postgres Resources for Spock for the formulas.
Set output_plugin_libraries only if your server has that parameter — it
was added by a 2026 security fix and, without spock_output listed there,
logical decoding fails with library "spock_output" may not be used as an output plugin. The check runs every time decoding starts, so it stops
established clusters after a minor-version upgrade too, and it applies to
every node. On older releases the parameter does not exist and setting it
stops the server from starting. See
Configuring Spock for how to check.
PostgreSQL 15-17: The
max_replication_slotsparameter controls both slots and replication origin states. Account for both when sizing (one origin per subscription, and subscriptions are counted per replicated database).PostgreSQL 18+: A new parameter
max_active_replication_originsseparately controls origin states. The default value is 10, which may be insufficient. Set the value to at least the number of subscriptions this node applies -(nodes - 1) x replicated databasesin a full mesh - plus headroom.
After modifying postgresql.conf, restart PostgreSQL using your
OS-specific command.
In the following example, the systemctl commands restart and verify
the PostgreSQL service:
Verify the service is active and running.
On each node, modify the pg_hba.conf
file to allow connections between the nodes.
Add entries for both regular and replication connections. Replace
<node_1_IP_address> and <node_2_IP_address> with your actual IP
addresses.
In the following example, the configuration entries allow connections from both nodes:
The example above uses trust authentication for simplicity and is
not recommended for production systems. In production, use
appropriate authentication methods like scram-sha-256 or md5.
After modifying pg_hba.conf, reload the server configuration to apply the
changes (no restart required):
Create the Spock Extension
On each node, connect to PostgreSQL and create the Spock extension.
In the following example, the CREATE EXTENSION command creates the
Spock extension:
Spock uses the spock schema to provide replication functionality.
Do not delete, create, or modify files in the spock schema
directly. Use Spock functions and procedures to manage replication.
Create Nodes and Configure Replication
This section describes how to set up bidirectional replication between the two nodes.
For this guide, the nodes are named n1 and n2.
On Node 1 (n1)
Follow these steps to create the node definition and add tables to the replication set.
Create the node definition with the following command:
Add tables to the default replication set with this command:
If you are working in a schema other than
public, adjust the schema name accordingly.
On Node 2 (n2)
Follow these steps to create the node definition, add tables, and create the subscription.
Create the node definition with the following command:
Add tables to the default replication set with this command:
Create the subscription from n2 to n1 with these commands:
On Node 1 (n1)
Create the reverse subscription from n1 to n2 with the following commands:
On Both Nodes (n1 and n2)
To ensure DDL statements are automatically replicated across your cluster, run these commands on both nodes.
In the following example, the ALTER SYSTEM commands enable automatic
DDL replication:
These settings enable the following features:
- DDL statements are automatically replicated through the default replication set.
- New tables are automatically added to replication sets; tables with primary keys are added to the default set, and tables without primary keys are added to the default_insert_only set.
Verify the Cluster
On each node, use the following command to verify that nodes are properly configured.
In the following example, the SELECT command displays the configured
nodes:
Expected output:
Then, use the following command to verify that subscriptions are active and replicating.
In the following example, the SELECT command displays the subscription
status:
Expected output:
The status field should display replicating.
Test Replication
Perform a simple replication test using the following steps.
On n1, create a test table with the following commands:
On n2, verify the table exists and contains the data with this query:
Expected output:
On n2, insert a new row with the following command:
On n1, verify both rows are present with this query:
Expected output:
Both messages should appear on both nodes, confirming that bidirectional replication is working.
Next Steps
Your two-node Spock cluster is now operational. The following documents describe the next steps for configuring and managing the cluster.
- The Configuring Spock document describes conflict resolution settings and advanced configuration options.
- The Spock Functions Reference document provides detailed information about monitoring functions and replication management.
- The Managing DDL Replication document explains how to control automatic DDL replication behavior.
Troubleshooting
If you encounter issues, review the following common problems and solutions.
- Check the
pg_hba.confentries and ensure the nodes can connect to each other if replication is not starting. - Verify that
max_replication_slotsandmax_wal_sendersare set to sufficient values when a subscription is stuck initializing. A subscription that is synchronizing needs a second slot and walsender on the provider in addition to those held by its apply stream; see Sizing Postgres Resources for Spock. - If DDL is not replicating, confirm that the automatic DDL replication settings are enabled on both nodes.
- If errors are not clear, review the PostgreSQL logs for detailed error messages.
For more information, see the following resources:
- The Spock Functions Reference document provides detailed function documentation.
- The Advanced Configuration Options document describes additional configuration parameters.
- The Managing DDL Replication document explains DDL replication features.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.3 - Using Spock to Create a Two-Node Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The upstream example in step 3 gives postgresql.conf as the path to pg_hba.conf. Authentication rules belong in the actual pg_hba.conf; SHOW hba_file; reports its path. See known upstream issues.
After installing and initializing Postgres and creating the Spock Extension, you can use the following steps to configure a two-node cluster. In the examples that follow, we’ll be creating a cluster that contains two nodes, named n1 and n2 that listen for Postgres server connections on port 5432.
Connect to each node, and use the following commands to initialize a cluster:
sudo /usr/pgsql-17/bin/postgresql-17-setup initdbsudo systemctl enable postgresql-17Use your choice of editor to open the
postgresql.conffile (located in/var/lib/pgsql/17/data/postgresql.conf) and add the following parameters to the bottom of the file:wal_level = 'logical'max_worker_processes = 20max_replication_slots = 10max_wal_senders = 10shared_preload_libraries = 'spock'track_commit_timestamp = onThese values are sized for this two-node example, which replicates a single database. Before moving to production, or if you add nodes or databases, size them from your topology using Sizing Postgres Resources for Spock - subscriptions are created per database, so slots, walsenders, and workers scale with node count multiplied by replicated database count, and
max_worker_processesis additionally shared with parallel query workers and needs one slot per database in the instance, one for the supervisor, and one more for the slot sync worker.Edit the
pg_hba.conffile (useSHOW hba_file;to find its path) and allow connections betweenn1andn2; the following commands are provided as an example only, and are not recommended for production systems as they will open your system for connection from any client:host all all 0.0.0.0/0 trustlocal replication all trusthost replication all 0.0.0.0/0 trustUse the
spock.node_createcommand to create the provider and subscriber nodes; onn1, use the command:SELECT spock.node_create (node_name := 'n1', dsn := 'host=<n1_ip_address> port=<n1_port> dbname=<db_name>');On
n2:SELECT spock.node_create (node_name := 'n2', dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>');On
n1, use thespock.repset_add_all_tablescommand to add the tables in thepublicschema to thedefaultreplication set. If you are working in another schema, customize this command as needed:SELECT spock.repset_add_all_tables('default', ARRAY['public']);On n2, use the
spock.sub_createcommand to create the subscription between n2 and n1; the name of the subscription issub_n2_n1:SELECT spock.sub_create (subscription_name := 'sub_n2_n1', provider_dsn := 'host=<n1_ip_address> port=<n1 port> dbname=<db_name>');SELECT spock.sub_wait_for_sync('sub_n2_n1');On
n1, create a corresponding subscription ton2namedsub_n1_n2:SELECT spock.sub_create (subscription_name := 'sub_n1_n2', provider_dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>');To ensure that modifications to your DDL statements are automatically replicated, connect to each node with a Postgres client and invoke the following SQL commands:
ALTER SYSTEM SET spock.enable_ddl_replication=on;ALTER SYSTEM SET spock.include_ddl_repset=on;ALTER SYSTEM SET spock.allow_ddl_from_functions=on;SELECT pg_reload_conf();Then, check the status of each node:
A simple test to check that your system is replicating is to connect to the Postgres server on n1 and add an object (like a table), and then confirm that it is available on n2. Similarly, you can create an object on n2, and confirm that it has been created on n1.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.4 - Sizing Postgres Resources for Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock replication consumes three separate, independently-configured Postgres resources: background worker slots, walsender slots, and replication slots/origins. Each is governed by a different parameter, and each is sized from a different property of your cluster.
Many of the values shown in the tutorials are a starting point for a small test cluster, not a recommendation for production. This page explains what Spock actually launches so you can size each parameter deliberately.
Every parameter on this page backed by an explicit recommendation requires
a server restart to change. Under-sizing them is not a soft failure:
Spock raises an ERROR when a worker cannot be registered and the
supervisor retries in a loop, so replication does not start at all. Formulas
include a small amount of headroom partially to prevent this.
What Spock Runs on Each Node
| Process | How many | Counts against |
|---|---|---|
| Supervisor | 1 per instance, always running | max_worker_processes |
| Slot sync worker | 1 per instance | max_worker_processes |
| Manager | 1 per connectable database in the instance | max_worker_processes |
| Apply worker | 1 per enabled subscription | max_worker_processes |
| Table sync worker | at most 1 concurrently per subscription | max_worker_processes |
| Walsender | 1 per subscription streaming from this node, plus 1 more per subscription during table sync | max_wal_senders |
Four of these counts are commonly misjudged.
A slot sync worker exists on every node, not just standbys. These workers copy logical replication slots to each physical standby so that failovers do not force a full resync of every subscriber. These workers remain idle on primary nodes but still consume a worker slot, so are included in the formula. See Slot Synchronization below for more information.
Managers are launched for every connectable database, not just the ones
using Spock. The supervisor cannot determine whether a database contains a
Spock node without connecting to it, and a background worker cannot switch
databases. So it launches a manager for every database in pg_database with
datallowconn = true; managers that find no Spock node exit immediately.
On a default cluster that means postgres and template1 each get a
short-lived manager in addition to your replicated database. template0 is
excluded because it does not allow connections.
Walsenders are not background workers. They are governed by
max_wal_senders and counted separately in MaxBackends. Raising
max_worker_processes does nothing for walsender exhaustion, and vice versa.
Subscriptions are per database, not per node. A Spock node is created inside a single database, and each subscription connects one database on this instance to the corresponding database on one other instance. An instance that replicates several databases therefore hosts one Spock node per replicated database, and each of those nodes carries its own full set of subscriptions. Everything downstream of the subscription count such as apply workers, table sync workers, walsenders, slots, and origins, all scale with node count multiplied by replicated database count, not node count alone.
Slot Synchronization
Slot synchronization is not optional for a cluster with a physical standby: a promotion without it forces every subscriber to recreate its slot and re-sync its tables. What changes between PostgreSQL versions is only who supplies the worker.
| PostgreSQL | Supplied by | Charged to max_worker_processes |
|---|---|---|
| 15, 16 | Spock’s spock_failover_slots background worker | Yes |
| 17 | Either, depending on sync_replication_slots | Yes - Spock registers its worker regardless, and it stands down when the native one is enabled |
| 18+ | PostgreSQL’s native slotsync worker | No - it is a dedicated postmaster process, counted separately in MaxBackends |
Budget a worker for it on every node and every version. Where PostgreSQL supplies the worker the budgeted slot simply becomes headroom, which costs nothing beyond a little shared memory and spares you a version-dependent formula. Logical Slot Failover covers the configuration each mechanism needs.
Sizing max_worker_processes
For one node, at peak:
spock_workers = 1 # supervisor
+ 1 # slot sync worker
+ D # connectable databases in this instance
+ S # apply workers: one per enabled subscription
+ S # table sync workers: worst case, one per subscription
max_worker_processes = spock_workers
+ max_parallel_workers # shared pool - see below
+ other_extension_workers # pg_cron, pg_squeeze, ...
+ 2 # headroom
Where:
Nis the number of Spock nodes in the cluster.Dis the number of databases in the instance withdatallowconn = true, includingpostgresandtemplate1— not just the databases participating in replication.Ris the number of databases in this instance that actually participate in Spock replication (R <= D). It is1in most deployments.Sis the total number of enabled subscriptions across all databases in the instance. In a fully-meshed cluster ofNnodes each replicating the sameRdatabases,S = R * (N - 1). With a single replicated database that reduces to the familiarS = N - 1.
max_worker_processes is a shared pool. Parallel query workers
(max_parallel_workers, default 8), native logical replication workers
(max_logical_replication_workers), and background workers belonging to
other extensions all draw from the same allocation. A parallel-heavy
workload can starve replication of worker slots. Autovacuum workers are
the exception — they have their own autovacuum_max_workers allocation.
Recommended Minimums
Assuming a single replicated database alongside postgres and template1
(D = 3, R = 1), the default max_parallel_workers = 8, and no other
worker-using extensions:
| Cluster | Spock Workers | Total Workers |
|---|---|---|
| 2-node | 7 | 20 |
| 3-node | 9 | 20 |
| 4-node | 11 | 24 |
| 5-node | 13 | 24 |
| 8-node | 19 | 32 |
The totals are rounded up to leave room for growth; there is no meaningful
cost to over-provisioning max_worker_processes beyond a small amount of
shared memory, and the parameter cannot be changed without a restart.
Add to these numbers if your instance hosts more databases, replicates more
than one database, or runs other extensions that register background workers.
Each additional replicated database costs 1 manager (if the database is
not already counted in D) plus 2 * (N - 1) workers for its apply and sync
workers, so a 3-node cluster replicating three databases needs 3 * 2 * 2 = 12
apply and sync workers per instance rather than 4.
Sizing max_replication_slots and max_wal_senders
Each node holds a logical replication slot for every subscription that streams from it, plus a transient slot for each in-progress table sync. Sync slots are created as persistent slots (not temporary), so each one occupies a slot until the sync finishes and the slot is dropped. Every one of those slots has a walsender behind it while it is streaming, so set both parameters to the same value and compute it once, from the slot count.
The default is 10 for max_replication_slots and max_wal_senders. Consider
this a minimum value for each. If any formulas provide a value below 10,
simply retain the default value.
Where N is the number of Spock nodes and R the number of replicated
databases in the instance:
max_replication_slots = 2 * R * (N - 1) # apply slot + sync slot per subscription
+ physical_and_failover_slots
+ 2 # headroom for pg_basebackup and ad-hoc tooling
max_wal_senders = max_replication_slots
R is 1 in most deployments. A 5-node mesh replicating a single database, with
one physical standby per node, needs 2 * 1 * 4 + 1 + 2 = 11 for both
parameters; the same mesh replicating three databases needs
2 * 3 * 4 + 1 + 2 = 27.
PostgreSQL’s logical replication documentation recommends setting
max_wal_senders to at least max_replication_slots plus the number of
physical replicas connected at the same time. That extra term covers
physical standbys that stream without a slot; the formula above already
gives each physical standby a slot in physical_and_failover_slots, so
adding them a second time would double-count. Sizing every node from the
same formula, standbys included, also satisfies the separate rule that a
standby’s max_wal_senders be at least as high as its primary’s.
Not every replication connection is a walsender. Table sync workers open a
second, non-replication connection to run COPY, which draws from
max_connections. The slot sync worker on a standby likewise reaches the
primary over an ordinary connection. Both Spock’s worker and PostgreSQL’s
native one cost the primary a max_connections slot, not a walsender.
Replication Origins
Postgres uses origins to track local state for remote replication slots.
Internally, Postgres tracks replication origins separately from slots and
pins their count to max_replication_slots in Postgres versions 15-17. Our
formula should make it impossible for there to be more origins than slots in
those versions of Postgres.
However, Postgres 18 introduces max_active_replication_origins with a
default value of 10, which may be too low for an active Spock cluster. For
the sake of simplicity, we encourage using this simple formula for that
parameter:
max_active_replication_origins = max_replication_slots
This should cause Postgres 18+ to operate with a sufficiently large origin pool.
Worked Examples
Because these settings require so many inputs, this documentation provides some examples.
3-Node Mesh
Three nodes, each with a single replicated database app, plus the default
postgres and template1 databases. Each node subscribes to the other two,
and each node has one physical standby.
Per node: D = 3, R = 1, S = R * (N - 1) = 2.
5-Node Mesh
Five nodes, each with replicated databases app and ledger, plus the default
postgres and template1 databases. Each node subscribes to the other four,
and each node has two physical standbys, common in clusters leveraging safe
synchronous replication.
Per node: D = 4, R = 2, S = R * (N - 1) = 8.
Verifying Your Configuration
List the Spock workers currently running on a node:
Each Spock worker reports its role and the OIDs it serves in backend_type -
for example spock supervisor, spock manager 16384, and
spock apply 16384:1.
Compare the number of background workers in use against the limit:
The exclusion list names the client backends and auxiliary processes that do
not draw on max_worker_processes; everything left over does. The list of
auxiliary process types changes between major versions, so check it against
pg_stat_activity
for your version.
Diagnosing Exhaustion
worker registration failed, you might want to increase max_worker_processes setting
Postgres refused to register a background worker because
max_worker_processes is fully allocated. Recompute with the formula above,
remembering that parallel query workers share the pool, and restart.
could not register spock worker: all background worker slots are already used
Spock’s own worker-tracking array — sized to max_worker_processes at
startup — has no free entry. A worker that exits cleanly releases its entry
immediately, but a worker that crashes leaves its entry reserved for the
same database until that database’s manager (or the supervisor) reclaims it.
Repeated worker crashes across many different databases can therefore exhaust
the array while Postgres still reports free worker slots. Check the server log
for the preceding crash and address that; raising max_worker_processes
enlarges the array but does not fix the underlying failures.
Subscription stuck in initializing
Usually max_replication_slots or max_wal_senders on the provider. A
subscription that is initializing needs a slot and walsender for its sync
worker in addition to those already held by its apply stream, which is why a
cluster that replicates fine in steady state can fail to add or resync a
table. See Troubleshooting.
Increasing replication lag with idle apply workers
If spock.lag_tracker shows growing lag but apply workers are not running,
check the server log for worker registration failures — the manager retries
registration on a delay, so an exhausted worker pool presents as intermittent
apply rather than a hard stop.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.5 - Configuring Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Add the following postgresql.conf settings on each node in your Spock
replication scenario before creating the Spock extension:
These values suit a small cluster of two or three nodes replicating a single database. Subscriptions - and the workers, walsenders, and slots that follow from them - scale with node count multiplied by the number of replicated databases, so an instance replicating several databases needs proportionally more of each. For anything larger, or for an instance hosting several databases or other extensions that use background workers, size each parameter with the formulas in Sizing Postgres Resources for Spock. All three require a server restart to change.
output_plugin_librariesA 2026 PostgreSQL security fix (CVE-2026-6471, back-patched to every
supported major) added the output_plugin_libraries parameter, and a
library may no longer be used as an output plugin unless it is listed
there. Its default, 'pgoutput, test_decoding', does not include
spock_output, so on such a server logical decoding fails with:
The check runs every time decoding starts, not only when the slot is
created, so an established cluster stops replicating after a minor-version
upgrade too. Add spock_output to the list, keeping the core defaults, as
shown above, on every node — including standbys, which need it once
promoted.
Only set the parameter if your server has it. On a PostgreSQL release
predating the fix an unrecognised parameter in postgresql.conf stops the
server from starting at all. To check, run against a server that is up:
A NULL result means the parameter does not exist and must not be set. You can also ask the binary, with no server running:
After modifying the parameters and restarting the Postgres server with your OS-specific restart command, connect with psql and create the Spock extension:
You will also need to modify your
pg_hba.conf file
to allow logical replication connections from localhost and between nodes.
Logical replication connections are treated by pg_hba.conf as regular
connections to the provider database.
After modifying the pg_hba.conf file on each node, reload the server
configuration to apply the changes (no restart required):
Advanced Configuration Options for Spock
You can use the following configuration parameters (GUCs) on the psql
command line with a SET statement or in a Postgres configuration file
(for example, postgresql.conf) to configure a Spock installation.
spock.allow_ddl_from_functions
spock.allow_ddl_from_functions enables spock to automatically replicate
DDL statements that are called within functions to also be automatically
replicated. This can be turned off if these functions are expected to run
on every node. When this is set to off, statements replicated from
functions adhere to the same rule previously described for
include_ddl_repset. If a table possesses a defined primary key, it will be
added into the default replication set; alternatively, they will be added
to the default_insert_only replication set.
spock.apply_change_logging
spock.apply_change_logging controls per-change JSON logging by the apply
worker. After each change is successfully applied locally, a single JSON
object is written to the PostgreSQL server log (at LOG level) so that
operators can correlate replayed changes with their origin and commit
timestamp. This is intended for debugging and auditing; it adds log volume
proportional to the apply workload, so leave it at the default in normal
operation.
The following values are possible:
none(the default) - no per-change logging.key_only- for eachINSERT/UPDATE/DELETE, log the action, schema-qualified table, primary-key values, origin, and commit timestamp.verbose- all of the above, plus the old and new row data for each change.
Replicated DDL is logged (with its SQL text) in both key_only and
verbose modes. This option can be set by a superuser via SET, or
reloaded with the SIGHUP mechanism (for example,
SELECT pg_reload_conf()); a server restart is not required.
spock.channel_counters
spock.channel_counters is a boolean value (the default is true) that
enables or disables the Spock channel statistic information collection. This
option can only be set when the postmaster starts.
spock.check_all_uc_indexes
This feature is experimental and OFF by default. Use this feature at
your own risk.
This parameter enhances conflict resolution during INSERT operations in
scenarios where a row exists that meets unique constraints defined on the
table (rather than primary keys or replication identity).
If this GUC is enabled, Spock will continue to check unique constraint
indexes, after checking the primary key or replica identity index. Only one
conflict will be resolved, using Last-Write-Wins logic. This includes the
primary key or replica identity index. If a second conflict occurs, the outcome is recorded in the
spock.resolutions table if spock.save_resolutions is enabled; otherwise
it is not persisted.
Partial unique constraints are supported, but nullable unique constraints are not. Deferrable constraints are not supported, are filtered out and are not checked, and therefore may still cause an exception during the final commit.
Unique constraint indexes are checked in OID order, after the primary key. It is therefore possible for the resolution of a unique constraint to change the primary key value.
Child tables / foreign keys are not checked or handled. Therefore, if resolving a unique constraint changes the primary key value, you can inadvertently create orphaned foreign key records.
spock.conflict_resolution
spock.conflict_resolution sets the resolution method for any detected
conflicts between local data and incoming changes. The only supported value
in current Spock releases is:
last_update_wins(the default) - the version of data with the newest commit timestamp will be kept (this can be either the local or the remote version).
To enable conflict resolution, the track_commit_timestamp setting must be
enabled.
spock.deny_all_ddl
spock.deny_all_ddl is a boolean value (the default is false) that
enables or disables the execution of DDL statements within a Spock
configured cluster. This option can be set at postmaster startup, with the
SIGHUP mechanism, or on the command line with SQL if you’re a superuser.
spock.enable_ddl_replication
spock.enable_ddl_replication enables
automatic replication of ddl statements through
the default replication set.
spock.exception_behaviour
Use this GUC to specify the commit behavior of Postgres when it encounters an ERROR within a transaction:
transdiscard(the default) - setspock.exception_behaviourtotransdiscardto instruct the server to discard a transaction if any operation within that transaction returns anERROR.discard- setspock.exception_behaviourtodiscardto continue processing (and replicating) without interrupting server use; the server will commit any operation (any portion of a transaction) that does not return anERRORstatement.sub_disable- setspock.exception_behaviourtosub_disableto disable the subscription for the node on which the exception was reported; transactions for the disabled node will be added to a queue that is written to the WAL log file; when the subscription is enabled, replication will resume with the transaction that caused the exception, followed by the other queued transactions; you can use thespock.sub_alter_skiplsnfunction to skip the transaction that caused the exception and resume processing with the next transaction in the queue.
Note that the value you choose for spock.exception_behaviour could
potentially result in a large WAL log if transactions are allowed to
accumulate.
spock.event_history_size
spock.event_history_size sets how many recent events the spock.events
view keeps in shared memory. Once the history is full the oldest event is
dropped for each new one. The parameter accepts values from 16 to
1048576 (the default is 1024) and can only be set when the postmaster
starts.
spock.exception_logging
Use this GUC to specify which operations or transactions are written to the exception log table:
all(the default) - setspock.exception_loggingtoallto instruct the server to record all transactions that contain one or more failed operations in thespock.exception_logtable; note that this setting will log all operations that are part of a transaction if one operation fails.discard- add a row to thespock.exception_logtable for any discarded operation; successful transactions are not logged.none- instructs the server to not log any operation or transactions to the exception log table.
spock.exception_replay_queue_size - DEPRECATED
This parameter will not be supported after version 5.X.
When Spock encounters a replication exception, it attempts to resolve the
exception by entering exception-handling mode, based on the value of
spock.exception_behaviour. Spock then writes any transaction up to a
default size of 4MB to memory, and the apply worker replays the
transaction from memory. This provides a massive speed and performance
increase in the handling of the vast majority of exceptions. The memory
size is configurable with spock.exception_replay_queue_size.
Now, Spock performs as specified by the
spock.exception_behaviour parameter.
spock.extra_connection_options
You can use the spock.extra_connection_options parameter in the
postgresql.conf file to assign connection options that apply to all
connections made by Spock. This can be a useful place to set up custom
keepalive options, etc.
spock defaults to enabling TCP keepalives to ensure that it notices when
the upstream server disappears unexpectedly. To disable them add
keepalives = 0 to spock.extra_connection_options.
wal_sender_timeout
For Spock replication, set wal_sender_timeout to a conservative value such
as 5min (300000ms) on each node in postgresql.conf:
The default PostgreSQL value of 60s can cause spurious disconnects when
the subscriber is busy applying a large transaction and cannot send feedback
in time. A higher value gives the apply worker enough headroom while still
detecting truly dead connections. Liveness detection is primarily handled by
TCP keepalives, and spock.apply_idle_timeout provides an additional
subscriber-side safety net.
spock.apply_idle_timeout
Maximum idle time (in seconds) before the apply worker reconnects to the
provider. This acts as a safety net for detecting a hung walsender that keeps
the TCP connection alive but stops sending data. The timer resets on any
received message. Set to 0 to disable and rely solely on TCP keepalive for
liveness detection. Default: 300 (5 minutes).
spock.sync_timeout
Overrides the time (in seconds) budgeted for a single synchronisation wait in
the node management routines - waiting for a sync event to arrive on a peer,
waiting for a node to catch up, or waiting for a subscription to start
replicating. Default: 0, meaning each routine keeps its own built-in limit
(3 minutes). Only a positive value takes effect, so leaving this unset
preserves the behaviour those routines have always had.
Raise it on large databases. The built-in limits are sized for small clusters, where a node joins in seconds; when catchup legitimately takes minutes or hours, the routines fail with a timeout long before the work is done. It can be raised for a single operation rather than cluster-wide:
This bounds a whole wait, not an individual probe of a remote node. Routines that additionally bound each remote probe - so that one unresponsive peer cannot consume the entire budget - keep their own, much smaller limit for that purpose.
spock.read_retry_count
Number of times the apply worker re-reads the local relation when a row
targeted by a remote UPDATE or DELETE is not yet visible. On each retry
the apply worker waits for any concurrently-applying transaction to finish
and then searches the local relation again. If the row is still missing
after the configured number of retries, the apply worker falls through to
the standard row-missing handling path (conflict resolution and/or the
exception handler, depending on the configured
spock.exception_behaviour).
Set to 0 to disable retries entirely (the row-missing path runs
immediately). Valid range is 0 to 100. Default: 5. Changes take
effect on SIGHUP (for example, SELECT pg_reload_conf()); a server
restart is not required.
Logical Slot Failover (HA Standby)
Spock creates logical replication slots on each provider node. For high availability with a physical standby, these slots must be synchronized to the standby so that replication can resume without data loss after a failover.
See Logical Slot Failover for full setup
instructions, including a runbook step for clearing
synchronized_standby_slots on the promoted node after a failover.
The behaviour depends on the PostgreSQL version:
| PostgreSQL | Slot sync mechanism | Spock worker |
|---|---|---|
| 15, 16 | Spock built-in spock_failover_slots worker | Runs on every node |
| 17 | Spock worker OR native sync_replication_slots | Spock worker yields to native if enabled |
| 18+ | Native sync_replication_slots (required) | Not registered |
Whichever mechanism applies, a slot sync worker is present on every node, primary and standby alike, so include one in the worker budget - see Sizing Postgres Resources for Spock.
PostgreSQL 17 and Later (Native Slot Sync)
On PostgreSQL 17+, Spock marks every logical slot with the FAILOVER flag
at creation time. PostgreSQL’s built-in slotsync worker then synchronizes
those slots automatically.
On PostgreSQL 17, Spock’s worker only yields to native slotsync when you
set sync_replication_slots = on (below). On PostgreSQL 18+, Spock’s own
failover worker is not registered, so the native mechanism is required.
Either way, PostgreSQL’s own slot synchronization must be configured. To
switch a PostgreSQL 17 standby that Spock’s worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker;
setting sync_replication_slots = on alone is not enough.
First create the physical replication slot on the primary. The standby streams
through it, and its catalog_xmin (fed back via hot_standby_feedback) is what
protects the synchronized logical slots from being invalidated:
Primary (postgresql.conf):
Standby (postgresql.conf):
Only logical slots created with failover = true are synchronized. Spock 6.0.0
sets that flag when it creates a slot, and the upgrade from 5.x sets it on
existing slots; see
Upgrading Spock to 6.0.0
for any it skips.
After a failover, subscribers only need to update their host= in the
connection string — replication resumes from the last synchronized LSN with
no data loss. However, if the promoted node has
synchronized_standby_slots set, you must clear or update it first —
otherwise its walsenders wait forever on the now-orphaned physical slot(s) and
logical replication to subscribers freezes. See the
runbook in Logical Slot Failover
for when this applies and the exact steps.
PostgreSQL 15, 16, and 17 (Spock Built-in Worker)
On PostgreSQL 15, 16, and 17, Spock’s spock_failover_slots background worker
handles slot synchronization. On PostgreSQL 17 it yields to the native
slotsync worker when sync_replication_slots = on is enabled. Configure it
with the GUCs below.
spock.synchronize_slot_names
List of slot name patterns to synchronize from primary to physical standby.
Accepts name prefixes (name:foo) or LIKE patterns (name_like:spock%).
Default: name_like:%% (synchronize all logical slots).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled). On PostgreSQL 17 with native slotsync active, or on PostgreSQL 18+,
this setting is ignored.
spock.drop_extra_slots
When on (the default), the spock_failover_slots worker drops any slots
on the standby that do not match spock.synchronize_slot_names.
spock.primary_dsn
Connection string used by the spock_failover_slots worker to connect to
the primary and read slot state. If empty, primary_conninfo from
postgresql.conf is used.
spock.pg_standby_slot_names
Comma-separated list of physical replication slot names that must confirm durable flush of a given LSN before the walsender is allowed to replicate logical changes beyond that LSN. This prevents a physical standby from falling behind a logical subscriber.
Used on every supported PostgreSQL version, with or without native slot
sync. PostgreSQL’s own synchronized_standby_slots has no equivalent of
spock.standby_slots_min_confirmed: it waits for every slot it names, so
with it one standby that is down stops logical replication to every
subscriber. Use only one of them; setting both is redundant. For a failover slot
synchronized_standby_slots is applied first and waits for all of its
slots, so when it names every slot listed here this setting adds nothing,
and the walsender logs that; a slot listed only here still counts. A
listed slot that does not exist can never confirm: with the default -1
the walsender waits until wal_sender_timeout, logs a warning naming the
slot, and starts over, so after a promotion either create the slots on
the new primary or clear the setting there.
spock.standby_slots_min_confirmed
Number of slots from spock.pg_standby_slot_names that must confirm a
given LSN before logical replication is allowed to proceed. The default
-1 requires all listed slots to confirm. 0 disables the check.
With a value lower than the number of listed slots, subscribers can receive
changes that some standbys do not have yet. After a failure, promote the
standby with the highest pg_last_wal_receive_lsn(): it has every change
sent to a subscriber. Promoting a standby that is further behind leaves
subscribers with rows the new primary never had.
spock.failover_slots_naptime
How long the spock_failover_slots worker sleeps between slot-synchronization
passes, in milliseconds. A smaller value keeps the standby’s synchronized slots
closer to the primary — narrowing the window in which a promotion can find a
stale slot — at the cost of more frequent sync passes. Default: 1000 (1s).
Range: 1–3600000. Settable at runtime with SIGHUP (reload).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled) — the versions on which the built-in worker performs the sync.
spock.failover_slots_feedback_naptime
Shorter retry interval, in milliseconds, used instead of
spock.failover_slots_naptime while the standby has not yet received or fed
back the WAL a slot needs. Default: 10000 (10s). Range: 1–3600000.
Settable at runtime with SIGHUP (reload).
spock.failover_slots_recreate_invalidated
Whether the spock_failover_slots worker drops and recreates a synchronized
slot whose copy on the standby was invalidated, for example because the
standby removed WAL or the primary removed catalog rows the copy still
needed. Such a copy looks current but cannot serve a subscriber after a
promotion. With the default on, the worker reports it with a WARNING,
drops it and creates it again from the primary. The new copy stays a
temporary slot until the primary’s slot has caught up with it, while the
worker keeps synchronizing the other slots; if the standby is promoted
before then, the copy is dropped. A temporary copy belongs to the worker
process: if the worker exits for any reason, for example because the
primary is restarting and cannot be reached, the copy is dropped with it,
and the worker that the postmaster starts a minute later creates it again
at the standby’s position of that time, which the primary’s slot has to
pass again. If a temporary copy is invalidated while the worker holds it,
PostgreSQL terminates the worker to release the slot, with the same
effect. With off, the worker
leaves the copy as it is and reports it once, so it can be looked at
before anything is dropped; it is recreated on the first pass after the
setting is turned back on. Settable at runtime with SIGHUP (reload).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled). On PostgreSQL 17 with native slotsync active, or on PostgreSQL 18+,
this setting is ignored.
spock.failover_slots_database
The instructions below describe the 6.0.0-beta.2 snapshot. On the 5.0 maintenance branch, v5.0.15-rc.2 adds connection retries and shortens the worker restart delay to 15 seconds. See the 5.0.15 candidate notes and its configuration reference.
The database the spock_failover_slots worker connects to on the standby.
A synchronized slot copy holds the primary’s positions, but not the
snapshot the primary saved for the slot, which physical replication does
not carry. After a promotion, decoding from such a copy has to build a new
snapshot, and transactions that commit before it is consistent are never
sent to the subscriber. When this setting names a database, the worker
decodes each copy’s WAL on the standby, as PostgreSQL 17’s native slot sync
does, so the copy only points at positions where the standby has saved a
snapshot of its own. A new copy is made persistent only once that
snapshot is consistent. While a transaction older than a copy’s
restart_lsn is still open on the primary, decoding cannot reach a
consistent snapshot; the copy is reported once and left as it is until
the transaction ends, and the worker goes on with the other slots.
The check is off by default. While the setting is empty, every copy is synchronized without it, as in earlier releases, and is reported once (a WARNING on PostgreSQL 16 and 17, a LOG entry on 15); after a promotion, such a copy can still skip transactions the old primary committed shortly before the failover.
On PostgreSQL 16 this must be the database the synchronized slots belong
to, normally the Spock database. Copies in another database are
synchronized without the check, reported once with a WARNING, and carry
the same risk. The worker connects to one database only, so with Spock in
several databases on PostgreSQL 16, name the most important one; the
slots of the others are not protected. On PostgreSQL 17, any one database
covers the slots of every database. The standby also needs
wal_level = logical. PostgreSQL 15 cannot decode WAL on a standby, so
there the check is not available and each copy is noted once in the log
instead. Default: empty. Requires a restart.
On PostgreSQL 16 and 17 the worker stays connected to this database on
every node where the setting is present, including a primary, where it
otherwise sleeps, and a PostgreSQL 17 standby using native slot sync. As
with any open connection, DROP DATABASE, ALTER DATABASE ... RENAME and
CREATE DATABASE ... TEMPLATE on that database then fail. Stopping the
worker frees the database only until it restarts 60 seconds later; use
DROP DATABASE ... WITH (FORCE), or clear the setting and restart the
server. If connecting fails, for example because the database does not
exist, the worker reports it, carries on without the check, and does not
try again until the server is restarted. The same happens when the
database is dropped on the primary: replaying the drop on the standby ends
the worker, the restarted worker cannot connect to the database, and the
worker after that keeps synchronizing slots without the check.
The check is made on PostgreSQL 16 and 17 (when sync_replication_slots is
not enabled). On PostgreSQL 17 with native slot sync active, the worker still
connects but makes no check. On PostgreSQL 17, native slot sync is the
recommended setup; it gives every copy a consistent snapshot without this
setting. Turning on sync_replication_slots alone is not enough to switch:
native slot sync has further requirements and will not take over the copies
the Spock worker made, so until those are dropped most or all slots stop
being synchronized. See
Switching a PostgreSQL 17 standby from the Spock worker.
On PostgreSQL 15 and 18+, this setting is ignored.
On PostgreSQL 17, once the worker has taken over from native slot sync, a copy that native slot sync made is synchronized like any other, but a standby cannot drop it. If the primary drops that slot, the worker leaves the copy and reports it once; it is dropped on the promoted node.
spock.include_ddl_repset
spock.include_ddl_repset enables spock to automatically add tables to
replication sets at the time they are created on each node. Tables with
primary keys will be added to the default replication set, and tables
without primary keys will be added to the default_insert_only replication
set. Altering a table to add or remove a primary key will make the correct
adjustment to which replication set the table is part of. Setting a table to
unlogged will remove it from replication. Detaching a partition will not
remove it from replication.
spock.log_origin_change
spock.log_origin_change indicates whether changes to a row’s
origin should be logged to the PostgreSQL log. Rows may be being updated
locally by regular SQL operations, or by replication from apply workers.
Note that rows that are changed locally (not from replication) have the
origin value of 0. This is distinct from an unavailable or unknown origin:
a NULL value in spock.resolutions.local_origin, or unknown in
PostgreSQL logs, indicates that the origin metadata could not be determined
— it does not mean the change was local. For example:
The default of none is recommended because otherwise the amount of entries
may become numerous. The other options allow for monitoring when updates
occur outside expected patterns.
The following configuration values are possible:
none(the default) - do not log any origin change information.remote_only_differs- only log origin changes when the existing row was from one remote publisher and was changed by another remote publisher.since_sub_creation- log origin changes whether a publisher changed a row that was previously from another publisher or updated it locally, but only since the time when the subscription was created.
spock.log_verbosity
spock.log_verbosity controls the verbosity of Spock’s own debug log
output. Spock emits internal DEBUG1/DEBUG2 messages that are normally
silent, because PostgreSQL’s log_min_messages typically defaults to
warning. Lowering log_min_messages globally would surface those
messages, but it would also flood the log with unrelated PostgreSQL debug
output.
Instead, this setting promotes Spock’s own debug messages to LOG level
(which is written to the server log under any normal log_min_messages
setting), without changing log_min_messages. The value controls how much
detail is promoted:
normal(the default) - promote nothing; Spock’sDEBUG1/DEBUG2messages keep their native (normally silent) levels.debug1- promote Spock’sDEBUG1messages toLOG.debug2- promote both Spock’sDEBUG1andDEBUG2messages toLOG.
This option can be set by a superuser via SET, or reloaded with the
SIGHUP mechanism (for example, SELECT pg_reload_conf()); a server
restart is not required.
spock.non_conflicting_inserts
spock.non_conflicting_inserts is a boolean value (the default is off)
with which you assert that a replicated INSERT can never collide with a row
that already exists locally - because, for example, every node generates keys
from its own range.
Applying an INSERT normally costs two pieces of work that only a possible
collision justifies: a lookup for the conflicting local row, and a
speculative insertion that lets the unique indexes report a duplicate instead
of raising one. When this parameter is on, the apply worker skips both and
inserts the row directly.
Nothing checks the assertion. If a collision does occur, the index raises
duplicate key value violates unique constraint, the transaction is aborted,
and the outcome is decided by
spock.exception_behaviour - the row is not
resolved by spock.conflict_resolution and is not recorded in
spock.resolutions. Leave this parameter off unless collisions are
impossible by design rather than merely rare.
This option can only be set when the postmaster starts.
spock.save_resolutions
spock.save_resolutions is a boolean value (the default is false) that
logs all conflict resolutions to the spock.resolutions table. This option
can only be set when the postmaster starts.
spock.resolutions_retention_days
spock.resolutions_retention_days controls how long rows are kept in the
spock.resolutions table before the apply worker automatically deletes them.
The default is 100 days. Set to 0 to disable automatic cleanup entirely,
in which case rows accumulate indefinitely until removed manually.
This setting takes effect on pg_reload_conf() (no restart required).
spock.stats_max_entries
spock.stats_max_entries specifies the maximum number of entries that can
be stored into the Spock channel statistic. This option can only be set when
the postmaster starts. The parameter accepts values from -1 to INT_MAX
(the default is -1).
spock.temp_directory
spock.temp_directory defines the system path where temporary files needed
for schema synchronization are written. This path needs to exist and be
writable by the user running Postgres. The default is empty, which tells
Spock to use the default temporary directory based on environment or
operating system settings.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6 - Managing a Spock Installation
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension is a powerful addition to any PostgreSQL installation; management features of the Spock extension allow you to seamlessly:
- replicate partitioned tables.
- create logical row-based data filters.
- set a cluster to READ-ONLY mode; this restricts non-superusers to read-only operations, while superusers can still perform both read and write operations.
- use a trigger to manage replication set membership.
- use Snowflake sequences for sequence management in a distributed cluster.
- use the Lolor extension to replicate large objects.
- enable automatic DDL replication.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.1 - Automatic DDL Replication
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock extension can automatically replicate DDL statements. To enable
automatic DDL replication, set the following parameters to on:
spock.enable_ddl_replicationenables replication of ddl statements through the default replication set. Some DDL statements are intentionally not replicated (likeCREATE DATABASE). Other DDL statements are replicated, but can lead to replication issues (like theCREATE TABLE... AS...statement). In the case ofCREATE TABLE... AS..., the DDL statement is replicated before the table is added to the replication set, leading to potential data irregularities. Some DDL statements are replicated, but might potentially create an issue in a 3+ node cluster (ie.DROP TABLE).spock.include_ddl_repsetenables spock to automatically add tables to replication sets at the time they are created on each node. Tables with Primary Keys will be added to thedefaultreplication set, and tables without Primary Keys will be added to thedefault_insert_onlyreplication set. Altering a table to add or remove a primary key will also modify which replication set the table is a member of. Setting a table tounloggedremoves the table from replication. Detaching a partition will not remove a table from replication.spock.allow_ddl_from_functionsenables spock to automatically replicate DDL statements that are called within functions. Setspock.allow_ddl_from_functionstooffif each function is expected to execute on every node. When set tooff, statements replicated from functions adhere to the same rule described forinclude_ddl_repset. If a table possesses a primary key, it will be added into thedefaultreplication set; alternatively, they will be added to thedefault_insert_onlyreplication set.
To completely block all DDL across the cluster (including DDL that would otherwise be replicated automatically), use:
spock.deny_all_ddl- a boolean value, defaultfalse. When set totrue, Spock rejects any DDL statement executed on the node. This is useful as a guard during sensitive maintenance windows or while a node is being added or repaired. The setting can be changed by a superuser at runtime (PGC_SUSET); a server reload is not required.
It’s best to set these parameters to on only when the database schema
matches exactly on all nodes - either when all databases have no objects, or
when all databases have exactly the same objects and all tables are added to
replication sets.
You can also use the spock.replicate_ddl() function to instruct Spock
to enable automatic DDL replication. Starting automatic DDL replication
with this function instructs Spock to check the statement type of each
transaction, and execute and replicate statements identified as DDL.
During the auto replication process, spock generates messages that provide information about the execution. Here are the descriptions for each message:
DDL statement replicated.This message is an INFO level message. It is displayed whenever a DDL statement is successfully replicated. To include these messages in the server log files, the configuration must have
log_min_messages=INFOset.DDL statement replicated, but could be unsafe.This message serves as a warning. It is generated when certain DDL statements, though successfully replicated, are deemed potentially unsafe. For example, statements like
CREATE TABLE... AS...will trigger this warning.This DDL statement will not be replicated.This warning message is generated when auto replication is active, but the specific DDL is either unsupported or intentionally excluded from replication.
table 'test' was added to default replication set.This is a LOG message providing information about the replication set used for a given table when
spock.include_ddl_repsetis set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.2 - Automatically Assigning Tables to Replication Sets
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Automatic DDL replication is a great alternative to using a trigger to manage replication sets, but if you do need to dynamically modify replication rules, column or row filters, or partition filters, this trigger might be useful. This trigger does not replicate the DDL statements across nodes, but automatically adds newly created tables to a replication set on the node on which the trigger fires.
Before using the trigger, you should modify this trigger to account for all
flavors of CREATE TABLE statements you might run. Since the trigger
executes in a transaction, if the code in the trigger fails, the transaction
is rolled back, including any CREATE TABLE statements that caused the
trigger to fire. This means that statements like CREATE UNLOGGED TABLE will
fail if the trigger fails.
Please note that you must ensure that while using the trigger, automatic replication of DDL commands is disabled. You can use the following commands on the PSQL command line to disable automatic DDL updates:
You can use the event trigger facility to describe rules that define replication sets for newly created tables. For example:
The code snippet shown above adds any new table created in the config
schema into a replication set named configuration, and adds all other new
tables (which are not created by extensions) to the default replication
set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.3 - Filtering
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock allows row based filtering on both the provider side and the subscriber side.
Row Filtering on the Provider
On the provider, you can implement row filtering with the row_filter
property of the spock.repset_add_table function. The row_filter is a
normal PostgreSQL expression with the same limitations as the CHECK
constraint.
A simple row_filter would look something like row_filter := 'id > 0';
this filter ensures that only rows where values of id column is greater
than zero are replicated.
You can use a volatile function inside row_filter but use caution with
regard to writes as any expression that will do writes could potentially
throw an error and stop replication.
It’s worth noting that the row_filter is running inside the
replication session, so session specific expressions such as CURRENT_USER
will have the values of the replication session and not the session that did
the writes.
Row Filtering on the Subscriber
On the subscriber, row-based filtering can be implemented using the standard
BEFORE TRIGGER mechanism. You must mark triggers as either ENABLE REPLICA
or ENABLE ALWAYS or they will not be executed by the replication
process.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.4 - Replicating Partitioned Tables
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
By default, when you add a partitioned table to a Spock replication set,
Spock will include all the current partitions of a partitioned table. If you
partition a table, or add partitions to a partitioned table at a later date,
you will need to use the
spock.repset_add_partition
function to add them to your replication sets. The DDL for the partitioned
table and partitions must reside on the subscriber nodes (like a
non-partitioned table).
When you remove a partitioned table from a replication set, by default, the
partitions of the table will also be removed. You should use
spock.repset_remove_partition
to update the cluster’s meta-data.
Replication of partitioned tables is a bit different from normal tables. During an initial synchronization, we query the partitioned table (or parent) to get all the rows for synchronization purposes and don’t synchronize the individual partitions. After the initial sync of data, the normal operations resume and the partitions start replicating like normal tables.
If you add individual partitions to a replication set, they will be replicated like regular tables (to the table of the same name as the partition on each subscriber). This has performance advantages if your partitioning definition is the same on both provider and subscriber, as the partitioning logic does not have to be executed with each sync.
During the initial cluster setup and sync, table partitions are not
synced directly. Instead, the parent table is synced with the source
with data from all partitions, and the partitions are populated properly
on the destination preserving the table structure. This partitioning
behavior is equivalent to setting synchronize_data = false for
individual partitions during the initial sync.
When setup completes (after the initial sync), both the parent table and partitions are monitored for modifications, and changes are replicated as they are made.
When partitions are replicated through a partitioned table, TRUNCATE
commands always replicate to the complete list of affected tables or
partitions.
You can use a row_filter clause with a partitioned table, as well as
with individual partitions.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.5 - Using LOLOR to Manage Large objects
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
PostgreSQL’s logical decoding facility does not support decoding changes to large objects; we recommend instead using the LOLOR extension to manage large objects.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.6 - Using Spock in Read-Only Mode
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock supports operating a node in read-only mode. Read-only status is managed using a GUC parameter named spock.readonly, which can be set to one of three values:
| Value | Description |
|---|---|
off | No restrictions. All users may write. This is the default. |
local | Non-superuser local sessions are read-only. Replicated writes from apply workers are still permitted, so inbound replication continues normally. Superusers may still perform write operations. (The legacy alias user is accepted for backward compatibility.) |
all | Non-superuser local sessions and apply workers are blocked from writing. Superusers may still perform write operations. Use this mode when you need to stop both local application writes and inbound replication. |
The setting is at cluster level: either all databases are read-only or all databases are read-write (the usual setting).
Read-only mode is enforced by setting PostgreSQL’s transaction_read_only flag for affected sessions. This means that any statement that would modify data — including DML (INSERT, UPDATE, DELETE), DDL, TRUNCATE, and DCL (GRANT, REVOKE) — will be rejected by PostgreSQL’s standard read-only transaction checks.
The databases are in read-only mode at the SQL level: however, the checkpointer, background writer, walwriter, and the autovacuum launcher are still running. This means that the database files are not read-only and that in some cases the database may still write to disk.
Setting Read-Only Mode
Only a superuser can modify the spock.readonly parameter. The value can be changed using the ALTER SYSTEM command:
To set the mode for the current session only:
To query the current status:
Superuser writes and outbound replication
In both local and all modes, superusers are exempt from the read-only
restriction and may perform write operations. The readonly setting has no
effect on the walsender (outbound replication). Any writes made by a
superuser are captured in WAL and will be replicated outbound to other nodes
in the cluster, regardless of the readonly mode.
To perform repair operations that should not replicate to other nodes, use
spock.repair_mode() to suppress outbound
replication of DML/DDL statements:
Behavior of all mode
In all mode, apply workers detect the setting and stop consuming inbound
WAL — internally each worker raises a FATAL and exits, and the manager
restarts it once read-only is cleared. When the mode is switched back to
off or local, replication resumes from where it left off, provided
the upstream replication slot still retains the necessary WAL. Plan for
slot retention (max_slot_wal_keep_size, disk capacity) before placing a
node in all mode for an extended period; if the upstream slot is
recycled while the node is read-only, replication cannot resume from the
prior position and the node will need to be re-synchronized.
Notes:
- Only superusers can set and unset the
spock.readonlyparameter. - By using a GUC parameter, you can easily manage the node’s read-only status through standard PostgreSQL configuration mechanisms.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.6.7 - Using Spock with Snowflake Sequences
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Snowflake extension
provides a sequence-based unique ID solution to replace the Postgres
built-in bigserial data type in distributed replication clusters.
Snowflake sequences minimize the risk of assigning an identical key
value on different nodes at the same time; this prevents potential data
conflicts.
Spock strongly recommends using Snowflake sequences instead of legacy Postgres sequences. Snowflake sequences alleviate concerns that network lag could disrupt sequences in distributed transactions.
Using a Snowflake sequence
allows you to take full advantage of the benefits offered by a
distributed, multi-master replication solution. Snowflake provides an
int8 and sequence-based unique ID solution to optionally replace the
Postgres built-in bigserial data type.
Comparing Sequence Types
The following example compares the level of detail stored with a
traditional Postgres sequence (id values 1 and 2) versus the
level of detail available with a Snowflake sequence (id values
135824181823537153 and 135824609030176769):
The table preserves upstream output. With the v2.6.1 bit layout, the two larger IDs both encode node 0 and count 1. Snowflake functions
Snowflake Sequence Structure
Unlike Postgres sequences, a Snowflake sequence consists of a timestamp, a counter, and a unique node identifier; the structure ensures over 18 trillion unique sequence numbers. Snowflake sequences provide the following capabilities:
- A Snowflake sequence lets you add or modify data in different regions while ensuring a unique transaction sequence.
- A Snowflake sequence preserves unique transaction identifiers without manual administrative management of a numbering scheme.
- A Snowflake sequence lets you compare ID generation times across nodes. Clock skew and the interval between ID generation and commit can affect the observed order.
Internally, Snowflake sequences are 64-bit integers represented
externally as bigint values. The 64 bits divide into the following
bit fields:
- Bit 63 is unused and represents the sign of
int8. - Bits 22–62 store the timestamp with millisecond precision.
- Bits 12–21 store the unique pgEdge Distributed Postgres node number.
- Bits 0–11 store the counter within one millisecond.
The timestamp is a 41-bit unsigned value representing millisecond
precision with an epoch of 2023-01-01. The counter is a 12-bit
unsigned value that increments per ID allocation; this provides 4096
unique IDs per millisecond, or 4 million IDs per second. The node
number is a 10-bit unique identifier for the Postgres instance inside
a global cluster; you set this value using the snowflake.node GUC
in the postgresql.conf file.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7 - Adding a Node to a Replicating Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
There are several tools and scripts you can use to add a node to a cluster; the way that you choose should depend on the use and state of your cluster:
- Use Z0DAN to Add or Remove a Node with Zero Downtime
Z0DAN is a spock utility that provides scripts that you can use to seamlessly add or remove a node from your cluster with zero downtime.
- Use pgBackRest to Add a Node to a Replicating Cluster with Minimal Downtime
pgBackRest is an open-source tool that you can use to add a node to a replicating cluster with minimal interruption.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.1 - Modifying a Cluster with Zodan
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan provides tools to add or remove a node with zero downtime. The scripts are located in the samples/Z0DAN directory of the Spock GitHub repository.
During node addition, Zodan seamlessly manages creation of the new node, subscription management (both to and from the node), replication slot creation, data synchronization, replication slot advancement, and final activation of subscriptions.
During node removal, Zodan simplifies removing fully-functional or failed nodes from a cluster. When you remove a node from a cluster, the removal does not delete Postgres artifacts (the database, data directory, log files, etc.).
Zodan simplifies removing partially added nodes created during failed node add operations. Additional cleanup steps may be required before attempting another node deployment on the target host.
Each script must be run from the target node being added or removed.
Key Differences Between using Zodan and the Manual Process
The following differences highlight how Zodan automates and simplifies node addition:
Zodan stores sync LSNs and uses them later to ensure subscriptions start from the correct point even if hours pass between steps.
Zodan automatically detects existing schemas on the new node and populates the
skip_schemaparameter, preventing conflicts during structure sync.Zodan checks Spock versions before starting. Every node must be 5.0.9 or later, and the new node must run the same or a newer major.minor version than every existing node (patch levels may differ). So a 6.0.x node can join a 5.0.x cluster, and further 6.0.x nodes can join the resulting mixed cluster from any source node; a new node older than an existing node is rejected.
Zodan includes the
verify_subscription_replicating()function after enabling subscriptions to ensure they reach replicating status.When adding to a single-node cluster, Zodan handles the process differently — no disabled subscriptions are needed.
Zodan shows final status of all nodes and subscriptions across the entire cluster, not just the new node.
For more information, review the following resources:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.1.1 - Tutorial: Adding a Node to a Cluster with Zero Downtime
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
In this detailed walkthrough, we add a fourth node to a three-node cluster
with zero downtime. In our example, the cluster nodes are n1 (the source
node), n2, n3, and the new node is n4.
Important Prerequisites and Warnings
- The new node should not be accessible to users while adding the node.
- Disable
auto_ddlon all cluster nodes. - Do not modify your DDL during node addition.
- The users must be identical on the source and target node. You must create any users on the target node before proceeding; the permissions must be identical for all users on both the source and target nodes.
- The ZODAN process validates that all users from the source node exist on the new node before proceeding with cluster addition. This prevents replication failures caused by missing user permissions.
- The Spock configuration must be identical on both the source and the target node.
- All nodes in your cluster must be available to Spock for the duration of the node addition.
- The procedure should be performed on the new node being added.
- The
dblinkextension must be installed on the node from which commands likeSELECT spock.add_node()are being run. - Prepare the new node to meet all of the prerequisites described here.
- If the process fails, do not immediately retry a command until you ensure that all artifacts created by the workflow have been removed.
- The automated
spock.add_node()procedure allows 180 seconds (3 minutes) for each wait for a sync event between nodes. If replication lag exceeds this window, the procedure will raise an exception. Ensure network latency and replication lag are within acceptable limits before starting, or raise the budget for the session withspock.sync_timeout, as described in Setting the Synchronisation Timeout below. When following the manual workflow below, you callspock.wait_for_sync_event()directly and supply your own timeout (the examples use 1200 seconds), so neither the default norspock.sync_timeoutapplies.
Creating a Node Manually
If you are not using spock.node_create to create the new node, you will
need to complete the following steps:
- Initialize the new node with
initdb. - Create a database.
- Create a database user.
- Follow the instructions at the GitHub repository to build and install Spock on the database.
- Add
spockto theshared_preload_librariesparameter in thepostgresql.conffile. - Restart the server to update the configuration.
- Use the
CREATE EXTENSION spockcommand to create the Spock extension.
Sample Configuration and New Node Creation Steps
In our example, the cluster configuration details include the following information:
- Database:
inventory - User:
pgedge - Password:
1safepassword - n1 (source): port 5432
- n2 (replica): port 5433
- n3 (replica): port 5434
- n4 (new node): port 5435
- Host: 127.0.0.1
The steps used to configure the new node (n4) include the following commands. The commands initialize the database and install Spock:
Using the Zodan Procedure to Add a Node
After creating the node, you can use Zodan scripts to simplify adding a node to a cluster.
To use the SQL script, connect to the new node that you wish to add to the
pgEdge cluster. In the following example, the psql command connects to the
new node:
Load the Zodan procedures with the following command:
Then, use spock.add_node() from the new node to create the node
definition. In the following example, the spock.add_node procedure adds node n4 to
the cluster:
The spock.add_node function executes the steps required to add a node to
the cluster; a detailed explanation of the steps performed follows below.
Should a problem occur during this process, you can source the
zodremove.sql script and call the spock.remove_node procedure to
remove the node or reverse partially completed steps. The
spock.remove_node procedure should be called on the node being removed.
Setting the Synchronisation Timeout
spock.add_node() waits at several points for the nodes to synchronise -
for a sync event to arrive on a peer, for the new node to catch up, and
for a subscription to start replicating. Each of those waits is allowed
180 seconds (3 minutes) by default, which is sized for a small cluster
where a node joins in seconds. On a large database, catchup can
legitimately take minutes or hours, and the procedure fails with a timeout
long before the work is done.
To raise the budget, set
spock.sync_timeout in the
same session, before calling the add_node procedure:
The new value applies to every synchronisation wait the procedure
performs, and it reverts when the session ends, so a long-running node
addition does not need a cluster-wide configuration change. To raise the
limit for every session, set the parameter in postgresql.conf instead.
The setting bounds a whole wait, not an individual probe of a remote node; steps that also bound each remote probe - so that one unresponsive peer cannot consume the entire budget - keep their own, much smaller limit for that purpose.
Manually Adding a Node to a Cluster
The steps that follow outline the process Zodan goes through
when adding a node. You can manually perform the same steps to add a node
to a cluster instead of using spock.add_node above.
Check the Spock Version Compatibility
Before starting the node addition, verify that all nodes (n1, n2, n3, and n4) are running the exact same version of Spock. This prevents compatibility issues during replication setup.
If any node has a different version, the process will abort with an error.
On the orchestrator node, check the Spock version with the following commands:
Validate Prerequisites
You should ensure that the new node is in good condition before adding the node to your replicating cluster.
Perform safety checks to ensure node n4 is a clean slate:
- The n4 node must have the database and Spock extension installed.
- The n4 node must have no user data or existing replication configuration.
- Verify that a node named n4 does not already exist in the cluster.
If any prerequisite fails, the process aborts to prevent conflicts.
Confirm that the Database Exists on n4
Try to connect to the database on n4. If this fails, the database does not exist and needs to be created first.
In the following example, the query checks whether the database exists on n4:
Confirm that n4 Has No User-Created Tables
The new node must be empty; there can be no user tables in user schemas (system tables and extension tables are acceptable). If user tables exist, ZODAN will abort because syncing would overwrite existing data.
In the following example, the query checks for user-created tables on n4:
Confirm that n4 Does Not Exist in the Cluster
Check if a node with the name n4 is already registered in the cluster. If the node exists, ZODAN aborts to prevent duplicate node names. The following example checks to see if n4 already exists in the cluster:
Confirm that n4 Contains No Subscriptions
In the following example, the query checks whether n4 has any existing subscriptions:
Confirm that n4 Contains No Replication Sets
In the following example, the query checks whether n4 has any replication sets:
Create a Replication Node on n4
After confirming the state of the new node, you can add the node to your cluster. In this step, you will create a Spock node object on n4:
- This registers n4 as a participant in the replication cluster.
- Think of this like giving n4 an ID badge that says “I’m part of this cluster now.”
After this step, n4 is visible in the spock.node table on all nodes.
Create a Node on n4
Using dblink, connect to n4 and run spock.node_create() to register
the node. The DSN tells other nodes how to connect to n4.
In the following example, the spock.node_create function registers n4 as
a cluster participant:
Confirm the Initial Node Count
In the following example, the query retrieves the current node count:
Create Disabled Subscriptions and Slots
This is the critical bookmarking stage. During this stage, the process completes the following steps:
- Create subscriptions from n2 to n4 and n3 to n4, but keep them disabled.
- Before creating each subscription, trigger a
sync_event()which returns an LSN (log sequence number). You can think of the LSN as a bookmark in the replication stream. - Save these bookmarks in a temporary table for later use.
- When enabling these subscriptions later, transactions will start from exactly the right position. This ensures no data is missed or duplicated.
- Subscriptions remain disabled because n4 should get all initial data from n1 (the source) in one clean sync.
The n2 to n4 and n3 to n4 subscriptions are just being prepared now, but will not start moving data until later.
Identify All Existing Nodes
Query the cluster to find all of the nodes (n1, n2, n3, n4) and their connection strings. In the following example, the query retrieves all nodes and their DSNs:
For n2 to n4: Trigger Sync Event on n2 and Store LSN
Call sync_event() on n2, which inserts a special marker into the n2
replication stream and returns the LSN where the marker was inserted.
Store this LSN (0/1A7D1E0) in a temp table. Later, when enabling the
sub_n2_n4 subscription, use this stored LSN to ensure the subscription
starts from exactly this point, guaranteeing no data loss.
In the following example, commands trigger a sync event and store the LSN:
Create a Replication Slot on n2
A replication slot is like a queue that holds all changes from n2 that need to be sent to n4. Even though the subscription is disabled, the slot starts collecting changes immediately. This ensures no data is lost between now and when the subscription is enabled.
In the following example, the commands create a replication slot on n2:
Create Disabled Subscription on n4 from n2
We create the subscription object on n4, but with enabled := false.
This tells n4 you will eventually subscribe to n2, but not yet. The
subscription knows about the slot on n2 but is not actively pulling data
yet.
Repeat the Previous Steps for n3 to n4
In the following example, the commands perform the same operations for n3 to n4:
Configure Cross-Node Replication
A logical slot retains WAL on the node where it is created. The following historical examples connect to n2 and n3. Those slots retain changes on n2 and n3. Before allowing writes on n4, verify the slots on n4 that will serve its subscribers. The examples below do not establish that protection on n4.
Now prepare for replication directing the data flow from n4 to the replica nodes (n2, n3):
- Create replication slots on n2 and n3 that will hold changes from n4.
- These slots will be used later when creating subscriptions for n2 and n3 to receive data from n4.
- Create these slots early so they start buffering any changes from n4 immediately, even before the subscriptions are created.
This prevents data loss if n4 receives writes during the setup process.
Create a Slot on n2 for a Future Subscription (sub_n4_n2)
Create a replication slot on n2 named spk_inventory_n2_sub_n4_n2. This
slot will queue up changes from n4 that need to be sent to n2. The slot is
ready, but there is no subscription using the slot yet; that comes later.
In the following example, the command creates a replication slot on n2:
Create a Slot on n3 for a Future Subscription (sub_n4_n3)
In the following example, the command creates a replication slot on n3:
Trigger a Sync on Other Nodes, Wait on Source
Before copying data from n1 to n4, ensure n1 has all the latest data from n2 and n3.
- Any writes that happened on n2 or n3 must be fully replicated to n1 first.
- For example, if a user inserted data on n2 one second ago, that data must be on n1 before copying n1’s data to n4, or n4 would be missing that recent insert.
- By triggering a sync event on n2 and waiting for the event on n1, you can confirm that n1 has received everything from n2 up to this exact moment.
Process: Trigger sync_event on n2 (inserts a marker into the n2
replication stream), wait on n1 for that marker to arrive, and repeat
for n3.
Sync n2 to n1
Call the sync_event() function on n2, which returns an LSN (0/1C9F400).
Then on n1, wait for that specific LSN to be replicated. When
wait_for_sync_event() completes, you are guaranteed that n1 has received
all changes from n2 up to and including that LSN.
In the following example, the commands trigger a sync event and wait for completion:
Sync n3 to n1
Perform the same process on n3. Trigger sync_event() on n3, get the LSN
(0/1D0E510), and then wait for that LSN on n1. After both syncs complete,
n1 is fully caught up with both n2 and n3.
In the following example, the commands trigger a sync event on n3 and wait for completion on n1:
Copy the Source to New Subscription
This is the big data copy step.
- Create an enabled subscription on n4 from n1 with
synchronize_structure=trueandsynchronize_data=true. - This causes Spock to dump the entire schema (tables, indexes, constraints, etc.) from n1, restore that schema on n4, and copy all table data from n1 to n4.
- Before creating the subscription, detect if n4 has any existing schemas
that should be omitted from the sync (like monitoring tools, management
schemas). Build a
skip_schemaarray with these schema names. When Spock syncs the structure, Spock excludes these schemas usingpg_dump --exclude-schema. When copying data, Spock also skips tables in these schemas. This prevents overwriting local tools or extensions on n4.
This can take minutes to hours depending on database size (a 100GB database might take 30+ minutes to sync).
Detect Existing Schemas on n4
Query the n4 information_schema to find all user-created schemas
(excluding system schemas like pg_catalog, information_schema,
spock, public). If schemas like mgmt_tools or monitoring are
found, they will be excluded from replication.
In the following example, the query detects existing schemas on n4:
Create an Enabled Subscription on n4 from n1
Create a subscription (sub_n1_n4) on n4, pointing to n1 as the provider.
The key parameters include:
synchronize_structure := true- Dump and restore schema from n1.synchronize_data := true- Copy all table data from n1.enabled := true- Start replicating immediately.skip_schema := ARRAY['mgmt_tools','monitoring']::text[]- Exclude detected schemas.forward_origins := ARRAY[]::text[]- Do not forward changes that originated elsewhere.
What Spock does internally:
- Run pg_dump on n1 with –exclude-schema=mgmt_tools –exclude-schema=monitoring
- Restore dump on n4
- For each table in replication sets on n1: Skip tables in mgmt_tools and monitoring schemas → Run COPY command to transfer data from n1 to n4
- Once initial sync completes, start streaming ongoing changes from n1 to n4
Trigger a Sync on the Source Node and Wait on the New Node
After the initial bulk data copy, there might be a small lag to recover changes that happened on n1 while the copy was in progress.
- This confirms that n4 has caught up completely with n1 before proceeding.
- Trigger a
sync_eventon n1 (marking the current position in the n1 stream); then, wait on n4 for that marker to arrive. When the marker arrives, n4 has received and applied everything from n1 up to this point.
For example: You start copying 100GB at 10:00 AM, but while copying, users insert 1000 rows on n1 between 10:00-10:30. The copy completes at 10:30, but those 1000 rows are still being streamed. You must wait until all 1000 rows have been applied on n4 so you do not lose data.
Trigger a Sync Event on n1
Insert a sync marker into the n1 replication stream at the current position. The LSN returned (0/1E1F620) represents this exact moment in the n1 transaction log.
In the following example, the command triggers a sync event on n1:
Wait for Sync Event on n4
On n4, wait for the sync marker that matches the returned LSN (0/1E1F620)
to arrive and be processed. This is a blocking call; the call will not
return until the n4 subscription from n1 has replicated up to this LSN.
The timeout (1200 seconds = 20 minutes) is a value chosen for this manual
example to give plenty of headroom; tune it to suit your environment. It
prevents waiting forever if something goes wrong. (The automated
spock.add_node() procedure uses a shorter 180-second internal timeout
for its sync waits, as noted in the prerequisites.)
In the following example, the command waits for the sync event on n4:
Check the Commit Timestamp and Advance Slots
This is a critical optimization step.
Earlier, n4 received a full copy of all data from n1, which includes data that originally came from n2 and n3. Those nodes now have disabled subscriptions waiting to activate (sub_n2_n4 and sub_n3_n4). The replication slots on n2 and n3 have been buffering changes.
If you enable those subscriptions now, n4 will receive duplicate data (n4 already has n2’s data via n1, then will get the data again directly from n2).
Solution: Use the lag_tracker to find the exact timestamp when n4 last
received data from n2 (even though the data came via n1). Then advance the
n2 replication slot to skip past all data up to that timestamp. When
enabling sub_n2_n4 later, the subscription only sends new changes that
happened after the sync, not old data that n4 already has.
Steps for each replica node: Check the n4 lag_tracker to get the
commit_timestamp for the last change from n2. On n2, convert that
timestamp to an LSN using get_lsn_from_commit_ts(). Then, advance
the n2 replication slot to that LSN. Repeat these steps for n3.
Get the Commit Timestamp for n2 to n4
Query the n4 lag_tracker table, which tracks replication progress to
find the row where origin_name='n2' and receiver_name='n4'. The
commit_timestamp tells us the last time n4 received a change that
originated from n2. Even though the change came through n1, lag_tracker
tracks the original source.
In the following example, the query retrieves the commit timestamp:
Advance the Slot on n2
This is a two-step process: Use spock.get_lsn_from_commit_ts() to
convert the timestamp (2025-01-15 10:30:45.123456) into an LSN that
corresponds to that point in the n2 transaction log. Then, use
pg_replication_slot_advance() to move the slot’s restart_lsn forward
to that position.
The slot spk_inventory_n2_sub_n2_n4 has been buffering all changes to
n2. By advancing the slot, you discard everything up to this LSN (n4
already has the data). Now the slot only contains new changes that n4
needs.
In the following example, the commands convert the timestamp and advance the slot:
Repeat for n3 to n4
In the following example, the commands perform the same operations for n3 to n4:
Enable Disabled Subscriptions
In this step, activate subscriptions from replica nodes to new node using stored sync LSNs.
Remember when you created disabled subscriptions and stored sync LSNs? Now we bring it all together. Enable those subscriptions (sub_n2_n4 and sub_n3_n4), and use the stored LSNs to verify they start from the correct position.
Why the stored LSNs matter: When you created sub_n2_n4 and triggered
sync_event on n2, you got LSN 0/1A7D1E0. That LSN marked the exact
moment you created the replication slot. Between then and now, hours may
have passed. The replication slot has been buffering changes, but you need
to ensure the subscription starts processing from that original bookmark
point, not skipping ahead.
The verification: After enabling each subscription, call
wait_for_sync_event() with the stored LSN. This confirms that the
subscription has processed up to at least that sync point before you
continue.
After the slot advancement: The slots were advanced to skip duplicate data. Now when you enable the subscriptions, they will only send new changes that happened after the initial sync, which is exactly what you want.
Enable sub_n2_n4 on n4
Next, call spock.sub_enable() on n4 to activate the subscription. The
subscription worker process starts, connects to n2, and begins pulling
changes from the replication slot.
The following example enables the subscription:
Wait for Stored Sync Event from n2
Then, retrieve the LSN we stored (0/1A7D1E0) and use the LSN in
the wait_for_sync_event() function. This is the key to the entire
ZODAN approach. We are verifying that the subscription has caught up to
the sync point we marked when we first set things up. This guarantees
data consistency.
In the following example, the query retrieves the stored LSN and waits for the sync event:
Verify the Subscription is Replicating
Check the subscription status using the sub_show_status() function. We
want to see status='replicating', which means the subscription worker
is active, connected to n2, and successfully applying changes. Any other
status (down, initializing) would indicate a problem.
The following example checks the subscription status on n4:
Repeat the Steps for sub_n3_n4
In the following example, commands enable the subscription and verify replication:
Create Subscriptions from Other Nodes to New Node
This step enables bidirectional replication from n4 to all other nodes.
Up to this point, data has been flowing TO n4 from other nodes. Now we set up the reverse paths. Data will flow FROM n4 TO other nodes. We create subscriptions on n1, n2, and n3 that subscribe FROM n4.
We waited until n4 was fully populated with data before allowing other nodes to subscribe to it. If we had created these subscriptions earlier, the other nodes would try to sync from an empty n4, which would cause problems.
These subscriptions have synchronize_structure=false and
synchronize_data=false because n1, n2, and n3 already have all the
data. We only want them to receive NEW changes that happen ON n4 from
now on, not copy existing data.
After this, the cluster is fully bidirectional:
- n1 sends to n4, n4 sends to n1
- n2 sends to n4, n4 sends to n2
- n3 sends to n4, n4 sends to n3
Create sub_n4_n1 on n1
Create a subscription ON n1 that points TO n4 as the provider. This is commonly misunderstood; the subscription is created on the RECEIVER node (n1), not the sender (n4). After this, any INSERT/UPDATE/DELETE that happens directly on n4 will replicate to n1.
The following example creates the subscription:
Create sub_n4_n2 on n2
This is the same concept. We create a subscription on n2 that pulls from n4. Now n2 will receive changes that happen on n4.
In the following example, the command creates the subscription on n2:
Create sub_n4_n3 on n3
The following command creates the subscription on n3:
Monitor Replication Lag
Next, we will verify that n4 is keeping up with n1.
We monitor the lag_tracker table on n4 to ensure replication from n1 is keeping up. The lag_tracker shows the time difference between when a transaction was committed on n1 and when the transaction was applied on n4.
If lag is growing (for example, 5 seconds, then 10 seconds, then 30 seconds), n4 cannot keep up with the write load from n1. This could indicate the following issues:
- Network bandwidth issues.
- n4 hardware is slower than n1.
- Long-running transactions blocking replication.
We want lag under 59 seconds, or lag_bytes=0 (meaning n4 has processed everything). If lag stays consistently low, n4 is successfully integrated.
The following example monitors replication lag:
Show All Nodes
Next, we will verify that all of the nodes are registered; the following query displays all registered nodes:
Show the Status of all Subscriptions
Next, we want to verify that all subscriptions are replicating. In the following example, the query displays subscription status across all nodes:
Verification
Next, we perform a series of tests to verify that the cluster is replicating between n1 and n4.
First, we create a test table and insert data:
Test Replication between n4 and n1
Next, we insert data on n4:
Then, verify replication on n1:
Our Final Cluster Topology
All nodes are now bidirectionally replicating:
- n1, n2, n3, and n4 are all bidirectionally connected.
- Total subscriptions: 12 (each node subscribes to 3 others).
Troubleshooting
The following sections share commands that can help diagnose issues you encounter while adding a node:
Subscription Status Stuck in ‘initializing’ or ‘down’
The following commands can help you identify places where a node is encountering issues with replication status:
Node Addition Fails with a Timeout
If spock.add_node() raises a timeout while waiting for a sync event or
for the new node to catch up, the node is likely larger than the default
3-minute budget allows for. Remove the partially added node with
spock.remove_node, then retry with a longer budget, as described in
Setting the Synchronisation
Timeout:
Use the lag query below to gauge how long catchup actually takes before choosing a value.
Replication Lag Too High
Use the following command to check replication lag on a subscribing node:
Slot Not Advancing
Use the following command to check the status of a replication slot:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.1.2 - Tutorial: Updating the Postgres Version with a Rolling Update
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan’s add_node and remove_node procedures move data between nodes
regardless of which PostgreSQL major version each node runs. Because
of this, the same node-replacement strategy used to roll a Spock
version forward also upgrades PostgreSQL itself. During the upgrade,
you:
- build a replacement node on the target PostgreSQL major version.
- add it to the cluster.
- confirm it is replicating.
- remove the node it replaces.
Since the replacement node is fully live and replicating before the node it replaces is removed, the cluster never drops below its optimal node count and the application sees no interruption - a true zero-downtime rolling upgrade of the PostgreSQL version. When a node also carries a physical standby for high availability, bootstrapping that standby and bringing it under Patroni folds into the same per-node loop, so high availability is preserved, before you move on to the next node.
In this tutorial, a three-node cluster running PostgreSQL 16 (n1,
n2, n3) rolls forward to PostgreSQL 18, becoming n1b, n2b, and
n3b in turn. If you are also moving to a newer Spock version in the
same rollout, the two upgrades combine in a single pass of
add/verify/remove per node.
Important Prerequisites and Warnings
- Each replacement node should not be accessible to users while it is being added.
- Disable automatic DDL replication on every node
(
spock.enable_ddl_replication = off), and do not run DDL on the cluster for the duration of the rollout. - The users must be identical on the source and the replacement node. Create any users on the replacement node before proceeding; permissions must be identical for all users on both the source and the replacement node.
- Zodan validates that all users from the source node exist on the replacement node before proceeding. This prevents replication failures caused by missing user permissions.
- All nodes in the cluster must be available to Spock for the duration of each add/remove step.
- Run each
add_nodeandremove_nodecall from the node being added or removed. - The
dblinkextension must be installed on the node from whichadd_nodeorremove_nodeis called. - On a node whose PostgreSQL build has the
output_plugin_librariesparameter (the patch versions in Checking PostgreSQL Version Compatibility Before Each Step and later), it must listspock_output, or logical decoding with Spock fails. On an older build the parameter does not exist and must not be set. - If a step fails partway, do not immediately retry. Confirm every artifact the workflow created has been removed first, as described in Troubleshooting below.
add_nodeallows 180 seconds for each wait for a sync event between nodes. If replication lag exceeds this window, the call raises an exception. Confirm network latency and replication lag are within acceptable limits before starting, or raise the budget for the session withspock.sync_timeout.- Do not remove an old node until its replacement reports
replicatingstatus. - Keep at least two nodes running at all times; never remove the second-to-last old node and the first new node in the same window.
- A rolling PostgreSQL update can only move a cluster forward. Unlike a Spock version mismatch, Zodan does not check PostgreSQL version ordering itself - see Checking PostgreSQL Version Compatibility Before Each Step.
The examples run every instance on one host and use 127.0.0.1.
When a node and its standby, or the nodes of the cluster, run on
separate hosts, use addresses each host can reach in connection
strings, listen and connect_address, and the etcd URLs, and
point every Patroni member of a scope at the same DCS. Replace the
<...> password placeholders with your own unique secrets.
Checking PostgreSQL Version Compatibility Before Each Step
Zodan’s check_spock_version_compatibility procedure (invoked
automatically by add_node) checks only the Spock extension version;
it does not check the PostgreSQL server version. Before adding
a replacement node, you can confirm its PostgreSQL patch version
number yourself against the source node:
The replacement node’s server_version_num must be the same as or
greater than the source node’s. The following table describes the
first patch version of each PostgreSQL major version that has the
output_plugin_libraries parameter. On those versions and later it
must list spock_output; on earlier ones leave it unset:
| PostgreSQL major version | Minimum patch version |
|---|---|
| 15 | 15.19 |
| 16 | 16.15 |
| 17 | 17.11 |
| 18 | 18.6 |
Preparing a Replacement Node
Each replacement node needs its own host (or port, on a single host),
data directory, and a PostgreSQL and Spock build at the target
version, prepared before you call add_node. Add the pgEdge
repository to the replacement node’s host and install pgEdge
Enterprise Postgres and Spock for the target version, as described in
Installing pgEdge Enterprise
Postgres.
For PostgreSQL 18 on RHEL, Rocky Linux, or AlmaLinux:
On Ubuntu or Debian:
In our example, the replacement node runs on its own port on the same
host as the node it replaces; n1b runs on port 5442. Initialize
its data directory on the target PostgreSQL version:
Before starting the replacement node for the first time, edit the
postgresql.conf file:
- set the settings Spock requires, as in Configuring Spock, using the source node’s values.
- size replication origin tracking for the target version.
shared_preload_libraries only takes effect when the server
starts, so set it now rather than after CREATE EXTENSION spock
has already run.
PostgreSQL 15 through 17 track replication origins with the
max_replication_slots parameter; PostgreSQL 18 and later uses the
max_active_replication_origins parameter. Set the parameter to the
number of subscriptions required:
Copy any spock.* settings the existing nodes use, such as the
conflict resolution settings, so the replacement behaves the same.
Without wal_level = logical, add_node cannot create the slots it
needs on the replacement, and it does not stop: it reports the failure
only as a notice, and only when called with verb := true.
Start Postgres on the replacement node’s port, then connect with
psql to confirm the settings took effect:
Create the database and user, matching the source node exactly:
Install the Spock extension built against the target PostgreSQL version:
If the node it replaces runs behind a physical standby for high
availability, and the replacement node’s target version is PostgreSQL
18 or later, also configure the server’s native
sync_replication_slots mechanism before adding it to the cluster -
Spock’s own failover worker does not run on PostgreSQL 18+. Both
approaches below need a replication role, a known superuser password,
and a pg_hba.conf entry permitting both to connect; set these up
once, on the replacement node, before choosing a path:
Add entries to /path/to/data/n1b/pg_hba.conf permitting the standby
host to open a replication connection and, if you choose the Patroni
path below, a superuser connection for Patroni’s own health checks:
Choose one of the following approaches:
Manage the standby pair through Patroni, as described in step 3 of Rolling the Update Across the Cluster below.
Configure the native path by hand:
Create a physical replication slot on the replacement node, for its future standby to stream through:
Take a base backup of the replacement node into the standby’s data directory, streaming through that slot:
standby.signalis what makes the server start as a standby;pg_basebackup -Rwould also write it, but it would put aprimary_conninfowithoutdbnameintopostgresql.auto.conf, which overrides the one set in the next steps, and slot sync needsdbname.Set
synchronized_standby_slotsin the replacement node’spostgresql.conf, naming that slot:On the standby itself, point it at the replacement node and enable native slot sync in its
postgresql.conf:After starting the standby, confirm the slot synchronized:
See Logical Slot Failover (HA Standby) for the full reference, including the PostgreSQL 15/16 path and upgrading existing slots.
Rolling the Update Across the Cluster
Repeat the following four steps once per node, moving from n1 to
n3 in our example. Finish all steps for one node before starting the
next.
Connect to the prepared replacement node and load the Zodan workflow:
NoteBoth
zodan.sqlandzodremove.sqlare located in the samples/Z0DAN directory of the Spock GitHub repository.Then add the replacement node, sourcing it from whichever node in the cluster is reachable and already caught up - the node you are replacing is the simplest choice for the first replacement:
Confirm the replacement node is fully caught up and replicating in both directions before touching the node it replaces:
Every subscription involving
n1bshould reportreplicating, including the subscriptions to and fromn2andn3thatadd_nodecreated automatically.If the node being retired runs behind a physical standby for high availability, build a matching standby for
n1band bring the pair under Patroni, then cut over to it. Skip this step if the cluster does not use physical standbys.Patroni and a DCS (Distributed Configuration Store) must be installed and reachable from
n1band its future standby host before either node can run under Patroni. This tutorial usesetcdas the DCS, the most common choice for Patroni. Install Patroni on both hosts:This installs Patroni’s etcd client library, not the etcd server itself. If no etcd cluster already serves the rest of your Spock cluster’s Patroni pairs, install and start one. Package name and installation method vary by platform; see the etcd releases page if your package manager does not provide one. A production etcd deployment needs an odd number of members (3 or 5) for quorum; the following configures a single-member etcd suitable for this tutorial:
Confirm
n1band its standby host can reach the DCS before continuing:Bring
n1bunder Patroni as the leader of a new Patroni cluster, rather than letting Patroni bootstrap it from scratch -n1bis already initialized and already running with the dataadd_nodepopulated. Patroni only runs its bootstrap process against an emptydata_dir, so pointing it atn1b’s existing, populated directory makes Patroni adopt the running instance as the cluster’s first member instead:sync_replication_slotsandhot_standby_feedbackare the two settings the native slot sync path needs on a standby; set them on bothn1bandn1b_standbyrather than only on whichever is the standby today, since either one can end up in that role after a promotion.synchronized_standby_slotsis deliberately left out ofpostgresql.parametershere - it is set directly on whichever node is primary, by theon_role_changecallback below, and declaring it as a static Patroni-managed parameter would fight that callback: Patroni reconciles managed parameters back to the value in its own configuration, which would undo the callback’s update after every promotion.Start Patroni against the running instance:
Then point a second Patroni instance at the same
scopeand DCS endpoint, under the member namen1b_standby, with an emptydata_dir. Patroni finds the existing cluster in the DCS and, on first start, runspg_basebackupitself againstn1bto populate that empty directory - connecting as thereplicatorrole over the replication connection permitted by thepg_hba.confentry added above, using the credentials in theauthentication.replicationblock below. No manualpg_basebackupstep is needed on this path; Patroni’s bootstrap process runs it for you:Confirm
n1b_standbyjoined and is streaming before moving on:Also confirm, on
n1b, that the slot backing the standby has synced before relying on it for failover:synchronized_standby_slotsnames a Patroni-managed physical slot, and Patroni’s auto-created slots are named after the member, not the role - the slot namedn1b_standbyonly exists whilen1b_standbyis not the primary. Theon_role_changecallback named in both Patroni configurations above resets the setting on a future promotion to whichever member is then the standby. Patroni reads its local configuration only at start and on reload, so if you add the callback to a member that is already running, reload it afterwards:The following script, deployed on
n1bwithSIBLING_MEMBERset ton1b_standbyandLOCAL_PORTset to5442(and onn1b_standbywith them set ton1band5452), setssynchronized_standby_slotsto the other member’s name whenever this node becomes the primary:The callback only fires on a future promotion, so set the initial value by hand now, on
n1bwhile it is still the leader:With
n1b_standbystreaming and the callback in place on both nodes, cut over: repoint anything that depended on the old node’s standby - a VIP, a DNS record, or a connection string used for read traffic or disaster recovery - at the new Patroni cluster. Leave the old node’s standby running until the cutover is confirmed; step 4 removes the old primary, and its standby can be stopped once the rest of the cluster is healthy.A later promotion of
n1b_standbyis a separate event from this cutover, and needs its own plan: Spock’s subscriptions onn2andn3connect ton1busing the rawhost=127.0.0.1 port=5442address from theadd_nodecall above, and Patroni does not repoint that address for them. Ifn1bis reachable only through a VIP or DNS record that Patroni (orkeepalivedalongside it) moves to whichever member is primary, pointnew_node_dsnat that stable address instead of a node’s raw host and port when you calladd_node, and no further Spock-level action is needed after a promotion. Without such an abstraction in front of the pair, repoint each subscription by hand after a promotion, from any node whose subscription still points at the old address:node_add_interfacewrites only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, heren2andn3, sincesub_alter_interfacelooks the interface up locally:Then run
sub_alter_interfaceon each of those nodes:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1b_n2is the subscription onn2whose provider isn1b; confirm the exact names for your cluster withSELECT sub_name FROM spock.subscription;on each node before repointing them.Move application traffic from
n1ton1b, and confirm no new connections are arriving atn1.remove_nodedrops every subscription to and fromn1at once and does not wait for anything, so any write onn1that has not reached the other nodes by then is lost. Whenn1takes no writes, emit a sync event on it:Wait for it on every other node, passing the LSN it returned. The
resultcolumn must come backt:Then load the removal workflow on the node being retired, and remove it from the cluster:
remove_nodedoes not delete the retired node’s database, data directory, or logs; stop the instance and reclaim its resources once you confirm the rest of the cluster is healthy.
With n1 replaced by n1b, repeat steps 1 through 4 for n2 and
n3, sourcing each new node from any node already in the cluster -
old or new - that runs a PostgreSQL version no newer than the
replacement node itself.
Re-enabling DDL Replication
Once every node is replaced, turn automatic DDL replication back on, on every node, as in Upgrading Spock:
Verifying the Rollout
After replacing all nodes, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:
Run the dblink query once per node, changing the port.
show_all_nodes lists the nodes; show_all_subscription_status
reports each subscription’s status.
The following table describes what to check in the output before considering the rollout complete:
| Field | What to confirm |
|---|---|
| PostgreSQL version | Every node reports the target version. |
| Node name | Only n1b, n2b, and n3b remain; no old node is listed. |
| Subscription status | Every subscription between every pair of nodes reports replicating. |
Troubleshooting
add_nodefails withcannot synchronize structure from provider running PostgreSQL, or the replacement node’s apply worker exits withcannot synchronize structure from upstream server version. The replacement node’spg_dumpcannot dump from a PostgreSQL version newer than itself. The node named as the source runs a newer PostgreSQL major version than the replacement node. Rebuild the replacement node on an equal or newer PostgreSQL major version, or source it from a different node that is not newer than the replacement, and retry.Logical decoding fails with
library "spock_output" may not be used as an output plugin. The node’s build has theoutput_plugin_librariesparameter and it does not listspock_output. Add it topostgresql.confand runSELECT pg_reload_conf();; no restart is needed. Do not set the parameter on a build that does not have it: an unrecognized parameter stops the server from starting.add_nodereports that it could not create a replication slot. Checkwal_level = logicalandmax_replication_slotson the replacement node.add_nodereports a failed slot creation only as a notice, only withverb := true, and carries on; the subscriptions it then creates do not replicate.add_nodetimes out waiting for a sync event on a large database. Raise the wait budget for the session withspock.sync_timeoutbefore callingadd_nodeagain.A step fails partway through
add_node. Do not retry immediately. Sourcezodremove.sqland callspock.remove_node()on the partially added node first, to clear any subscriptions and slots it created, then retry the add.
For more information, review the following resources:
- Modifying a Cluster with Zodan
- Using Zodan Scripts and Workflows
- Tutorial: Adding a Node to a Cluster with Zero Downtime
- Logical Slot Failover (HA Standby)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.1.3 - Zodan: Zero-Downtime Node Addition for Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan provides tools to add or remove a node with zero downtime. The scripts are located in the samples/Z0DAN directory of the Spock GitHub repository.
Zodan’s workflows and scripts streamline the process of adding a node to or removing a node from a Spock cluster. Zodan features the following scripts and workflows:
- The zodan.sql workflow is a complete
SQL-based workflow that uses
dblinkto perform the same add node operations from within Postgres. - The zodremove.sql workflow is a complete
SQL-based workflow that uses
dblinkto perform the same removal operations from within Postgres.
Components
The following scripts and workflows are available via Zodan.
Using the zodan.sql SQL Workflow
The SQL-based implementation utilizes the Postgres dblink extension to
handle node addition directly from within the database. This method is
ideal for environments where you may not have access to a shell or Python.
Within the workflow, SQL commands orchestrate the following operations:
add_node- The main procedure to orchestrate the full workflow.create_node- Register the new node viaspock.node_create.get_spock_nodes- Fetch current node metadata from a remote node.create_subandenable_sub- Manage subscription creation and activation.create_replication_slot- Create and configure logical replication slots.sync_eventandwait_for_sync_event- Coordinate data synchronization events.get_commit_timestampandadvance_replication_slot- Align replication states.
To use the workflow, execute the following command in your Postgres
session. In the following example, the spock.add_node procedure adds a
new node to the cluster:
In the following example, the command adds node n4 to the cluster:
The zodremove.sql Workflow
The SQL-based implementation utilizes the Postgres dblink extension to
handle node removal directly from within the database. This method is
ideal for environments where you may not have access to a shell or Python.
Within the workflow, SQL commands orchestrate the following operations:
spock.remove_node- Main procedure to orchestrate the full workflow.spock.remove_node_subscriptions- Manages removing subscriptions. Also removes the replication slot if there are no remaining subscriptions.spock.remove_node_replication_sets- Removes published repsets on the node being removed.spock.remove_node_from_cluster_registry- Removes the node from the cluster.
The workflow is located in the samples/Z0DAN directory of the Spock GitHub repository.
To use the workflow, call a command from your Postgres session. In the
following example, the Z0DAN spock.remove_node procedure removes a node
from the cluster. Note that spock.remove_node is a Z0DAN utility
procedure provided by zodremove.sql; it is not a built-in function of
the Spock extension.
In the following example, the command removes node n4 from the cluster:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.2 - Adding a Node with pgBackRest
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can use a pgBackRest backup to populate a new cluster node, and then
add that node to your cluster with the Spock extension. In the following
high-level walkthrough, we walk through the steps you can use to add a
fourth node (n4) to a three-node cluster (n1, n2, and n3).
Create a pgBackRest stanza. This step is required as the stanza defines the cluster configuration, which is essential for backup and restore operations.
Perform a full backup of your primary node,
n1. The backup can be stored in an S3 bucket, a network-shared folder, or a local directory (if all nodes are on the same machine).Restore the backup from
n1to the data directory ofn4. This preparesn4to become a replica ofn1.Configure streaming replication on
n4, making the node a replica ofn1. This ensures thatn4contains all transactions onn1since the backup was taken, ensuringn4is 100 percent synchronized withn1.Use the
ALTERcommand to set nodesn1,n2, andn3to read-only mode and reload the configuration on these nodes to apply the changes. This step is crucial becausen4has configurations copied fromn1that are not valid forn4. By making the nodes read-only, you ensure no transactions occur while you modify the configurations.Terminate all ongoing transactions on
n1,n2, andn3. This prevents any long-running queries from interfering during the configuration changes.Edit the
shared_preload_librariesparameter onn4, removingspock. This prevents Spock from using the old configuration fromn1onn4.Start
n4, allowing the node to become a replica ofn1. This step ensures thatn4contains all transactions fromn1.Promote
n4to the role of primary node or configure the node as a standalone node with Spock disabled. This step finalizesn4as the new primary node in your replication setup.Remove all replication sets and nodes from the configuration. This clears any old replication configurations that are no longer needed.
Re-add
spockto theshared_preload_librariesparameter onn4. This preparesn4to handle replication in the new role.Restart
n4to apply the changes made in the previous steps.Reintegrate
n4into the replication cluster withn1,n2, andn3.Remove the read-only mode from
n1,n2, andn3, allowing them to resume normal operations.Add the following subscriptions between the new node (
n4) and Nodes 1, 2, and 3 (n1,n2,n3):- The
subn1n4subscription syncs n1 with n4. - The
subn2n4subscription syncs n2 with n4. - The
subn3n4subscription syncs n3 with n4. - The
subn4n1subscription syncs n4 with n1. - The
subn4n2subscription syncs n4 with n2. - The
subn4n3subscription syncs n4 with n3.
- The
Verify that all nodes (
n1,n2,n3, andn4) are properly configured and synchronized within the cluster. Ensure that replication is functioning as expected by checking the status of all nodes.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.7.3 - Tutorial: Upgrading the Postgres Version In Place with pg_upgrade
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
If your database is too large for your system’s free storage to hold
a second full copy, you can upgrade the node’s existing data directory
in place with pg_upgrade.
pg_upgrade migrates a node’s existing data directory to a new
PostgreSQL major version in place. Run with --link, it hard-links
the new cluster’s files to the old cluster’s rather than copying them.
This avoids doubling storage: the new data directory shares disk
blocks with the old one instead of duplicating them.
The trade-off is downtime for that one node. Unlike the rolling
replacement strategy, there is no freshly built node standing by to
take over its traffic while it upgrades - the node goes down, runs
pg_upgrade, and comes back up on the new version before it rejoins
the cluster. The upgrade is zero-downtime for the application only
because the other nodes in the cluster keep serving traffic during
that window; it is not zero-downtime for the node itself.
This tutorial upgrades a three-node cluster (n1, n2, n3) running
PostgreSQL 16 to PostgreSQL 18, one node at a time, without a second full copy
of any node’s data. pg_upgrade still needs a new, empty data directory for
each node, but in link mode it holds hard links to the old files rather than
copies of them. When a node also carries a physical standby for high
availability, rebuilding that standby and bringing it under Patroni folds into
the same per-node loop, so high availability is preserved before you move on to
the next node.
Prerequisites and Warnings
Important Prerequisites and Warnings
- The cluster needs at least three nodes. With one node down for its upgrade, at least two others must remain available to serve the application.
- Your load balancer, connection pooler, or application must be able to stop routing traffic to a node before it goes down for upgrade, and resume routing to it afterward. There is no replacement node to absorb that traffic automatically.
- Disable automatic DDL replication on every node
(
spock.enable_ddl_replication = off), and do not run DDL on the cluster for the duration of the rollout. pg_upgrade --linkrequires the old and new data directories to be on the same filesystem, so that hard links are possible. On a filesystem without hard links, or with the directories on separate volumes,pg_upgradestops withcould not create hard link between old and new data directories; it does not fall back to copying.--linkmode ties the old and new clusters’ data files together. After you start the new cluster, you cannot go back to running the old one; treat the oldpostgresql.conf,pg_hba.conf, and any other node-specific configuration as reference material to port forward, not something you can revert to.pg_upgradedoes not carry Spock’s replication origins over, on any PostgreSQL version. This procedure records them before the upgrade and restores them afterwards (steps 2 and 19), and drops and recreates the other nodes’ subscriptions to the node without copying data (steps 3 and 20).- While a node is down, the other nodes keep WAL for their
subscriptions to it. If
max_slot_wal_keep_sizeis set, make sure it allows for the whole upgrade window, or those slots can be invalidated and the node will need a full rebuild. spock.show_all_subscription_status()andspock.show_all_nodes()are Zodan procedures. Loadzodan.sqlfrom the Spock distribution, which needs thedblinkextension, on the node you run them from.- Run
pg_upgrade --checkagainst the node before running the real upgrade, and resolve everything it reports. - A node’s physical standby cannot continue streaming once the node’s major version changes; the standby must be rebuilt from the upgraded node, not upgraded in place alongside it.
The examples run every instance on one host and use 127.0.0.1.
When a node and its standby, or the nodes of the cluster, run on
separate hosts, use addresses each host can reach in connection
strings, listen and connect_address, and the etcd URLs, and
point every Patroni member of a scope at the same DCS. Replace the
<...> password placeholders with your own unique secrets.
Upgrading the Cluster with pg_upgrade
Repeat the following steps once per node, moving from n1 to n3 in
our example. Finish all steps for one node before starting the next.
Drain traffic from the node being upgraded at the load balancer, pooler, or application layer, and confirm no new connections are arriving at it.
Make sure every other node has applied everything
n1committed, and record what the upgrade will lose. With traffic drained, emit a sync event onn1:Wait for it on every other node, passing the LSN it returned. The
resultcolumn must come backt:Then confirm on
n1that every slot has confirmed past that LSN; this query must return no rows:A physical slot, such as the one a standby streams through, always has a
NULLconfirmed_flush_lsn, which is why the query is limited to logical slots.pg_upgradedoes not carry Spock’s replication origins over, so record where each ofn1’s subscriptions has applied up to. Every row must show an LSN; aNULLmeans a subscription with no origin, which you must resolve before upgrading:Also record, on every other node, the definition of its subscription to
n1, so you can recreate it unchanged in step 20:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1_n2is the subscription onn2whose provider isn1. Confirm the names for your cluster withSELECT sub_name FROM spock.subscription;on each node.Disable
n1’s own subscriptions, so it stops applying, and wait untilSELECT * FROM spock.sub_show_status();onn1no longer shows any asreplicating:While
n1is still running, drop every other node’s subscription to it.sub_dropremoves the subscription’s slot onn1only when it can reachn1; a subscription dropped later leaves its slot behind onn1. No data is lost, because step 2 confirmed that every node had applied all ofn1’s changes:If this node already runs under Patroni, pause it so that manually stopping PostgreSQL below does not trigger an automatic restart - Patroni’s own documentation names major-version upgrades as the intended use case for this mode.
--waitreturns only once every member has seen the pause, so the stop below cannot race it:Record the Spock version the node runs; step 4 needs it, and the server cannot answer once it is down:
Then stop PostgreSQL on the node:
Install the target PostgreSQL version and Spock on the host, alongside the existing installation; see Installing pgEdge Enterprise Postgres. For PostgreSQL 18 on RHEL, Rocky Linux, or AlmaLinux:
On Ubuntu or Debian:
pg_upgraderecreates the Spock extension in the new cluster at the version you recorded in step 3, and the new server loads the Spock library installed for the target PostgreSQL version. Install that same Spock version for the target version. If the only package for the target version carries a newer Spock, runALTER EXTENSION spock UPDATE;in every database where Spock is installed once the node is up in step 8, before step 19. The other nodes keep their version until their own turn, so the cluster runs mixed Spock versions while the rollout is in progress, as it does in the node-by-node procedure in Upgrading Spock. Finish the rollout on every node before adding a node with Zodan:add_noderequires the new node’s Spock version to be the same as or newer than every existing node’s.Initialize a new data directory on the target PostgreSQL version.
pg_upgrademigrates data into an already-initialized cluster; it does not create one. On a PostgreSQL 16 or later target,pg_upgradecopies the old cluster’s encoding and locale settings into the new cluster itself, soinitdbneeds no encoding or locale option. The data checksum setting is not copied and must match the old cluster, orpg_upgradestops. Read it from the stopped data directory:If the checksum version is
1, enable checksums:If it is
0, disable them explicitly. PostgreSQL 18initdbenables checksums by default, so leaving the option out does not match a cluster without them:pg_upgradedoes not carry configuration files forward; the new data directory has only the defaultsinitdbwrote. Configure it now, before step 6:pg_upgrade --checkreadswal_level,max_replication_slotsandoutput_plugin_librariesfrom the new cluster, and fails if they cannot hold the old cluster’s logical slots when the old cluster is PostgreSQL 17 or later. Copypg_hba.confas-is, since authentication rules do not change with the PostgreSQL version:Then add the Spock settings to the new data directory’s
postgresql.conf, using the old node’s values where they are larger.max_replication_slotsmust be at least the number of logical slots on the old node:output_plugin_librariesexists only from the patch versions in the table below. Set it only if the new binaries have it: on an older patch version the server does not recognize the parameter and will not start. Check withSELECT current_setting('output_plugin_libraries', true);, which returns NULL when the parameter does not exist. The following table describes the first patch version of each major version that has it:PostgreSQL major version Minimum patch version 15 15.19 16 16.15 17 17.11 18 18.6 Run
pg_upgrade --checkfirst, against the target version’s binaries, to confirm there are no blocking issues:Pass
--linkto the check too, so it also confirms hard links work between the two directories.Then run the upgrade itself, adding
--linkto hard-link the data files instead of copying them:Port any other settings the node needs from the old
postgresql.conf(memory, logging, connection limits and similar) to the new one before you start it. Do the same for the oldpostgresql.auto.conf, which holds everything set withALTER SYSTEM, and for any file the old configuration pulls in withinclude;pg_upgradecarries none of them over. Review each setting against the target version’s documentation rather than copying the files whole, since parameters are renamed or removed between major versions.Start PostgreSQL on the new version:
If this node runs behind a physical standby for high availability, stop it now - physical replication cannot continue once the primary’s major version changes. Skip steps 9 through 18 if the node does not use a physical standby.
Install the target PostgreSQL version on the standby’s host, alongside its existing installation, the same way you did for the primary in step 4.
Updating Patroni to use the Upgraded Instance
If this standby pair already runs under Patroni, you can reuse this node’s own existing Patroni cluster and the DCS (Distributed Configuration Store) behind it, rather than standing up either from scratch.
Optional: if this is the first time this node and its standby are being brought under Patroni, install Patroni and a DCS on both hosts first. This tutorial uses
etcdas the DCS, the most common choice for Patroni:This installs Patroni’s etcd client library, not the etcd server itself. If no etcd cluster already serves the rest of your Spock cluster’s Patroni pairs, install and start one. Package name and installation method vary by platform; see the etcd releases page if your package manager does not provide one. A production etcd deployment needs an odd number of members (3 or 5) for quorum; the following configures a single-member etcd suitable for this tutorial:
Confirm both hosts can reach the DCS before continuing, whether it is freshly started or already serving this pair:
Point this node’s Patroni configuration at the upgraded instance. If this is the first time the node is being brought under Patroni, write a new config for it as the leader of a new Patroni cluster, rather than letting Patroni bootstrap it from scratch - the data directory is already initialized and already running the data
pg_upgradeproduced, and Patroni only runs its bootstrap process against an emptydata_dir; pointing it at the existing, populated directory makes Patroni adopt the running instance as the cluster’s first member instead. If the node was already under Patroni before this upgrade, update its existing config’sdata_dirandbin_dirto the values below instead of writing a new file.pg_upgradepreserves roles and their passwords, and step 5 above already copiedpg_hba.confforward, so areplicatorrole and itspg_hba.confentry from an existing standby still work unchanged.Optional: set a password on the
postgressuperuser only if one is not already set:If the node was already under Patroni, its DCS still records the old cluster’s system identifier, and
pg_upgradegave the upgraded cluster a new one. Patroni refuses to manage a data directory whose system identifier does not match, so the old cluster state has to go before Patroni can adopt the upgraded instance. Stop the Patroni process on bothn1andn1_standby, then remove the scope’s state from the DCS.patronictl removeasks you to type the cluster name and confirm:This deletes only the DCS keys for
n1-cluster, not any data directory. It also deletes the scope’s dynamic configuration, which ends the pause from step 3 and drops any settings you applied withpatronictl edit-config; record those first withpatronictl -c /path/to/n1_patroni.yml show-config n1-clusterand apply them again once Patroni is running.Whether the node was already under Patroni or is being brought under it for the first time, start Patroni on
n1with the configuration from step 12. With no cluster state in the DCS and PostgreSQL already running on a populateddata_dir, Patroni adopts the running instance as the leader rather than bootstrapping a new one:Then bring up
n1_standbyas a new member: its old data directory holds the old, now-incompatible major version and cannot be reused. Run Patroni on the standby’s own host, pointed at the samescopeand DCS, under the member namen1_standby, with an emptydata_dir. Patroni finds the cluster in the DCS and, on first start, runspg_basebackupitself againstn1to populate that empty directory. Ifn1_standbywas already under Patroni, edit its existing config to the values below:Confirm
n1_standbyjoined and is streaming before moving on:Also confirm, on
n1, that the slot backing the standby has synced:synchronized_standby_slotsnames a Patroni-managed physical slot, and Patroni auto-creates one such slot per standby member - on whichever node is currently primary - named after that standby member rather than after its role. Today that slot is namedn1_standbyand exists onn1; ifn1_standbyis ever promoted, that slot disappears and a new one namedn1appears onn1_standbyinstead, representingn1as the new standby. Theon_role_changecallback named in both Patroni configurations above resets the setting on a future promotion to whichever member is then the standby. Patroni reads its local configuration only at start and on reload, so if you add the callback to a member that is already running, reload it afterwards:The following script, deployed on
n1withSIBLING_MEMBERset ton1_standbyandLOCAL_PORTset to5432(and onn1_standbywith them set ton1and5442), setssynchronized_standby_slotsto the other member’s name whenever this node becomes the primary:The callback only fires on a future promotion, so set the initial value by hand now, on
n1while it is still the leader:A later promotion of
n1_standbyis a separate event from this setup, and needs its own plan: Spock’s subscriptions onn2andn3connect ton1using whichever address was configured when those subscriptions were created, and Patroni does not repoint that address for them. Ifn1is reachable only through a VIP or DNS record that Patroni (orkeepalivedalongside it) moves to whichever member is primary, no further Spock-level action is needed after a promotion. Without such an abstraction in front of the pair, repoint each subscription by hand after a promotion, from any node whose subscription still points at the old address.node_add_interfacewrites only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, heren2andn3, sincesub_alter_interfacelooks the interface up locally:Then run
sub_alter_interfaceon each of those nodes. The subscriptions it names are the ones step 20 recreates, so this only applies once step 20 is done:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1_n2is the subscription onn2whose provider isn1; confirm the exact names for your cluster withSELECT sub_name FROM spock.subscription;on each node before repointing them.Put
n1’s replication origins back where step 2 recorded them, before its subscriptions run again. For each subscription, create the origin ifpg_upgradedid not keep it, then advance it to the recorded LSN:Confirm each origin now shows its recorded LSN:
On every other node, recreate its subscription to
n1from the definition recorded in step 2. Do not copy data: step 2 made sure every node already held all ofn1’s changes, andn1has taken no writes since. The following example recreates the subscription onn2whose provider isn1:Do not set
synchronize_data := truehere. The data sync copies each table into the existing one without emptying it first, so it fails on the rows the node already holds.Re-enable
n1’s own subscriptions, then confirm every subscription to and fromn1reportsreplicating:Then check the status of every subscription in the cluster:
Restore traffic to the node at the load balancer, pooler, or application layer.
With n1 upgraded, repeat steps 1 through 22 for n2 and n3.
Each node’s standby must be built from a pg_basebackup against that
specific node, never against another one - n2_standby streams from
n2, not from n1, even though Spock keeps their table data
identical.
A physical standby is tied to the exact system identifier and
Spock catalog rows (its own spock.node/spock.subscription
entries) of the instance it shadows, so it can be promoted into
that instance’s exact identity; a standby built from n1 and
promoted in place of n2 would still carry n1’s identity and
subscriptions, breaking the mesh rather than replacing n2.
Each node’s physical standby, if it has one, also belongs under its
own Patroni scope (n2-cluster, n3-cluster) with its own leader -
never add n2 or n3 as a member of n1-cluster. Patroni elects one
primary per scope, and n1, n2, and n3 each remain independent
primaries in the Spock mesh, not standbys of one another. The DCS
deployment itself can still be shared: one etcd cluster can serve
every node’s Patroni scope, so long as each scope’s name is unique.
Re-enabling DDL Replication
Once every node is upgraded, turn automatic DDL replication back on, on every node, as in Upgrading Spock:
Verifying the Rollout
When every node has been upgraded, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:
Run the dblink query once per node, changing the port.
The following table describes what to check in the output before considering the rollout complete:
| Field | What to confirm |
|---|---|
| PostgreSQL version | Every node reports the target version. |
| Subscription status | Every subscription between every pair of nodes reports replicating. |
Troubleshooting
pg_upgrade --checkreports an incompatible extension version. Install the Spock build for the target PostgreSQL version on the node before upgrading;pg_upgradechecks that every extension in the old cluster has a matching library available for the new one.pg_upgrade --linkfails withcould not create hard link between old and new data directories. The old and new data directories are on different filesystems or volumes. Place the new data directory on the same filesystem as the old one, or run without--linkand accept the storage cost of a full copy.A subscription on the upgraded node fails because its replication origin does not exist. The origin was not restored before the subscription was enabled. Disable it, restore the origin as in step 19 from the position recorded in step 2, then enable it again.
The application still routes traffic to a node that is down for upgrade. Confirm the load balancer, pooler, or application-level routing actually removed the node from rotation in step 1 before you stopped it in step 3, rather than relying on connection failures to redirect traffic.
For more information, review the following resources:
- Modifying a Cluster
- Logical Slot Failover (HA Standby)
- Tutorial: Updating the Postgres Version with a Rolling Update
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.8 - Conflict Types
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
For conflict avoidance using delta-apply columns, see Conflict Avoidance and Delta-Apply Columns.
In a multi-master replication environment, conflicts occur when two or more nodes make changes to the same row (as identified by a primary key or replica identity) at overlapping times. Spock detects these conflicts during the apply phase on the subscribing node and resolves them according to a configurable resolution strategy.
Each conflict is classified as one of the types described below.
Resolvable conflicts are recorded in the spock.resolutions table
(when spock.save_resolutions is enabled); non-resolvable conflicts
are recorded in spock.exception_log.
Summary Table
| Conflict Type | DML | Resolvable |
|---|---|---|
insert_exists | INSERT | Yes |
update_origin_differs | UPDATE | N/A (normal flow, not recorded) |
update_exists | UPDATE | No (unique constraint violated), saved in spock.exception_log |
update_missing | UPDATE | No (row not found), saved in spock.exception_log |
delete_origin_differs | DELETE | N/A (normal flow, not recorded) |
delete_missing | DELETE | Yes |
delete_exists | DELETE | Yes |
A conflict is resolvable when Spock can automatically choose a
winning tuple and continue replication without operator intervention.
update_missing and update_exists are not resolvable and result in
an ERROR that is recorded in spock.exception_log.
insert_exists
A remote INSERT arrives but a row with the same primary key (or replica identity) already exists on the local node. This typically happens when two nodes independently insert a row with the same key.
Spock detects the conflict by looking up the incoming tuple against
unique indexes (primary key, replica identity, and optionally all
unique constraints when spock.check_all_uc_indexes is enabled).
Resolution: The configurable conflict resolver (default
last_update_wins) compares the commit timestamps of the local and
remote rows. The winner’s values are applied as an UPDATE to the
existing row.
update_origin_differs
A remote UPDATE targets a row whose local copy was last modified by a
different replication origin. In a multi-master topology this is the
normal flow of replication – two nodes each modify a row and the
changes propagate – so Spock does not treat it as a true conflict.
PostgreSQL’s native logical replication does classify it as a conflict,
however, so Spock tracks the type for completeness and supports
optional logging via the spock.log_origin_change GUC.
Spock detects this by comparing replorigin_session_origin (the
source of the incoming change) with the origin recorded on the local
tuple. Changes from the same origin or the same local transaction are
silently applied without any conflict reporting.
Resolution: The configurable conflict resolver (default
last_update_wins) determines the winner. Since this is normal
replication flow, the event is not written to spock.resolutions
regardless of which side wins.
update_exists
A remote UPDATE is applied successfully via the replica identity, but the new row values violate a unique constraint on a different index. For example, the UPDATE changes a column that is part of a secondary unique index and the new value collides with another existing row.
This conflict type matches the definition used by PostgreSQL 18’s native logical replication. Spock reports it to the PostgreSQL server log and PG18 conflict statistics when the unique constraint violation is detected.
Resolution: This conflict is not automatically resolvable. The
error is written to spock.exception_log.
update_missing
A remote UPDATE cannot find the target row on the local node. The row may have been deleted locally, or it may never have arrived due to a replication gap.
Spock retries the lookup several times (with short waits) in case the row is being inserted by a concurrent transaction. If the row still cannot be found after retries, the conflict is raised.
Resolution: This conflict is not resolvable. Spock raises an
ERROR, which is logged to spock.exception_log.
delete_origin_differs
A remote DELETE targets a row that exists locally but was last modified
by a different replication origin. As with update_origin_differs,
this is normal replication flow rather than a true conflict – one node
deletes a row while another node’s earlier update is still in flight.
Spock tracks the type because PostgreSQL’s native logical replication
considers it a conflict, and supports optional logging via
spock.log_origin_change.
If the local tuple came from the same origin as the incoming delete, or from the same local transaction, the delete is applied silently with no conflict reporting.
Resolution: The configurable conflict resolver (default
last_update_wins) determines the winner. When the remote DELETE
wins, the delete proceeds. When the local tuple wins (it is newer),
the delete is skipped and the row is preserved; this case is reported
as delete_exists instead.
delete_missing
A remote DELETE cannot find the target row on the local node. The row was likely already deleted by a local or other replicated transaction.
As with update_missing, Spock retries the lookup several times
before confirming the row is absent.
Resolution: The conflict is automatically resolved by skipping the
delete (skip). Since the row is already gone, the desired end state
has been achieved. The event is recorded in the spock.resolutions
table.
delete_exists
A remote DELETE arrives but the local copy of the row has a more recent commit timestamp than the delete. This is unique to Spock and does not have a counterpart in native PostgreSQL logical replication.
This occurs when one node deletes a row while another node updates it with a later timestamp. The delete is the older operation, so the updated row should be preserved.
Resolution: The delete is skipped and the local (newer) row is
kept (skip / keep_local). The event is recorded in the
spock.resolutions table.
Conflict Resolution Strategies
The spock.conflict_resolution GUC controls how resolvable conflicts
(all types except update_missing and update_exists) are decided. In
current Spock releases the only supported value is:
| Strategy | Behavior |
|---|---|
last_update_wins | The row with the most recent commit timestamp wins (default). |
last_update_wins requires track_commit_timestamp = on in
postgresql.conf.
Tiebreaker: When two rows have identical commit timestamps, Spock
uses the tiebreaker value from the spock.node configuration to
determine a winner. The node with the lower tiebreaker value wins. By
default the tiebreaker is set to the node’s unique ID.
Tiebreaker resolution is always local. Every node keeps its own copy
of what it believes each node’s tiebreaker to be, read from its own
spock.node.info column. A node’s info (including tiebreaker) is
populated once – either when the node is created, or when another node
first subscribes to it (via spock.sub_create(), which fetches the
provider’s node metadata at that moment).
A node’s own location, country, and info (including tiebreaker)
can be changed afterward with
spock.node_alter –
the recommended way, since it validates a tiebreaker value and merges
info rather than replacing it – or with a raw UPDATE spock.node.
Either way, the change propagates automatically to every node that
subscribes to it directly (see
Automatic Node Metadata Propagation):
Every node that subscribes to n1 directly picks this up with no
further action. The message is not forwarded through a cascade topology
(Node A → Node B → Node C): Node C normally has no spock.node row for
n1 unless it subscribes to n1, so there is nothing for it to update.
A node that has a row for n1 but did not apply the message keeps the old
value. This happens when the transaction carrying the message is skipped or
discarded by the exception handling. Use
spock.node_refresh_info
to catch up on demand:
Leaving some nodes unrefreshed has the same effect as updating them with different values: the cluster ends up with disagreeing tiebreaker values for the same node, which can cause different nodes to resolve the identical conflict differently.
Frozen Tuples and Missing Timestamp Data
Timestamp-based conflict resolution depends on commit timestamp and origin information being available for the local tuple. There are two cases where this information is missing:
Frozen tuples. PostgreSQL periodically “freezes” old row versions,
replacing their transaction ID with FrozenTransactionId. Once
frozen, the original commit timestamp and origin can no longer be
retrieved. When Spock encounters a frozen local tuple during conflict
resolution, it treats the local timestamp as zero. Since any real
remote timestamp is greater than zero, the remote change always wins.
No conflict is logged because the local origin could not be
determined.
track_commit_timestamp = off. If commit timestamp tracking is
disabled, Spock cannot retrieve origin or timestamp information for
any local tuple. In this case, Spock copies the remote origin and
timestamp into the local values. The same-origin check then sees
matching origins and treats the change as normal replication flow –
no conflict is detected or logged. This effectively makes conflict
resolution invisible: the remote change is always applied silently.
For reliable conflict detection and resolution,
track_commit_timestamp must be set to on.
Conflict Logging
spock.save_resolutions(defaultoff) – When enabled, resolved conflicts are written to thespock.resolutionstable with full tuple details in JSON format.spock.conflict_log_level(defaultLOG) – Controls the PostgreSQL log level at which detected conflicts are reported. Set to a level belowlog_min_messagesto suppress log output.spock.log_origin_change(defaultnone) – Controls whetherupdate_origin_differsanddelete_origin_differsevents (normal replication flow) are logged to the PostgreSQL server log. These events are never written tospock.resolutions. Options:none,remote_only_differs,since_sub_creation.
Comparison with PostgreSQL 18 Native Logical Replication
PostgreSQL 18 introduced built-in conflict detection for logical replication. Spock’s conflict types are aligned with PostgreSQL’s definitions (same names, same enum ordering) so that the two systems report conflicts in a consistent way. The key differences are in how each system resolves conflicts and where it records them.
| Conflict Type | PostgreSQL 18 | Spock (with last update wins) |
|---|---|---|
insert_exists | Logs and raises ERROR. | Resolves via last_update_wins; transforms INSERT into UPDATE of the winning tuple. |
update_origin_differs | Logs and always applies the remote tuple. | Resolves via last_update_wins; local tuple can win. Treated as normal replication flow (not a true conflict) with optional logging via log_origin_change. |
update_exists | Detects unique constraint violation on updated row; logs. | Logs and records in spock.exception_log. |
update_missing | Logs and skips. | Logs and records in spock.exception_log. |
delete_origin_differs | Logs and always applies the delete. | Resolves via last_update_wins; local tuple can win (reported as delete_exists). Treated as normal replication flow (not a true conflict) with optional logging. |
delete_missing | Logs and skips. | Logs and skips. Records in spock.resolutions. |
delete_exists | No equivalent. | Unique to Spock. The local row is newer than the remote DELETE, so the delete is skipped and the row is preserved. |
Resolution. PostgreSQL 18 does not resolve conflicts – it either
applies the remote change unconditionally or skips the operation, and
logs the event. Spock adds configurable resolution strategies (default
last_update_wins) with a tiebreaker mechanism, allowing the local
tuple to win when it is more recent.
Persistence. PostgreSQL 18 writes conflicts only to the PostgreSQL
server log. Spock additionally persists certain conflicts in the
spock.resolutions table (with full tuple details in JSON) –
specifically insert_exists, delete_missing, and delete_exists –
and non-resolvable conflicts (update_missing, update_exists) in
spock.exception_log. Origin-differs events are not persisted to
either table.
Statistics. On PostgreSQL 18, Spock reports all conflict types to
the native pgstat subscription conflict statistics, so they appear
in the same views used by built-in logical replication.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.9 - Conflict-Free Delta-Apply Columns (Conflict Avoidance)
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Conflicts can arise if a node is subscribed to multiple providers, or when local writes happen on a subscriber node. Without Spock, logical replication can also encounter issues when resolving the value of a running sum (such as a YTD balance).
Suppose that a running bank account sum contains a balance of
$1,000. Two transactions conflict because they overlap with each from
two different multi-master nodes. Transaction A is a $1,000 withdrawal
from the account. Transaction B is also a $1,000 withdrawal from the
account. The correct balance is $-1,000. The Delta-Apply algorithm
fixes this problem and highly conflicting workloads with this scenario
(for example, a tpc-c like benchmark) now run correctly at lightning
speeds.
In the past, Postgres users have relied on special data types and numbering schemes to help prevent conflicts. Unlike other solutions, Spock’s powerful and simple conflict-free delta-apply columns instead manage data update conflicts with the following logic:
- the old value is captured in WAL files.
- a new value comes in from a transaction.
- before the new value overwrites the old value, a delta value is created from the above two steps; that delta is correctly applied.
To simplify: local_value + (new_value - old_value)
Note that on a conflicting transaction, the delta-apply column will be correctly calculated and applied.
To make a column a conflict-free delta-apply column, ensuring that the value
replicated is the delta of the committed changes (the old value plus or
minus any new value) to a given record, you need to apply the following
settings to the column: log_old_value=true, delta_apply_function=spock.delta_apply. For example:
As a special safety-valve feature, if you ever need to re-set a
log_old_value column you can temporarily alter the column to
log_old_value is false.
Conflict Configuration Options
You can configure some Spock extension behaviors with configuration options
that are set in the postgresql.conf file or via ALTER SYSTEM SET:
spock.conflict_resolution = last_update_winssets the resolution method tolast_update_winsfor any detected conflicts between local data and incoming changes; the version of data with newest commit timestamp is kept; note that thetrack_commit_timestampPostgreSQL setting must also beenabled.spock.conflict_log_levelsets the log level for reporting detected conflicts; the default isLOG; if the parameter is set to a value lower thanlog_min_messages, resolved conflicts are not written to the server log; accepted values are the same as for thelog_min_messagesPostgreSQL setting (see possible values); this setting is used primarily to suppress logging of conflicts.
Handling INSERT-RowExists or INSERT/INSERT Conflicts
If Spock encounters a conflict caused by a constraint violation (unique
constraint, primary key, or replication identity) Spock can automatically
transform an INSERT into an UPDATE, updating all columns of the existing
row.
By default, when an INSERT statement targets a row that already exists,
Spock detects the conflict and transforms the operation into an UPDATE
statement, applying changes to all columns of the existing row. The event is
recorded in the spock.resolutions table.
Extended constraint violation behavior is controlled by the
spock.check_all_uc_indexes parameter. The default value is off; when set
to on, Spock will perform the following actions:
- scan all valid unique constraints (as well as the primary key and replica identity).
- scan non-null unique constraints (including the primary key or replica identity index) in OID order.
- locate and resolve conflicting rows encountered during an
INSERTstatement.
If spock.check_all_uc_indexes is enabled, Spock will resolve only
the first conflict identified, using Last-Write-Wins logic. If a second
conflict occurs, an exception is recorded in the spock.resolutions
table as either Keep-Local or Apply-Remote.
This feature is experimental; enable this feature at your own risk.
Handling DELETE-RowMissing Conflicts
Given that the purpose of the DELETE statement is to remove the row anyway,
we do not log these as exceptions, since the desired outcome of removing the
row has obviously been achieved, one way or the other. Instead
DELETE-RowMissing conflicts are automatically written to the
spock.resolutions table since the desired result has been achieved.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.10 - Monitoring the Configuration and Health of Your Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension provides several ways you can monitor data health in your Postgres cluster:
- You can query informational tables in the
spockschema to review information about your cluster configuration and status. - The status views
spock.node_status,spock.subscription_status,spock.worker_status,spock.slot_statusandspock.eventsgive a complete picture of a node without reading the server log. - The Spock extension’s Lag Tracking utility allows you to review node-specific metrics for replication lag.
- Use Spock’s Sync Event utility to watch for a specific transaction to replicate.
- Use the ACE (Active Consistency Engine) to evaluate cluster health.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.10.1 - Finding Cluster Information
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The following table describes informational tables in the spock schema:
| Table Name | Description |
|---|---|
channel_table_stats | This view tracks per-table statistics for a given subscription, including total inserts, updates, deletes, conflicts, and delta apply column changes. The view includes the following columns: subid, relid, sub_name, table_name, n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca |
channel_summary_stats | This view aggregates statistics from channel_table_stats across tables, showing overall metrics grouped by subscription. The view includes the following columns: subid, sub_name, n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca |
events | This view lists recent state changes of the node kept in shared memory: subscriptions enabled or disabled, workers started, stopped or failed, provider connects, extension upgrades. See Monitoring a Node. The view includes the following columns: event_id, event_time, event_type, severity, subscription_id, subscription_name, pid, lsn, detail |
depend | This is an internal-use table that tracks dependent objects (e.g., tables added for replication or row filters). If such objects are dropped, they are also removed from Spock’s tracking. The table includes the following columns: classid, objid, objsubid, refclassid, refobjid, refobjsubid, deptype |
exception_log | This table logs unrecoverable errors or conflicts encountered by Spock during the replication process. The table includes the following columns: remote_origin, remote_commit_ts, command_counter, retry_errored_at, remote_xid, local_origin, local_commit_ts, table_schema, table_name, operation (contains one of the following: BEGIN, COMMIT, INSERT, UPDATE, DELETE, or DDL), local_tup, remote_old_tup, remote_new_tup, ddl_statement, ddl_user, error_message |
exception_status | This table is not used internally by Spock. This table exists to support ACE by tracking specific status details. The table includes the following information columns: remote_origin, remote_commit_ts, retry_errored_at, remote_xid, status, resolved_at, resolution_details |
exception_status_detail | The table includes the following columns: remote_origin, remote_commit_ts, command_counter, retry_errored_at, remote_xid, status, resolved_at, resolution_details |
local_node | This table contains one row with information for the local node. It contains the node_id and node_local_interface and can be joined with the previous two tables to show all local node information only. |
local_sync_status | This table displays the synchronization status of relations (tables) added to subscriptions. Shows all tables if a full sync was requested, or individual tables if sync was limited to specific tables. The table includes the following columns: sync_kind, sync_subid, sync_nspname, sync_relname, sync_status, sync_statuslsn |
node | This table contains one row per replication node. This table contains: node_id, node_name, and optionally the location, country, and info. |
node_interface | This table contains one row per node interface. This table contains: if_id, if_name, if_nodeid, and if_dsn columns which represent the connection information for that node. |
node_status | This view returns one row describing the whole node: versions, worker and subscription counts, WAL retained by slots, replication lag and the time of the last events. See Monitoring a Node. |
peer_status | This view lists every node this node knows about with its interfaces and the subscription that brings its changes here. See Monitoring a Node. |
pii | This is an optional table in which you can define columns that contain personally identifiable information (pii). You can add information such as the schema, table, and column names and then use this table to create column filters when adding tables to replication sets. The table contains the following columns: id, pii_schema, pii_table, pii_column |
progress | This is an internal-use table that tracks replication progress, including source node, commit LSN, commit timestamp, and origin’s current WAL insert location. The table includes the following columns: node_id, remote_node_id, remote_commit_ts, remote_commit_lsn, remote_insert_lsn, last_updated_ts, updated_by_decode |
queue | This is an internal-use table used during AutoDDL, subscription/table synchronization, and native sequence synchronization processes. The table includes the following information columns: queued_at, role, replication_sets, message_type, message |
replication_set | This table contains one row per replication set. It contains the set_id, set_nodeid, set_name and four boolean columns: replicate_insert, replicate_update, replicate_delete, and replicate_truncate. This table also contains three rows by default for the default, default_insert_only, and ddl_sql replication sets. |
replication_set_seq | This table contains one row per replication set sequence. It contains set_id and set_seqoid. |
replication_set_table | This table contains one row per table that is in any replication set. It contains the set_id, set_reloid (the table name), set_att_list, and set_row_filter. The last two columns contain the row and column filters on that table for replication. |
replication_set_status | This view lists the replication sets of the local node with their replicate flags and the number of tables, sequences and subscriptions using each. |
resolutions | This table contains one row per resolution made on this node. It contains the id, node_name, log_time, relname, idxname, conflict_type (update_update), conflict_resolution (keep_local), local_origin, local_tuple, local_xid, local_timestamp, remote_origin, remote_tuple, remote_xid, remote_timestamp, remote_lsn. |
settings | This view shows the spock parameters and the core parameters replication depends on, with unit, source and pending restart. |
slot_status | This view describes every spock replication slot of the database together with the walsender serving it, the WAL it holds back and the feedback lag. See Monitoring a Node. |
sequence_state | This is an internal-use table that stores state information for native sequence synchronization. The table includes the following columns: seqoid, cache_size, last_value |
subscription | This table contains one row per subscription. It contains the following columns: sub_id, sub_name, sub_origin, sub_target, sub_origin_if, sub_target_if, sub_enabled, sub_slot_name, sub_replication_sets (an array of replication sets that have been added to the subscription), sub_forward_origins, sub_apply_delay, sub_force_text_transfer, sub_skip_lsn (a pg_lsn set by spock.sub_alter_skiplsn), sub_skip_schema (an array of schemas to skip during apply), and sub_created_at (timestamp of subscription creation). |
subscription_stats | This view returns the activity counters of every subscription: worker starts and failures, provider connects, messages and transactions received, tuple and conflict counters, and the last error. See Monitoring a Node. |
subscription_status | This view describes every subscription on one row: configuration, status, the apply worker serving it, replication positions and lag, and the last error. See Monitoring a Node. |
system_status | This view returns one row about the host and the instance: disk space, load, connections, long and idle transactions, wraparound age, database statistics and WAL archiving. See Monitoring a Node. |
table_sync_status | This view shows local_sync_status with readable sync_kind and sync_status values. |
tables | This table contains one row per table in the database. It contains the following columns: relid, nspname (the schema), relname (the tablename), and set_name (null if that table is not added to any replication set). |
worker_status | This view lists the spock processes of the node: supervisor, manager, apply and sync workers, with their status and the subscription or table they serve. See Monitoring a Node. |
Examples
The following examples demonstrate how to query the informational tables to monitor and validate your Spock replication cluster.
Validating Spock Configuration for a Two-Node Cluster
You can use the Spock extension to confirm that nodes are created and replication is happening.
Query spock.node to check node creation status: an empty result set means
the node creation command has not yet been run, while a single row confirms
the node exists.
Query spock.subscription to check subscription creation status: an empty
result set means no subscription has been created on this node, while a
single row confirms a subscription exists.
You can connect to the database server and query the spock.node table to
return information about configured nodes:
Confirming that a Functioning Subscription Exists
You can connect to the database server and query the spock.subscription
table to return information about a subscription:
Note that the value of sub_enabled is t if the subscription is currently
replicating.
Listing Tables that are Part of a Replication Scenario
You can connect to the database server and query the
spock.replication_set_table table to return similar information:
Listing Tables that are not Part of a Replication Cluster
You can query the spock.tables table to identify tables that are not yet
part of a replication set; if the set name is null, the table is not part
of a replication set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.10.2 - Lag Tracking
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension’s lag tracking feature shows how far behind a subscriber is when compared to a provider node in terms of write-ahead log (WAL) replication. You can use this feature to understand replication delays and monitor streaming health.
Tracking is implemented via a SQL view named spock.lag_tracker, which
exposes key metrics for replication lag on a per-node basis. For example:
The following table describes the columns displayed by spock.lag_tracker:
| Column Name | Description |
|---|---|
| origin_name | Name of the provider node. |
| receiver_name | Name of the subscriber node. |
| commit_timestamp | Commit time of the last transaction received from the provider. |
| commit_lsn | Log sequence number (LSN) of the commit on the provider. |
| remote_insert_lsn | WAL insert position on the provider when the commit was sent. |
| received_lsn | Last acknowledged log sequence number (LSN) received from the provider. |
| replication_lag_bytes | The amount of data the subscriber is behind. |
| replication_lag | Time delay between when the transaction was committed on the provider and when processed locally. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.10.3 - Monitoring a Node with the Spock Status Views
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock keeps the state of a node in shared memory and exposes it through a
set of views in the spock schema. Together they answer the questions an
operator would otherwise take to the server log: is every subscription
replicating, which workers are running, how far behind is each provider,
how much WAL is a slot holding back, and what happened recently.
| View | One row per | Purpose |
|---|---|---|
spock.system_status | host | Host and instance health: disk, load, connections, long transactions, wraparound age, archiving. |
spock.node_status | node | The whole node on one row: versions, counts, WAL, lag, last events. |
spock.subscription_status | subscription | Configuration, status, serving worker, replication position and lag, last error. |
spock.subscription_stats | subscription | Activity counters: worker starts, connects, transactions, tuples, conflicts, errors. |
spock.worker_status | spock process | Supervisor, manager, apply and sync workers with their state. |
spock.slot_status | replication slot | Provider side: walsender state, positions and retained WAL per spock slot. |
spock.table_sync_status | subscription or table | Initial synchronization state in readable form. |
spock.peer_status | known node | Every node this node knows, with the subscription that brings its changes here. |
spock.replication_set_status | replication set | Replication sets of the local node with table, sequence and subscriber counts. |
spock.settings | parameter | The spock parameters and the core parameters replication depends on. |
spock.events | event | Recent state changes: enable, disable, restarts, errors, upgrades. |
spock.node_report() runs all of them one after another and returns the
node as a single text report; see The full report.
All views are scoped to the current database. spock.lag_tracker,
spock.progress and the spock.channel_*_stats views remain available and
feed the views above.
System status
spock.system_status is one row about the host and the PostgreSQL
instance. It answers the questions that come before any replication
question: is the disk full, is the machine overloaded, are connections
exhausted, is a long or idle transaction holding back vacuum and the
replication slots, is WAL archiving failing.
| Column | Description |
|---|---|
hostname, os_name, os_release, architecture, cpu_count, memory_bytes | The host. |
load_average_1min, load_average_5min, load_average_15min | System load averages. |
data_directory, data_disk_total_bytes, data_disk_free_bytes | The data directory and the space on its volume. |
wal_disk_total_bytes, wal_disk_free_bytes, wal_size_bytes | The volume holding pg_wal, measured separately in case it is a symlink, and the size of pg_wal. |
database_size_bytes | Size of the current database. |
postgres_version, postmaster_pid, postmaster_start_time, uptime, in_recovery | The instance. |
max_connections, connections, active_connections, idle_in_transaction | Client connections and their state. |
longest_transaction, longest_idle_in_transaction | Age of the oldest open transaction and of the oldest idle one; both hold back vacuum and slot catalog_xmin. |
waiting_on_locks | Sessions currently waiting for a lock. |
prepared_transactions | Prepared transactions, which hold locks and xmin until resolved. |
physical_standbys | Streaming replicas other than spock subscribers. |
oldest_xid_age | Age of the database’s oldest transaction id, towards wraparound. |
xact_commit, xact_rollback, deadlocks, recovery_conflicts, temp_files, temp_bytes, checksum_failures, database_stats_reset | From pg_stat_database for this database. |
archive_mode, archived_count, last_archived_time, archive_failed_count, last_archive_failure | WAL archiving state; a failing archiver fills the WAL volume. |
Node status
spock.node_status always returns exactly one row, even before a node has
been created.
| Column | Description |
|---|---|
node_id, node_name, location, country | The local node, NULL when none exists. |
database_name | The current database. |
hostname, operating_system, postmaster_start_time | The host and the server start. |
spock_version | Version of the loaded shared library. |
extension_version | Version of the installed extension in the catalog. |
extension_update_pending | True when the library is newer than the extension; the manager runs ALTER EXTENSION UPDATE on its next start. |
postgres_version | Server version. |
spock_started_at | When spock shared memory was initialized, normally the postmaster start. |
postmaster_pid, supervisor_pid, manager_pid | Process ids of the postmaster, the supervisor and this database’s manager. |
readonly_mode | Current value of spock.readonly. |
apply_paused | True while spock.pause_apply_workers() is in effect. |
worker_slots, worker_slots_used | Background worker slots spock can use and how many are taken. |
subscriptions, subscriptions_enabled, subscriptions_replicating | Subscription counts. |
replication_slots, replication_slots_active | Spock slots of this database and how many have a connected walsender. |
apply_workers, sync_workers | Running worker counts. |
workers_restart_pending | Workers that exited with an error and wait for the manager to restart them. |
pending_exceptions | Transactions currently being retried under spock.exception_behaviour. |
replicated_tables, unreplicated_tables | Tables of this node in some replication set, and tables in none. |
current_wal_lsn | Current WAL position, replay position on a standby. |
wal_size_bytes | Size of pg_wal, read through spock.wal_size_bytes(), which sums the files itself so that a role without pg_monitor can read it. |
data_disk_free_bytes, wal_disk_free_bytes | Free space on the volumes holding the data directory and pg_wal. |
max_retained_wal_bytes | WAL held back by the slowest spock slot. |
max_replication_lag_bytes, max_replication_lag | Largest lag over all subscriptions. |
exceptions_logged | Rows in spock.exception_log. |
last_event_time, last_error_event_time | Time of the newest event, and of the newest error event. |
events_retained, events_recorded | Events kept in the history and recorded since start. |
Subscription status
spock.subscription_status is the first place to look when replication
seems stuck.
| Column | Description |
|---|---|
subscription_id, subscription_name, enabled | The subscription. |
status | replicating, initializing, starting (the worker is up but not streaming yet, as during a reconnect loop), down (enabled but no worker), disabled or unknown. |
provider_node, provider_dsn | The provider; the password in the DSN is replaced with asterisks. |
slot_name, replication_sets, forward_origins, apply_delay, skip_lsn, skip_schema, force_text_transfer, created_at | Configuration. |
sync_status | Initial synchronization state of the subscription as a whole. |
worker_pid, worker_status, worker_started_at | The apply worker. worker_status is restart pending after a failure. |
worker_terminated_at, worker_restart_delay | When the last worker failed and how long the manager waits before restarting it, in milliseconds. |
worker_paused | True while the worker sleeps because apply is paused. |
in_exception_handling | True while the worker replays a failed transaction under spock.exception_behaviour. |
pending_exception_lsn, pending_exception_error | Commit LSN and first error of the transaction being retried, if any. |
origin_lsn | Last durably applied provider LSN, from spock.replication_origin_status(). |
remote_commit_lsn, remote_commit_ts, remote_insert_lsn, received_lsn | Positions from spock.progress. |
replication_lag_bytes | WAL the provider has written that this node has not yet applied. |
replication_lag | Time between the last applied commit on the provider and its apply here. |
last_message_received, last_xact_applied | When data last arrived from the provider and when a transaction was last committed here. |
time_since_last_message | How long ago data last arrived; a silent provider shows here first. |
worker_blocked_by_pids, worker_blocking_pid, worker_blocking_query | Set while the worker waits for a lock: the sessions holding it and what the first one runs. |
worker_starts, worker_failures, xacts_applied, apply_errors | Counters from spock.subscription_stats. |
last_apply_error, last_error_sqlstate, last_error_pid, last_error_message | The most recent error of the apply worker: when, its SQLSTATE, the process that raised it, and the message with DETAIL and CONTEXT. |
Subscription statistics
spock.subscription_stats has one row for every subscription with the
counters collected by its apply and sync workers. Counters survive worker
restarts and are reset with spock.reset_subscription_stats(subid), or for
all subscriptions with no argument. Every counter has a matching last_*
timestamp of its most recent change.
| Column | Description |
|---|---|
worker_starts, worker_failures | Apply worker starts, and exits with an error. |
sync_worker_starts, sync_worker_failures | The same for the sync workers that copy tables; a resync adds one start per table. |
provider_connects, provider_disconnects, idle_timeouts | Connections to the provider, connection losses together with connection attempts that failed (so while the provider is down this counts every retry), and reconnects forced by spock.apply_idle_timeout. |
messages_received, bytes_received | Data messages received from the provider. |
xacts_applied, xacts_skipped, xacts_discarded | Transactions committed locally, skipped through sub_skip_lsn, and discarded under transdiscard. |
apply_errors, sync_errors | Errors raised in apply and in sync workers. An apply error counts once per failed transaction. |
deadlocks, lock_timeouts, constraint_violations, resource_errors | The same errors classified by SQLSTATE: deadlock detected, lock not available, class 23 and class 53. |
tables_synced | Tables whose initial synchronization completed. |
n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca | Tuple counters, summed from spock.channel_table_stats. |
confl_* | Conflict counters by type; NULL before PostgreSQL 18. |
last_error_message, last_error_lsn, last_error_sqlstate, last_error_pid | The most recent worker error with DETAIL and CONTEXT, the provider LSN it happened at, its SQLSTATE and the process that raised it. |
stats_reset | When the counters were last reset. |
Workers
spock.worker_status lists the supervisor, the manager of this database,
and every apply and sync worker, including slots of failed workers that are
waiting to be restarted.
| Column | Description |
|---|---|
worker_slot, worker_type, pid | Slot in shared memory, supervisor, manager, apply or sync, and process id. |
worker_status | starting, running, idle, stopping, stopped, failed or restart pending. |
subscription_id, subscription_name | For apply and sync workers. |
sync_schema_name, sync_table_name | The table a sync worker copies. |
started_at, xact_start, backend_state, wait_event_type, wait_event | From pg_stat_activity. |
blocked_by_pids, blocking_pid, blocking_xact_start, blocking_query | Set while the worker waits for a lock held by another session, from pg_blocking_pids(). |
paused, in_exception_handling, sync_pending | Apply worker flags. |
replay_stop_lsn, remote_wal_insert_lsn | Positions the worker works towards and has last seen on the provider. |
generation, terminated_at, restart_delay | Registration counter, time of the last failure, restart delay in milliseconds. |
Replication slots
spock.slot_status is the provider side view: one row per spock
replication slot of the current database, joined with the walsender that
serves it.
| Column | Description |
|---|---|
slot_name, active, active_pid | The slot and its walsender. |
client_name, client_addr, connected_at, state | The connected subscriber, from pg_stat_replication. |
restart_lsn, confirmed_flush_lsn, sent_lsn, write_lsn, flush_lsn, replay_lsn | Positions. |
retained_wal_bytes | WAL kept on disk for this slot. |
pending_wal_bytes | WAL the subscriber has not confirmed yet. |
write_lag, flush_lag, replay_lag, last_reply_time | Feedback timing. |
wal_status, safe_wal_size, catalog_xmin, catalog_xmin_age, temporary, two_phase | From pg_replication_slots; a growing catalog_xmin_age means the slot holds back catalog vacuum. |
decoded_txns, decoded_bytes, spill_*, stream_*, decode_stats_reset | Decoding work done for the slot, from pg_stat_replication_slots. Growing spill_bytes means transactions larger than logical_decoding_work_mem. |
slot_group_* | Shared state of the slot group, for parallel slots only. |
Peers, replication sets and settings
spock.peer_status lists every node in spock.node with its interfaces
(passwords hidden), whether it is the local node, and the subscription that
brings its changes here with that subscription’s status and lag. A node
with several subscriptions has one row per subscription.
spock.replication_set_status lists the replication sets of the local node
with their replicate flags, the number of tables and sequences in each, and
how many local subscriptions include the set. Tables that are in no set at
all are listed by spock.tables where set_name IS NULL.
spock.settings shows every spock.* parameter and the core parameters
replication depends on (wal_level, max_worker_processes,
max_replication_slots, max_wal_senders, max_slot_wal_keep_size,
track_commit_timestamp, shared_preload_libraries, the walsender and
walreceiver timeouts, synchronous commit settings and
logical_decoding_work_mem), with unit, source and whether a restart is
pending. Connection strings in parameters have their password hidden.
Events
spock.events is a ring of recent state changes kept in shared memory,
oldest first. The number of events kept is set by
spock.event_history_size. The history is cleared by a postmaster restart,
and spock.reset_events() clears the events of the current database.
| Column | Description |
|---|---|
event_id | Increases by one per event and is never reused. |
event_time, event_type, severity | When, what, and info, warning or error. |
sqlstate | The SQLSTATE of a worker_error or stream_error event. |
subscription_id, subscription_name, provider_node | The subscription concerned, if any, and the node its changes come from. |
pid | The reporting process. |
lsn | The provider LSN the event refers to: the start position of a stream, the commit LSN of a skipped, discarded or failed transaction, the position a subscription was disabled at. NULL for lifecycle events such as worker starts. |
detail | A short description. |
Event types:
| Type | Recorded when |
|---|---|
node_created, node_dropped | spock.node_create() and spock.node_drop() complete. |
subscription_created, subscription_dropped | A subscription is created or dropped. |
subscription_enabled, subscription_disabled | A subscription is enabled or disabled, by an operator or by exception handling. |
subscription_altered | Interface, replication sets, skip_lsn, options or a synchronization request changed. |
worker_started, worker_stopped, worker_failed | A manager, apply or sync worker starts, exits cleanly, or exits with an error. |
worker_error | An error is raised inside an apply or sync worker. The detail carries the message with DETAIL and CONTEXT. |
provider_connected, provider_disconnected | The replication connection to the named provider is established, with the start LSN, or lost, with the error. |
transaction_skipped, transaction_discarded | A transaction is skipped through sub_skip_lsn or discarded under transdiscard. |
sync_started, sync_finished, sync_failed | Initial copy of a table. sync_failed carries the error that ended the copy; the next sync worker for that table records a second sync_failed saying the table was abandoned after the earlier failure, and no further attempt is made. |
slot_created, stream_started, stream_stopped, stream_error | Provider side: a spock slot is created, a walsender starts streaming to a subscriber (its address, spock version and protocol in the detail, the slot position in lsn), stops (recorded as the walsender exits, so a subscriber that disconnects or restarts produces one), or fails with an error while decoding. |
apply_paused, apply_resumed | spock.pause_apply_workers() and spock.resume_apply_workers(). |
repair_mode_enabled, repair_mode_disabled | spock.repair_mode(). |
extension_upgraded | The manager updated the extension to the library version. |
Events are recorded when the reporting code runs, whether or not the surrounding transaction commits.
The full report
spock.node_report() returns the whole node as text, section by section:
system status, installed extensions, settings, node status, peers,
subscriptions, subscription statistics, workers, pending exceptions,
replication slots, replication sets, tables in no replication set, table
synchronization, lag by node pair, recent exceptions, recent conflict
resolutions and recent events. Wide views are printed one row per block,
lists as aligned tables. A section whose query fails, for example
node_status for a role without EXECUTE on the functions behind it,
prints one error line and the report continues.
In psql, \pset format unaligned and \o report.txt before the call
produce a plain file that can be attached to a ticket. The report contains
no passwords.
spock.report_section(title, query, expanded) is the formatter behind
the report and can render any query the same way.
Common tasks
The recipes below cover the questions that used to require the server log.
Run them in psql with expanded output (\x) when a row is wide.
Is the node healthy?
One row answers it. Anything other than zero in workers_restart_pending,
a difference between subscriptions_enabled and subscriptions_replicating,
or a last_error_event_time that is more recent than you expect deserves a
look.
Why is a subscription not replicating?
Start with the subscription row. status tells whether a worker runs at
all, worker_status and worker_terminated_at show a failed worker
waiting for its restart delay, and last_error_message is the error the
worker last raised, without opening the log.
Then read the events of that subscription, newest first:
A subscription that was disabled by exception handling shows a
subscription_disabled event with the detail disabled by exception handling and the origin LSN of the failing transaction in lsn; the row in
spock.exception_log has the failing tuple.
Is a worker blocked or deadlocking?
A worker waiting for a lock shows wait_event_type = 'Lock' and the
session holding the lock in blocked_by_pids and blocking_query. A
deadlock or lock timeout aborts the transaction; the worker exits and is
restarted, and the error is classified.
Is a worker restarting in a loop?
worker_starts and worker_failures climb together when the apply worker
crashes on every attempt. The events show the interval and the reason. Sync
workers have their own pair of counters, so a resync of many tables does
not look like a restart loop here.
What changed overnight?
Everything that is not routine has a severity above info.
Enable and disable calls, interface switches, replication set changes,
sub_skip_lsn, pause and resume, repair mode and extension upgrades are
all info or warning events with the operator’s backend pid in pid.
How far behind is each provider?
replication_lag_bytes is WAL the provider has written that this node has
not applied yet. replication_lag is the time between the last applied
commit on the provider and its apply here. Both come from
spock.progress and are also available per node pair in
spock.lag_tracker.
Is a slot holding back WAL on the provider?
Run this on the provider. A slot with active = false or a growing
retained_wal_bytes points at a subscriber that is down or lagging.
Is the initial synchronization finished?
The row without a table is the subscription itself. Sync workers in flight
are listed in spock.worker_status with worker_type = 'sync' and the
table they copy.
Did the extension get upgraded?
spock.node_status compares the loaded library with the installed
extension. After a binary upgrade the manager updates the extension on its
next start and records the change.
Starting a fresh measurement
Counters and events accumulate since the postmaster started. Reset them before a benchmark or after fixing an incident so that the next numbers are clean.
spock.reset_channel_stats() clears the per-table tuple counters
separately.
Watching from outside
The views are plain SQL, so any monitoring agent can poll them. Poll
spock.events by event_id to fetch only new rows, and treat a gap in
ids as history that was dropped because spock.event_history_size was too
small for the polling interval. spock.get_monitor_summary() reports how
full the event ring and the counters table are. The read-only views and
the functions they call are granted to pg_monitor; the role also needs
USAGE on the schema:
For now, USAGE on the spock schema also allows calling spock’s
management functions. Grant it only to trusted roles, and treat every
function that changes something as needing a superuser. Members of
pg_monitor cannot reset counters or events: spock.reset_events() and
spock.reset_subscription_stats() stay with the superuser. The
node_report() sections on spock.tables, spock.lag_tracker,
spock.exception_log and spock.resolutions need SELECT on those,
which the grant does not include; without it each shows as one error line.
Underlying functions
The views are built on functions that return the raw shared memory contents. They are useful for tooling that wants unfiltered rows.
| Function | Returns |
|---|---|
spock.get_worker_status() | Every worker slot of the cluster, with database_id. |
spock.get_events() | Every event in the history, with database_id. Superuser or pg_monitor. |
spock.get_apply_stats() | The counters of every subscription of the current database. Superuser or pg_monitor. |
spock.get_slot_groups() | Slot groups with attached walsenders. |
spock.get_monitor_summary() | Capacity and usage of the shared memory structures. |
spock.get_system_info() | Host name, operating system, CPU, memory, load averages, disk space of the data and WAL volumes, postmaster start, PostgreSQL and spock versions. Superuser or pg_monitor; the data directory only with pg_read_all_settings. |
spock.get_pending_exceptions() | Transactions being retried under exception handling, with their first error and the position of the failing change in the transaction. Superuser or pg_monitor. |
spock.replication_origin_status() | Every replication origin with its remote progress, as pg_replication_origin_status shows a superuser. Superuser or pg_monitor. |
spock.reset_events() | Clears the event history of the current database. Superuser only. |
spock.reset_subscription_stats(subid) | Resets the activity and conflict counters of one or all subscriptions. Superuser only. |
spock.redact_dsn(text) | Returns a connection string with its password hidden. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.10.4 - Using spock.sync_event to Confirm Synchronization
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sync_event enables event tracking and synchronization between a
provider and a subscriber node in a Spock logical replication setup. You can
use spock.sync_event to ensure that all changes up to a specific point
(indicated by the PostgreSQL Log Sequence Number or LSN) on the provider have
been received and applied on the subscriber.
To mark the start of the sync event and return the LSN of the event on the subscriber node, you call a function on the node you have selected to act as a provider node:
spock.sync_event()
Then, you monitor a procedure on the node you have selected to act as the subscriber node that detects the presence of the LSN, and confirms when it has been received and applied:
spock.wait_for_sync_event(...) (see the Synopsis for the
required arguments)
Synopsis
Invoked on the provider node, this function returns the current pg_lsn
value, representing a point-in-time value for your replication scenario. The
syntax of spock.sync_event is:
spock.sync_event(transactional boolean DEFAULT false) RETURNS pg_lsn
When transactional is false (the default), the sync event marker is
emitted into the WAL stream immediately, independent of the calling
transaction. When transactional is true, the marker is bound to the
calling transaction and is only visible to subscribers if the transaction
commits.
Invoked on a subscriber node, spock.wait_for_sync_event is available in two
flavors - the first uses the origin_id (an oid) as an identifier for the
node, while the second uses the node name as an identifier:
spock.wait_for_sync_event(OUT result boolean, origin_id oid, lsn pg_lsn, timeout int DEFAULT 0, wait_if_disabled bool DEFAULT false)spock.wait_for_sync_event(OUT result boolean, origin name, lsn pg_lsn, timeout int DEFAULT 0, wait_if_disabled bool DEFAULT false)
This procedure waits on the subscriber node to alert you when the specified LSN (from the provider) is received and applied to the node.
Parameters:
origin_idororigin: Identifies the provider node (by OID or name).lsn: The target LSN to wait for.timeout: (Optional) Number of seconds to wait before timing out. The default is 0 (wait indefinitely).wait_if_disabled: (Optional) Controls how a missing or disabled subscription is handled. The default isfalse.When
wait_if_disabledisfalse(the default), the procedure requires the subscription from the origin node to this node to already exist and be enabled. It raises an error if no such subscription is found, or if the subscription is disabled at any point while waiting:When
wait_if_disabledistrue, neither condition is an error. The procedure keeps polling until the subscription exists, becomes enabled, and reaches the target LSN, or untiltimeoutexpires. Use this when the subscription may not be ready yet - for example on a newly added node whose subscriptions are still being created, or while a subscription is temporarily disabled during a maintenance operation. Because a missing subscription is not reported, pass a non-zerotimeoutso a subscription that is never created does not wait forever.wait_if_disabledonly affects the subscription checks. It does not suppress the argument validation both flavors perform first, so these are still raised immediately regardless of its value:In particular, the name-based flavor requires the origin node to already be registered in
spock.node. If you are waiting on a node that is still joining the cluster, that row may not exist yet either - resolve theorigin_idonce the node is registered, or retry the call.
Returns:
result = true- LSN has been received and applied.result = false- Timeout occurred before the LSN was reached. Withwait_if_disabled = truethis also covers the case where the subscription never existed or never became enabled within the timeout.
Examples
On a provider node:
SELECT spock.sync_event();
-- Returns: 0/16342B0 (example output)
On a subscriber node:
The first parameter is the OUT result placeholder; pass NULL for it in
the CALL statement and read the OUT value from the procedure result.
To wait on a node whose subscription may not be created or enabled yet, pass
wait_if_disabled = true along with a timeout:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11 - Spock Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The following user functions are available via the Spock extension:
| Command | Description |
|---|---|
| Node Management Functions | You can add and remove nodes dynamically using Spock interfaces. |
| spock.node_info | Returns information about the node on which the function is invoked. |
| spock.node_create | Define a node for spock. |
| spock.node_drop | Remove a spock node. |
| node_add_interface | Add a new node interface. |
| spock.node_drop_interface | Delete a node interface. |
| spock.node_alter | Change this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set. |
| spock.node_refresh_info | Refresh this node’s cached copy of a peer’s (or every peer’s) location, country, and info. |
| Replication Set Management Functions | Replication sets provide a mechanism to control which tables in the database will be replicated and which actions on those tables will be replicated. Each replicated set can specify individually if INSERTs, UPDATEs, DELETEs and TRUNCATEs on the set are replicated. Each table can be in multiple replication sets, and each subscriber can subscribe to multiple replication sets. The resulting set of tables and actions replicated is the union of the sets the table is in. Spock installation creates three replication sets: default, default_insert_only and ddl_sql. The default replication set is defined to replicate all changes to tables in it. The default_insert_only replication set only replicates INSERT statements, and is meant for use by tables that don’t have primary key. The ddl_sql replication set is defined to replicate schema changes specified by spock.replicate_ddl. |
| spock.repset_create | Define a replication set. |
| spock.repset_alter | Modify a replication set. |
| repset_drop | Remove a replication set. |
| spock.repset_add_partition | Add a partition to a replication set. |
| spock.repset_remove_partition | Remove a partition from the replication set that the parent table is a part of. |
| spock.repset_add_table | Add table(s) to replication set. |
| spock.repset_add_all_tables | Add all existing table(s) to the replication set. |
| spock.repset_remove_table | Remove table from replication set. |
| spock.repset_show_table | |
| spock.repset_add_seq | Adds a sequence to a replication set. |
| spock.repset_add_all_seqs | Adds all sequences from the specified schemas to a replication set. |
| spock.repset_remove_seq | Remove a sequence from a replication set. |
| spock.sync_seq | Synchronize the specified sequence. |
| Subscription Management Functions | |
| spock.sub_create | Create a subscription. |
| spock.sub_drop | Delete a subscription. |
| spock.sub_disable | Put a subscription on hold, and disconnect from the provider. |
| spock.sub_enable | Make a subscription live. |
| spock.sub_add_repset | Add a replication set to a subscription. |
| spock.sub_remove_repset | Drop a replication set from a subscription. |
| spock.sub_show_status | Display the status of the subcription. |
| spock.sub_show_table | Show subscription tables. |
| spock.sub_alter_interface | Modify an interface to a subscription. |
| spock.sub_wait_for_sync | Pause until the subscription is synchronized. |
| spock.sub_alter_skiplsn | Skip transactions until the specified lsn. |
| spock.sub_alter_sync | Synchronize all missing tables. |
| spock.sub_alter_options | Change one or more subscription options in a single atomic operation. |
| spock.sub_resync_table | Synchronize a specific table. |
| Miscellaneous Management Functions | |
| spock.table_wait_for_sync | Pause until a table finishes synchronizing. |
| spock.replicate_ddl | Enable DDL replication. |
| spock_version | Returns the Spock version in a major/minor version form: 4.0.10. Defined in the public schema so invoked without the spock. prefix. |
| spock_version_num | Returns the Spock version in a single numeric form: 40010. Defined in the public schema so invoked without the spock. prefix. |
| spock.get_channel_stats | Returns tuple traffic statistics. |
| spock.get_apply_stats | Returns the activity counters of every subscription; the source of the spock.subscription_stats view. |
| spock.get_events | Returns the recent events of the node; the source of the spock.events view. |
| spock.get_monitor_summary | Returns capacity and usage of the spock shared memory structures. |
| spock.get_pending_exceptions | Returns the transactions apply workers are retrying under exception handling. |
| spock.get_system_info | Returns host, operating system and version information of the node. |
| spock.get_slot_groups | Returns the slot groups with attached walsenders. |
| spock.get_subscription_stats | Returns the conflict counters of a subscription (PostgreSQL 18 and later). |
| spock.get_worker_status | Returns every spock worker slot; the source of the spock.worker_status view. |
| spock.get_country | Returns the country code if explicitly set; returns ?? if not set. |
| spock.lag_tracker | Returns a list of slots, with commit_lsn and commit_timestamp for each. |
| spock.repair_mode | Used to manage the state of replication - If set to true, stops replicating statements, including DDL; when false, resumes replication. |
| spock.replicate_ddl | Replicate a specific statement. |
| spock.redact_dsn | Returns a connection string with its password hidden. |
| spock.reset_channel_stats | Reset the channel statistics. |
| spock.reset_events | Clears the event history shown by spock.events. |
| spock.reset_subscription_stats | Resets the activity and conflict counters of one subscription, or of all subscriptions. |
| spock.report_section | Renders the rows of a query as an aligned text table or as one block per row. |
| spock.node_report | Returns the whole node as a text report: versions, settings and every monitoring view. |
| spock_max_proto_version | The highest Spock native protocol supported by the current binary/build. Defined in the public schema so invoked without the spock. prefix. |
| spock_min_proto_version | The lowest build for which this Spock binary is backward compatible. Defined in the public schema so invoked without the spock. prefix. |
| spock.table_data_filtered | Scans the specified table and returns rows that match the row filter from the specified replication set(s). Row filters are added to a replication set when adding a table with repset_add_table. |
| spock.terminate_active_transactions | Terminates all active transactions. |
| spock.wait_slot_confirm_lsn | Wait for the confirmed_flush_lsn of the specified slot, or all logical slots if none given. |
| spock.xact_commit_timestamp_origin | Returns the commit timestamp and origin of the specified transaction. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1 - Spock Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can access the reference pages in this section via online help; at the terminal window, enter:
command_name --help
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.1 - spock.cleanup_resolutions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.cleanup_resolutions() function manually deletes old rows from the
spock.resolutions table.
Synopsis
Description
Deletes rows from spock.resolutions whose log_time is older than the
retention window. Returns the number of rows deleted.
This function is a superuser-only manual trigger for the same cleanup that
the apply worker runs automatically once per day. It is useful for
immediate cleanup via pg_cron or when the apply worker has not been
running.
When days is provided it takes precedence over
spock.resolutions_retention_days, including when the GUC is set to 0
(automatic cleanup disabled). If days is omitted, the GUC value is used;
if the GUC is also 0, the function returns 0 without deleting anything.
Arguments
The function accepts the following argument:
days- Retention window in days. Overridesspock.resolutions_retention_daysfor this call. Pass an explicit value to perform a one-off cleanup when automatic cleanup is disabled (resolutions_retention_days = 0). Default isNULL(use the GUC value).
Example
Delete rows older than the configured retention window:
Delete rows older than 60 days, regardless of the GUC setting:
See Also
spock.resolutions_retention_days
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.2 - spock.gen_slot_name()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_gen_slot_name()
SYNOPSIS
spock.spock_gen_slot_name(dbname name, provider_node name, subscription name)
RETURNS
The generated replication slot name as a name type.
DESCRIPTION
Generates a standardized replication slot name for a Spock subscription.
This function creates a consistent naming convention for replication slots based on the database name, provider node name, and subscription name. The generated name follows Spock’s internal naming scheme to ensure uniqueness and traceability.
This function that performs a calculation without accessing the database or modifying any data. It can be used to predict what slot name Spock will generate for a given subscription configuration.
ARGUMENTS
dbname
The name of the database.
provider_node
The name of the provider node.
subscription
The name of the subscription.
EXAMPLE
The following example executes the function; the database name is postgres, the node name is n1, and the subscription name is sub_n2n1:
postgres=# SELECT spock.spock_gen_slot_name('postgres', 'n1', 'sub_n2n1');
spock_gen_slot_name
--------------------------
spk_postgres_n1_sub_n2n1
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.3 - spock.get_country()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.get_country()
SYNOPSIS
spock.get_country ()
RETURNS
The country code configured for the node as text, or ?? if not set.
DESCRIPTION
Returns the spock.country property that was set during node creation. You can modify the property after configuration; modification requires a server restart to apply the change.
This function retrieves the value of the spock.country configuration parameter for the current session. The country code is typically used in multi-region or geo-distributed replication topologies to identify the geographic location of nodes and apply region-specific routing or filtering rules.
This function does not modify any data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
If the spock.country parameter has not been set, the function returns:
postgres=# SELECT spock.get_country();
get_country
-------------
??
(1 row)
If spock.country is set to US, the function returns:
postgres=# SELECT spock.get_country();
get_country
-------------
US
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.4 - spock.max_proto_version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_max_proto_version()
SYNOPSIS
spock_max_proto_version()
RETURNS
The maximum spock protocol version supported by the installed Spock extension as an integer. The protocol version determines compatibility between Spock versions.
DESCRIPTION
Returns the maximum protocol version supported by the Spock extension.
This function queries the Spock extension and returns the highest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use the lower of the two maximum protocol versions. This ensures compatibility between nodes running different Spock releases.
The protocol version is returned as an integer value. Higher numbers indicate newer protocol versions with additional features.
This is a read-only query function that does not modify data. This function is defined in the public schema.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command shows that the current version of Spock uses protocol version 4:
postgres=# SELECT spock_max_proto_version();
spock_max_proto_version
-------------------------
4
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.5 - spock.min_proto_version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_min_proto_version()
SYNOPSIS
spock_min_proto_version()
RETURNS
The minimum Spock protocol version supported by the installed Spock extension as an integer. The protocol version determines compatibility between Spock versions.
DESCRIPTION
Returns the minimum protocol version supported by the Spock extension.
This function queries the Spock extension and returns the lowest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use a protocol version that falls within the supported range of both nodes. The minimum protocol version defines the lower bound of compatibility - nodes supporting only protocol versions below this minimum cannot replicate with this Spock installation.
The protocol version is returned as an integer value. This minimum version ensures backward compatibility with older Spock releases while still allowing the use of newer protocol features when both nodes support them.
This is a read-only query function that does not modify data. This function is defined in the public schema.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command shows that the version of Spock in use is using protocol version 3:
postgres=# SELECT spock_min_proto_version();
spock_min_proto_version
-------------------------
3
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.6 - spock.node_add_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_add_interface()
SYNOPSIS
spock.node_add_interface (node_name name, interface_name name, dsn text)
RETURNS
The OID of the newly created interface. Returns NULL if any argument is NULL.
DESCRIPTION
Adds a new network interface definition to an existing Spock node; the network interface has an associated connection string that is used when the interface is referenced by other nodes.
Interfaces allow a single node to be reachable through multiple connection endpoints. This is commonly used in environments where nodes are accessible through different hostnames, IP addresses, private networks, public networks, or load balancers.
The interface definition consists of a name and a PostgreSQL DSN string that describes how other nodes should connect to this node.
This function writes metadata into the Spock catalogs but does not modify PostgreSQL server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
The name of an existing Spock node.
interface_name
A unique name for this interface on the node.
dsn
A PostgreSQL connection string that other nodes will use to connect to this node. The user in this string should equal the OS user. This connection string should be reachable from outside and match the one used later in the sub-create command. For example: host=10.1.2.5 port=5432 user=rocky
EXAMPLE
The following example adds an interface named private_net that uses the connection string defined in the last argument of the function call (‘host=10.0.0.10 port=5432 dbname=postgres’):
postgres=# SELECT spock.node_add_interface('n1', 'private_net',
'host=10.0.0.10 port=5432 dbname=postgres');
node_add_interface
--------------------
1239112588
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.7 - spock.node_alter()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_alter()
SYNOPSIS
spock.node_alter (p_location text DEFAULT NULL, p_country text DEFAULT NULL, p_info_patch jsonb DEFAULT NULL)
RETURNS
true on success. Raises an error if p_info_patch is not a JSON object,
or if it contains a tiebreaker key that is not a JSON number, is not a
whole number, or does not fit a 32-bit integer.
DESCRIPTION
Changes the local node’s own location, country, and/or info, merging
p_info_patch into the existing info rather than replacing it. Only
this node’s own row can be altered – there is no node_name argument,
since (unlike spock.node_refresh_info) there is only ever one valid
target: the local node.
Any omitted argument (left NULL) is left unchanged: p_location and
p_country each independently overwrite only if non-NULL, and
p_info_patch is merged key-by-key into the existing info (via ||)
only if non-NULL – an existing key not mentioned in the patch is left
as-is, not removed.
A tiebreaker key inside p_info_patch is validated: it must be a JSON
number (not a string, and not JSON null), a whole number, and fit a
32-bit integer, or the call raises an error and changes nothing. This is
the safe way to change a node’s tiebreaker; see the Tiebreaker section in
conflict_types.md for what the tiebreaker
does and why validation matters here.
This ends in the same UPDATE spock.node that a hand-written UPDATE
would use, so it propagates identically: automatically to every direct
subscriber of this node (see
Automatic node metadata propagation),
with no manual step required. A raw UPDATE spock.node SET ... on this
node’s own row remains fully supported and behaves the same way –
spock.node_alter exists to validate the input and merge info safely,
not to gate access to the underlying table.
ARGUMENTS
p_location
Optional. Replaces this node’s location. Left unchanged if omitted
(or NULL).
p_country
Optional. Replaces this node’s country. Left unchanged if omitted
(or NULL).
p_info_patch
Optional. A JSON object merged into this node’s existing info
(existing keys not mentioned are preserved). Left unchanged if
omitted (or NULL). A tiebreaker key, if present, must be a JSON
number representable as a 32-bit integer.
EXAMPLE
Assign a custom tiebreaker on n1, without disturbing any other info
keys already set:
n1=# SELECT spock.node_alter(p_info_patch => '{"tiebreaker": 42}'::jsonb);
node_alter
------------
t
(1 row)
Every direct subscriber of n1 picks this up automatically – no
spock.node_refresh_info call needed:
n2=# SELECT info->>'tiebreaker' FROM spock.node WHERE node_name = 'n1';
?column?
----------
42
(1 row)
Update location and country together in one call:
n1=# SELECT spock.node_alter(p_location => 'us-east', p_country => 'US');
node_alter
------------
t
(1 row)
An invalid tiebreaker is rejected and changes nothing:
n1=# SELECT spock.node_alter(p_info_patch => '{"tiebreaker": "42"}'::jsonb);
ERROR: invalid "tiebreaker" value "42": must be a JSON number, not a string or null
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.8 - spock.node_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_create()
SYNOPSIS
spock.node_create (node_name name, dsn text, location text, country text, info jsonb)
RETURNS
The OID of the newly created Spock node.
DESCRIPTION
Creates a new Spock node definition.
A node represents a PostgreSQL instance that participates in Spock replication. The node definition includes the connection information that other nodes will use to communicate with this node.
Optional metadata fields such as location, country, and info can be provided to describe the node for organizational or management purposes. These values are stored in the Spock catalogs but are not required for replication to function.
This function writes metadata into the Spock catalogs but does not modify Postgres server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
A unique name for the Spock node.
dsn
A PostgreSQL connection string that other nodes will use to connect to this node.
location
Optional descriptive text indicating the physical or logical location of the node. The default is NULL.
country
Optional country code or name associated with the node. The default is NULL.
info
Optional JSONB field for storing arbitrary metadata about the node. The default is NULL.
A tiebreaker key in this field overrides the node’s default
last-update-wins tiebreaker (otherwise the node’s unique ID). Each
node caches this value locally, populated once when it first learns
about the node. A later change (via spock.node_alter, the
recommended way, or a raw UPDATE) propagates automatically to every
direct subscriber. spock.node_refresh_info updates a node that missed
the change – see the Tiebreaker section in conflict_types.md for
details.
EXAMPLE
In the following example, Spock creates a node named n3, with a connection to a database named ‘inventory’:
inventory=# SELECT spock.node_create('n3','host=10.0.0.12 port=5432 dbname=inventory');
node_create
-------------
9057
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.9 - spock.node_drop_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_drop_interface()
SYNOPSIS
spock.node_drop_interface (node_name name, interface_name name)
RETURNS
true if the interface was dropped successfully.
Raises an ERROR if the interface does not exist, the call has invalid parameters or insufficient privileges, or the interface cannot be removed.
DESCRIPTION
Removes an existing network interface definition from a Spock node.
This function deletes the interface definition from the Spock catalogs. It does not modify PostgreSQL server configuration or networking settings; it only removes Spock’s logical representation of the interface.
Other nodes that were using this interface to connect will no longer be able to use it. To avoid a client error, ensure that no active subscriptions rely on this interface before attempting to remove it.
This function writes metadata into the Spock catalogs but does not modify PostgreSQL server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
The name of an existing Spock node.
interface_name
The name of the interface to remove from the node.
EXAMPLE
The following example drops an interface named ‘private_net’:
inventory=# SELECT spock.node_drop_interface('n3', 'private_net');
node_drop_interface
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.10 - spock.node_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_drop()
SYNOPSIS
spock.node_drop(node_name name, ifexists boolean)
RETURNS
true if the node was dropped successfully.
false if the node did not exist and ifexists was set to true.
ERROR if the call has invalid parameters, if the invoker has insufficient privileges, or the node cannot be removed due to existing dependencies.
DESCRIPTION
Removes an existing Spock node from the cluster metadata.
This function deletes the node definition and all associated metadata from the Spock catalogs. It does not remove any PostgreSQL data directory or stop the PostgreSQL server; it only removes Spock’s logical representation of the node.
If ifexists is set to false (default), an error is raised when the specified node does not exist. If ifexists is true, the function returns false instead of raising an error.
This command must be executed by a superuser and modifies Spock catalog tables.
ARGUMENTS
node_name
The name of the existing Spock node to remove.
ifexists
If true, do not raise an error when the node does not exist; return false instead. Default is false.
EXAMPLE
The following function call drops a node named ’n3':
inventory=# SELECT spock.node_drop('n3');
node_drop
-----------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.11 - spock.node_info()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_info()
SYNOPSIS
spock.node_info()
RETURNS
A record containing information about the local Spock node:
- node_id is the OID of the node.
- node_name is the name of the node.
- sysid is the system identifier.
- dbname is the database name.
- replication_sets is the available replication sets.
- location is the node location (if set).
- country is the node country (if set).
- info is additional metadata stored in JSONB format (if set).
DESCRIPTION
Returns information about the local Spock node.
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This is a read-only query function that does not modify data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
postgres=# SELECT * FROM spock.node_info();
-[ RECORD 1 ]----+--------------------------------------
node_id | 49708
node_name | n1
sysid | 7600444661598442547
dbname | postgres
replication_sets | "default",default_insert_only,ddl_sql
location |
country |
info |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.12 - spock.node_refresh_info()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_refresh_info()
SYNOPSIS
spock.node_refresh_info (p_node_name name DEFAULT NULL)
RETURNS
true if the refresh (or, with no argument, every refresh attempted)
succeeded; false if one or more nodes could not be refreshed when called
with no argument. Raises an error if called with a specific node_name
that does not exist or that names the local node, or if refreshing that
node fails for any reason – including an unreachable or misconfigured
interface, a dsn that now answers as a different node, or any other error
from the remote fetch.
DESCRIPTION
Re-fetches a known peer node’s location, country, and info (including
any tiebreaker key within info) directly from that node, and overwrites
this node’s locally cached copy.
spock.node is a local catalog: each node populates its row for a peer
once, either when that node is created or when a subscription to it is
first created. A peer’s later location/country/info change – most
commonly to assign a custom tiebreaker and resolve an equal-tiebreaker
collision – propagates automatically to every node that subscribes to
that peer directly (see
Automatic Node Metadata Propagation),
with no call to this function needed. The message is not forwarded, and a
node normally has a row for a peer only through its own subscription to it,
so a cascade node that does not subscribe to the changed peer has no row to
refresh. This function is needed when a node’s cached row missed an update,
for example because the transaction carrying it was skipped or discarded,
and to force a specific peer’s info to be re-fetched on demand.
spock.sub_resync_table() warns when the provider’s row differs from the
cached one. See the Tiebreaker section in
conflict_types.md for why this matters and why
spock.node is not simply replicated wholesale.
Called with a specific node_name, only that node’s row is refreshed and
any failure refreshing it is reported as an error. Called with no
argument, every known node other than the local one is refreshed on a
best-effort basis: a node that fails to refresh for any reason logs a
WARNING and does not stop the others from being refreshed, and the
overall return value is false if any node failed.
This command must be executed by a superuser.
ARGUMENTS
p_node_name
Optional. The name of a single peer node to refresh. If omitted (or NULL), every node other than the local one is refreshed.
EXAMPLE
After assigning a custom tiebreaker on n1 to resolve a collision:
n1=# UPDATE spock.node SET info = COALESCE(info, '{}'::jsonb) ||
'{"tiebreaker": 42}' WHERE node_name = 'n1';
Refresh that on every other node:
n2=# SELECT spock.node_refresh_info('n1');
node_refresh_info
--------------------
t
(1 row)
Or refresh everything this node knows about in one call:
n3=# SELECT spock.node_refresh_info();
node_refresh_info
--------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.13 - spock.replicate_ddl()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.replicate_ddl()
SYNOPSIS
spock.replicate_ddl (command text[], replication_sets text[], search_path text, role text)
RETURNS
true if the DDL command was successfully executed and queued for replication.
false if the command execution fails or replication queueing fails.
When called with a text array, returns a set of boolean values, one for each command in the array.
DESCRIPTION
Executes DDL commands locally and queues them for replication to subscribers.
This function runs the specified DDL command on the local node first, then adds it to the replication queue for execution on all subscriber nodes that are subscribed to one of the specified replication sets.
The function accepts either a single DDL command as text or an array of DDL commands. When provided with an array, each command is executed and queued sequentially.
The search_path and role parameters allow you to control the execution context for the DDL command on both the provider and subscriber nodes.
This function writes to the replication queue and modifies the database schema locally before propagating changes.
This command must be executed by a user with sufficient privileges to execute the DDL command.
ARGUMENTS
command
A DDL command as text, or an array of DDL commands to execute and replicate.
replication_sets
An array of replication set names. Only subscribers subscribed to one of these sets will receive and execute the DDL. Default is ‘{ddl_sql}’.
search_path
The schema search path to use when executing the DDL command. Default is the current session’s search_path setting.
role
The role (user) under which to execute the DDL command. Default is the current user.
EXAMPLES
The following command creates a table and instructs Spock to replicate the DDL to other nodes:
postgres=# SELECT spock.replicate_ddl('CREATE TABLE users (id SERIAL PRIMARY KEY,
name TEXT)');
-[ RECORD 1 ]-+--
replicate_ddl | t
The following command alters the table adding a column, and instructs Spock to replicate the DDL to other nodes:
postgres=# SELECT spock.replicate_ddl('ALTER TABLE users ADD COLUMN email TEXT',
'{default,ddl_sql}');
-[ RECORD 1 ]-+--
replicate_ddl | t
The following command creates a table and an index on the tables, and instructs Spock to replicate DDL to other nodes:
postgres=# SELECT spock.replicate_ddl(ARRAY['CREATE TABLE orders (id SERIAL)',
'CREATE INDEX ON orders(id)']);
-[ RECORD 1 ]-+--
replicate_ddl | t
-[ RECORD 2 ]-+--
replicate_ddl | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.14 - spock.repset_add_all_seqs()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_all_seqs()
SYNOPSIS
spock.repset_add_all_seqs (set_name name, schema_names text[], synchronize_data boolean)
RETURNS
true if all sequences were successfully added to the replication set.
ERROR if the call has invalid parameters, insufficient privileges, or the operation fails.
DESCRIPTION
Adds all existing sequences from the specified schemas to a replication set.
This function registers all sequence objects found in the given schemas with the specified replication set. Only sequences that exist at the time of execution are added; sequences created afterward must be added separately using spock.repset_add_seq().
The synchronize_data parameter controls whether sequence values are immediately synchronized across nodes. When set to true, the current value of each sequence is propagated to subscribers.
This function writes metadata into the Spock catalogs to track which sequences are part of the replication set.
This command must be executed by a superuser.
Warning: If you’re deploying a multi-master replication scenario, we recommend that you not add sequences to a replication set. Instead, use Snowflake Sequences to manage sequences in a distributed environment and avoid conflicts.
ARGUMENTS
set_name
The name of an existing replication set.
schema_names
An array of schema names from which all sequences will be added.
synchronize_data
If true, synchronize the current value of each sequence immediately. Default is false.
EXAMPLE
You can specify one or more schemas in the call to repset_add_all_seqs. The first command adds the sequences in the ‘public’ schema to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_all_seqs('default', ARRAY['public']);
-[ RECORD 1 ]-------+--
repset_add_all_seqs | t
The following command adds all sequences in the schemas named ‘public’ and ‘alice’ to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_all_seqs('default', ARRAY['public', 'alice'],true);
-[ RECORD 1 ]-------+--
repset_add_all_seqs | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.15 - spock.repset_add_all_tables()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_all_tables()
SYNOPSIS
spock.repset_add_all_tables (set_name name, schema_names text[], synchronize_data boolean)
RETURNS
true if every replicatable table was added to the replication set.
false if the call has invalid parameters, insufficient privileges, or the operation fails.
DESCRIPTION
Adds all existing tables from the specified schemas to a replication set.
This function registers all table objects found in the given schemas with the specified replication set. Only tables that exist at the time of execution are added; tables created afterward must be added separately using spock.repset_add_table().
A table that cannot be replicated is skipped and reported with a WARNING naming its schema and table; the remaining tables are still added. A table is skipped when the replication set replicates UPDATEs or DELETEs and the table has no index-based replica identity, or when the table belongs to an extension listed in spock.reserved_object. A schema listed in spock.reserved_object is reported once and passed over as a whole.
A replication set that replicates UPDATEs or DELETEs has to locate the affected row on the subscriber, so it can only take tables with an index-based replica identity — a PRIMARY KEY, or a unique index on NOT NULL columns nominated with ALTER TABLE … REPLICA IDENTITY USING INDEX. Note that REPLICA IDENTITY FULL and REPLICA IDENTITY NOTHING do not qualify, even when the table has a PRIMARY KEY. Tables without an index-based replica identity can be added to a set that replicates only INSERTs and TRUNCATEs.
Unlike spock.repset_add_table(), which raises an error when the table cannot be replicated, this function never refuses the whole call on account of a single relation. A schema that does not exist is still an error.
Views, materialized views, sequences, and UNLOGGED and TEMPORARY tables are not considered at all.
Partitioned tables and their partitions are collected independently, each in its own right, and each is checked separately. ALTER TABLE … REPLICA IDENTITY does not cascade to partitions in any supported PostgreSQL version, so a partitioned table and its partitions can differ here: a partition may be skipped while its parent is added, or the reverse. Spock resolves replication set membership per relation, so a skipped partition means changes to the rows stored in that partition are not replicated, even when the parent is a member.
The synchronize_data parameter controls whether existing table data is immediately synchronized to subscribers. When set to true, a full table copy is initiated for each table on all subscribers subscribed to the replication set.
This function writes metadata into the Spock catalogs to track which tables are part of the replication set.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
schema_names
An array of schema names from which all tables will be added.
synchronize_data
If true, synchronize existing table data to all subscribers immediately. Default is false.
EXAMPLE
Specify the names of one or more schemas in an array to add all of the tables in the schemas to the specified replication set; the following command adds all of the tables in the public schema to the default replication set:
postgres=# SELECT spock.repset_add_all_tables('default', ARRAY['public']);
-[ RECORD 1 ]---------+--
repset_add_all_tables | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.16 - spock.repset_add_partition()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset-add-partition ()
SYNOPSIS
spock.repset_add_partition ( parent regclass, partition regclass, row_filter text)
RETURNS
0 if the parent table is not a partitioned table or if all partitions are already in the replication sets.
A positive integer indicating the count of partitions successfully added to replication sets.
DESCRIPTION
Adds a partition of a table to the same replication set(s) as its parent table.
This function is used when working with partitioned tables to ensure that new or existing partitions are properly included in replication. If the partition argument is omitted, Spock automatically discovers and adds all partitions of the specified parent table.
An optional row_filter can be supplied to limit which rows from the partition are replicated.
This function writes metadata into the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
parent
The parent partitioned table, specified as a regclass.
partition
A specific partition table to add. If omitted, all partitions of the parent are added. The default is NULL.
row_filter
An optional SQL expression used to filter which rows from the partition are replicated. The default is NULL.
EXAMPLE
Add all four partitions of a parent table (named ‘public.sales_parent’) to the replication set to which the parent belongs:
SELECT spock.repset_add_partition('public.sales_parent');
-[ RECORD 1 ]--------+--
repset_add_partition | 4
Add a specific partition (named public.sales_2026_q1) to the replication set to which the parent table belongs:
postgres=# SELECT spock.repset_add_partition(
'public.sales_parent',
'public.sales_2026_q1',
'region = ''US'''
);
-[ RECORD 1 ]--------+--
repset_add_partition | 1
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.17 - spock.repset_add_seq()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_seq()
SYNOPSIS
spock.repset_add_seq ( set_name name, relation regclass, synchronize_data boolean)
RETURNS
- true if the sequence was successfully added to the replication set.
- Raises an ERROR if the sequence is already a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a sequence to an existing Spock replication set.
Once added, changes to the sequence value are replicated to subscribers that are subscribed to the replication set. This ensures that nextval operations remain consistent across nodes in a multi-master environment.
If synchronize_data is true, the current sequence value is immediately synchronized to all subscribers.
This function updates metadata stored in the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The sequence to add, specified as a regclass (for example, ‘public.my_sequence’).
synchronize_data
If true, the current sequence value is synchronized to all subscribers. The default is false.
EXAMPLE
Add a sequence (named public.sales_order_no_seq) to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_seq('default', 'public.sales_order_no_seq');
repset_add_seq
----------------
t
(1 row)
Add a sequence (named public.sales_invoice_no_seq) and synchronize its current value:
postgres=# SELECT spock.repset_add_seq(
'default',
'public.sales_invoice_no_seq',
synchronize_data := true
);
repset_add_seq
----------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.18 - spock.repset_add_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_table()
SYNOPSIS
spock.repset_add_table ( set_name name, relation regclass, synchronize_data boolean, columns text[], row_filter text, include_partitions boolean )
RETURNS
- true if the table was successfully added to the replication set.
- Raises an ERROR if the table is already a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a specific table to an existing Spock replication set.
This function allows fine-grained control over what data is replicated by optionally specifying:
- A subset of columns to replicate.
- A row filter to restrict which rows are replicated.
- Whether partitions of a partitioned table should also be included.
If synchronize_data is set to true, existing table data is copied to all subscribers that are subscribed to this replication set. Otherwise, only future changes are replicated.
When used with partitioned tables, include_partitions controls whether child partitions are automatically included in the replication set.
This function writes metadata into the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The table to add, specified as a regclass (for example, ‘public.mytable’).
synchronize_data
If true, existing table data is synchronized to all subscribers. Default is false.
columns
An optional list of column names to replicate. If NULL, all columns are replicated.
row_filter
An optional SQL WHERE clause used to filter which rows are replicated.
include_partitions
If true and the table is partitioned, all partitions are included automatically. Default is true.
EXAMPLE
The following command adds a table named public.accounts to the demo_repset replication set with full replication:
SELECT spock.repset_add_table('demo_repset', 'public.accounts');
The following command adds a table named public.accounts to the demo_repset replication set, and synchronizes existing data:
SELECT spock.repset_add_table('demo_repset',
'public.accounts',
synchronize_data := true);
The following command adds only specific columns (id and balance) from the public.accounts table to the demo_repset replication set, and filters the rows:
SELECT spock.repset_add_table('demo_repset',
'public.accounts',
columns := ARRAY['id','balance'],
row_filter := 'balance > 0');
WARNING: Use caution when synchronizing data with a valid row filter.
Using synchronize_data=true with a valid row_filter is usually a
one-time operation for a table. Executing it again with a modified
row_filter won’t synchronize data to the subscriber. You may need to call
spock.sub_resync_table() to fix it.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.19 - spock.repset_alter()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_alter()
SYNOPSIS
spock.repset_alter ( set_name name, replicate_insert boolean, replicate_update boolean, replicate_delete boolean, replicate_truncate boolean )
RETURNS
The OID of the altered replication set.
DESCRIPTION
Modifies the replication behavior of an existing Spock replication set.
Each replication set defines which types of table operations are replicated to subscribers. This function allows you to change those behaviors after the set has been created.
Any argument left as NULL will retain its current setting. Only the specified operation types are modified.
This function updates metadata in the Spock catalogs and does not change PostgreSQL server configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
replicate_insert
If true, INSERT operations are replicated; the default is NULL.
replicate_update
If true, UPDATE operations are replicated; the default is NULL.
replicate_delete
If true, DELETE operations are replicated; the default is NULL.
replicate_truncate
If true, TRUNCATE operations are replicated; the default is NULL.
EXAMPLE
The following command enables all operations in the demo_repset replication set:
postgres=# SELECT spock.repset_alter('demo_repset',
replicate_insert := true,
replicate_update := true,
replicate_delete := true,
replicate_truncate := true);
repset_alter
--------------
3356172311
(1 row)
The following command disables DELETE and TRUNCATE replication in the audit_only replication_set:
postgres=# SELECT spock.repset_alter('audit_only',
replicate_delete := false,
replicate_truncate := false);
repset_alter
--------------
3744767607
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.20 - spock.repset_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_create()
SYNOPSIS
spock.repset_create ( set_name name, replicate_insert boolean = true, replicate_update boolean = true, replicate_delete boolean = true, replicate_truncate boolean = true )
RETURNS
The OID of the newly created replication set.
DESCRIPTION
Creates a new Spock replication set.
A replication set defines which types of table operations are replicated to subscribers. Tables can later be added to this replication set with other Spock functions.
By default, all data modification operations are replicated; INSERT, UPDATE, DELETE, and TRUNCATE.
You can selectively disable specific operation types when creating the set.
This function writes metadata into the Spock catalogs but does not alter any PostgreSQL server configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The unique name for the replication set.
replicate_insert
If true (the default), INSERT operations are replicated.
replicate_update
If true (the default), UPDATE operations are replicated.
replicate_delete
If true (the default), DELETE operations are replicated.
replicate_truncate
If true (the default), TRUNCATE operations are replicated.
EXAMPLE
The following example creates a replication set named demo_repset; all operations are replicated to the set:
postgres=# SELECT spock.repset_create('demo_repset');
repset_create
---------------
3356172311
(1 row)
The following command creates a replication set named audit_only; only INSERT and UPDATE statements are replicated:
postgres=# SELECT spock.repset_create('audit_only',
replicate_delete := false,
replicate_truncate := false);
repset_create
---------------
3744767607
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.21 - spock.repset_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_drop()
SYNOPSIS
spock.repset_drop (set_name name, ifexists boolean)
RETURNS
true if the replication set was successfully dropped.
false if the replication set does not exist and ifexists is true.
ERROR if the replication set does not exist and ifexists is false.
DESCRIPTION
Drops an existing replication set.
This function removes a replication set from the Spock configuration. When a replication set is dropped, all table, sequence, and DDL memberships associated with it are removed. However, the actual tables and sequences themselves remain in the database - only their association with the replication set is deleted.
Dropping a replication set does not affect existing subscriptions that reference it, but those subscriptions will stop receiving changes for objects that were in the dropped replication set. Subscriptions can be modified to remove the dropped replication set using spock.sub_remove_repset().
The ifexists parameter controls error-handling behavior for the function; when set to true, the function returns false if the replication set does not exist instead of raising an error. This is useful in situations where the replication set may or may not be present.
This function modifies the Spock catalogs but does not modify any user data or the Postgres server configuration.
ARGUMENTS
set_name
The name of the replication set to drop.
ifexists
If true, the function returns false instead of raising an error when the replication set does not exist. Defaults to false.
EXAMPLE
The following command drops a replication set named demo_repset; it does not raise an error if the set does not exist:
postgres=# SELECT spock.repset_drop('demo_repset', true);
repset_drop
-------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.22 - spock.repset_remove_partition()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_partition()
SYNOPSIS
spock.repset_remove_partition (parent regclass, partition regclass)
RETURNS
The number of partitions removed from replication sets as an integer.
DESCRIPTION
Removes a partition or all partitions of a partitioned table from the replication sets that include the parent table.
This function removes partition tables from replication without affecting the parent table’s replication membership. When a specific partition is provided, only that partition is removed. When the partition parameter is NULL, all partitions of the parent table are removed from replication.
This is useful when you want to exclude specific partitions from replication while keeping the parent table and other partitions replicated. For example, you might want to replicate recent partitions but not historical data stored in older partitions.
Removing a partition from replication does not drop the partition table itself - it only removes the partition from the replication sets. The partition remains in the database and can still be accessed locally.
The function returns the count of partitions that were actually removed from replication sets. If no partitions were removed (because they were not in any replication sets), it returns 0.
This function modifies the Spock catalogs but does not modify any user data or PostgreSQL server configuration.
ARGUMENTS
parent
The parent partitioned table whose partition(s) should be removed from replication.
partition
The specific partition to remove from replication. If NULL, all partitions of the parent table are removed. Defaults to NULL.
EXAMPLE
SELECT spock.repset_remove_partition('public.mytable',
'public.mytable_202012');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.23 - spock.repset_remove_seq()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_seq ()
SYNOPSIS
spock.repset_remove_seq ( set_name name, relation regclass)
RETURNS
- true if the sequence was successfully removed from the replication set.
- Raises an ERROR if the sequence is not a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Removes a sequence from an existing Spock replication set.
After removal, changes to the sequence value are no longer replicated to subscribers of the replication set.
This function updates metadata stored in the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The sequence to remove, specified as a regclass (for example, ‘public.my_sequence’).
EXAMPLE
Remove a sequence (public.orders_id_seq) from a replication set (demo_repset):
postgres=# SELECT spock.repset_remove_seq('demo_repset', 'public.orders_id_seq');
repset_remove_seq
-------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.24 - spock.repset_remove_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_table ()
SYNOPSIS
spock.repset_remove_table ( set_name name, relation regclass, include_partitions boolean)
RETURNS
- true if the table was successfully removed from the replication set.
- Raises an ERROR if the table is not a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Removes a table from an existing Spock replication set. After removal, changes to this table will no longer be replicated to subscribers that are subscribed to the replication set.
If the table is partitioned, the include_partitions argument controls whether all child partitions are also removed from the replication set.
This function updates metadata stored in the Spock catalogs and does not modify the PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The table to remove, specified as a regclass (for example, ‘public.mytable’).
include_partitions
If true and the table is partitioned, all partitions are also removed from the replication set. Default is true.
EXAMPLE
Remove a table (public.users) from the default replication set:
postgres=# SELECT spock.repset_remove_table('default', 'public.users');
repset_remove_table
---------------------
t
(1 row)
Remove a partitioned table named public.sales_parent from the default replication set without removing its partitions:
postgres=# SELECT spock.repset_remove_table('default',
'public.users',
include_partitions := false);
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.25 - spock.repset_show_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_show_table()
SYNOPSIS
spock.repset_show_table (relation regclass, repsets text[])
RETURNS
A record containing detailed information about how a table is configured for replication:
- relid is the OID of the table relation.
- nspname is the schema name of the table.
- relname is the table name.
- att_list is an array of column names included in replication.
- has_row_filter is true if a row filter is applied to the table.
- relkind is the relation kind (‘r’ for regular table, ‘p’ for partitioned table).
- relispartition is true if the table is a partition of a partitioned table.
DESCRIPTION
Returns detailed replication configuration information for a specific table within the specified replication sets.
This function queries how a table is configured for replication across one or more replication sets. It shows which columns are included in replication, whether row filtering is applied, and metadata about the table type and partition status.
The att_list field shows the specific columns that will be replicated. If all columns are replicated, this will contain all column names. If column filtering was configured when the table was added to a replication set, only the specified columns appear in this list.
The has_row_filter field indicates whether a row filter expression is applied to the table, which would limit which rows are replicated based on custom criteria.
The repsets parameter allows you to check the table’s configuration across multiple replication sets. The function returns information based on how the table is configured in those sets.
This is a read-only query function that does not modify any data.
ARGUMENTS
relation
The table to query information about.
repsets
An array of replication set names to check the table’s configuration within.
EXAMPLE
The following command shows detailed information about the public.invoices table:
postgres=# SELECT * FROM spock.repset_show_table('public.invoices',
ARRAY['default', 'ddl_sql']);
-[ RECORD 1 ]--+-----------------------------------------
relid | 17241
nspname | public
relname | invoices
att_list | {order_id,customer_id,order_date,amount}
has_row_filter | f
relkind | r
relispartition | f
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.26 - spock.sub_add_repset()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_add_repset()
SYNOPSIS
spock.sub_add_repset (subscription_name name, replication_set name)
RETURNS
true if the replication set was successfully added.
Raises an ERROR if the subscription does not exist, the replication set is already attached, or the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a replication set to an existing subscription.
This function modifies a subscription to begin receiving changes from an additional replication set on the provider node. The subscription will start consuming events from the newly added replication set immediately.
This operation does not perform data synchronization. It only activates the consumption of future events from the replication set. If you need to synchronize existing data from the replication set, you must handle that separately.
This function writes metadata into the Spock catalogs.
Returns NULL if any argument is NULL.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
replication_set
The name of the replication set to add to the subscription.
EXAMPLE
The following example adds a replication set named audit_only to a subscription named sub_n2_n1:
postgres=# SELECT spock.sub_add_repset('sub_n2_n1', 'audit_only');
-[ RECORD 1 ]--+--
sub_add_repset | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.27 - spock.sub_alter_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_interface()
SYNOPSIS
spock.sub_alter_interface (subscription_name name, interface_name name)
RETURNS
true if the interface was successfully changed.
Raises an ERROR if the subscription or interface does not exist, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Changes the network interface used by a subscription to connect to its provider node.
This function modifies an existing subscription to use a different interface when establishing the replication connection to the provider. The specified interface must already exist on the provider node.
This is useful for switching between different network paths, such as moving from a public network to a private network connection, or switching to a different hostname or IP address for the same provider node.
The subscription connection will be restarted using the new interface.
This function writes metadata into the Spock catalogs.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
interface_name
The name of an existing interface on the provider node.
EXAMPLE
The following example modifies the interface used when connecting to the replication cluster to use the connection string associated with an interface named private_net:
postgres=# SELECT spock.sub_alter_interface('sub_n2_n1', 'private_net');
sub_alter_interface
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.28 - spock.sub_alter_options()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_options()
SYNOPSIS
spock.sub_alter_options (subscription_name name, options jsonb)
RETURNS
true if the
optionsobject contained at least one key; the Spock catalog is updated and the apply worker is signalled to restart.false if the
optionsobject was empty ({}); the catalog is not touched and the apply worker is not restarted.Raises an ERROR if the subscription does not exist, if
optionsis not a JSON object, if an unrecognised key is supplied, or if any option value fails validation.
DESCRIPTION
Changes one or more options on an existing subscription in a single atomic operation.
Only the keys present in the options object are modified; omitted
options retain their current values. If the object is empty ({}), the
function returns false without touching the catalog or restarting the
apply worker.
When at least one key is present in options, the function writes the
new values to the Spock catalog and signals the apply worker to restart
so that they take effect. The caller can use spock.sub_show_status()
or spock.sub_wait_for_sync() to confirm the worker has restarted and
reached replicating status.
ARGUMENTS
subscription_name
The name of an existing subscription.
options
A JSON object whose keys are the option names to change. Unrecognised keys raise an error. Supported keys:
forward_origins
A JSON array of origin names whose transactions the subscriber should apply or receive based on their origin. The only accepted element is the string “all”. Pass an empty array ([]) to disable origin forwarding.
See Origin Forwarding for the restriction on combining this with other enabled subscriptions.
apply_delay
A PostgreSQL interval string (e.g. “2 seconds”, “500ms”, “0”) that sets how long the apply worker waits before applying each transaction. The value must be a string; passing a bare number raises an error.
skip_schema
A JSON array of schema names to exclude from apply. Pass an empty array ([]) to clear the exclusion list.
EXAMPLE
Set a 2-second apply delay:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1',
'{"apply_delay": "2 seconds"}');
sub_alter_options
-------------------
t
(1 row)
Enable forwarding of all origins and exclude the audit schema in a
single call:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1',
'{"forward_origins": ["all"], "skip_schema": ["audit"]}');
sub_alter_options
-------------------
t
(1 row)
No-op call (empty object); returns false without restarting the worker:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1', '{}');
sub_alter_options
-------------------
f
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.29 - spock.sub_alter_skiplsn()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_skiplsn()
SYNOPSIS
spock.sub_alter_skiplsn (subscription_name name, lsn pg_lsn) RETURNS boolean
RETURNS
true if the skip LSN was successfully set, false otherwise.
DESCRIPTION
Advances the replication position of an existing subscription to the specified Log Sequence Number (LSN). This is typically used as a recovery operation when a subscription is unable to proceed due to a problematic change in the replication stream. Any changes between the old LSN and the specified LSN will be permanently skipped.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
lsn
The Log Sequence Number to which the subscription should advance.
EXAMPLE
SELECT spock.sub_alter_skiplsn('sub_n1_to_n2', '0/16B6A50');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.30 - spock.sub_alter_sync
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_alter_sync() function synchronizes all unsynchronized tables
in all sets in a single operation.
Synopsis
Description
The spock.sub_alter_sync() function synchronizes all unsynchronized tables
in all sets in a single operation. The function copies and synchronizes
tables one by one. The function does not wait for completion before returning
to the caller; use spock.sub_wait_for_sync() to wait for completion.
Arguments
The function accepts the following arguments:
- The
subscription_nameargument specifies the name of an existing subscription. - The
truncateargument accepts a boolean value; when set totrue, the function truncates tables before copying, and the default value isfalse.
Example
In the following example, the spock.sub_alter_sync() function synchronizes
all unsynchronized tables for a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.31 - spock.sub_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_create()
SYNOPSIS
spock.sub_create (subscription_name name, provider_dsn text, replication_sets text[], synchronize_structure boolean, synchronize_data boolean, forward_origins text[], apply_delay interval, force_text_transfer boolean, enabled boolean, skip_schema text[])
RETURNS
The OID of the newly created subscription.
DESCRIPTION
Creates a subscription from the current node to a provider node.
This function establishes a replication subscription that allows the current (subscriber) node to receive changes from the specified provider node. The subscription defines which replication sets to subscribe to and how to handle initial synchronization.
The command returns immediately without waiting for the subscription to complete its initialization. Use spock.sub_wait_for_sync() to wait for the subscription to finish synchronizing and begin replicating.
The subscription_name is used as the application_name for the replication connection, making it visible in pg_stat_replication. This can be useful for monitoring and for configuring synchronous_standby_names in synchronous replication scenarios.
This function writes metadata into the Spock catalogs and initiates a replication connection to the provider.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
A unique name for the subscription. Must be unique across the cluster. This name appears in pg_stat_replication as application_name.
provider_dsn
A PostgreSQL connection string specifying how to connect to the provider node.
replication_sets
An array of replication set names to subscribe to. Accepted values are default, default_insert_only, ddl_sql.
synchronize_structure
If true, synchronize table and schema structure from the provider before starting replication. Default is false.
synchronize_data
If true, perform an initial data copy for all tables in the subscribed replication sets. Default is false.
forward_origins
Controls which changes to replicate based on their origin. Use ‘{}’ to
only replicate changes originating locally on the provider node (origin ID 0,
i.e. not already replicated in from another node — useful for bidirectional
replication to avoid forwarding changes in a loop). Use {all} to replicate all
changes regardless of origin. The default is {} (local-origin changes only).
See Origin Forwarding for the restriction on combining this with other enabled subscriptions.
apply_delay
An interval specifying how long to delay applying changes from the provider. Useful for delayed standby scenarios. Default is ‘0’.
force_text_transfer
If true, replicate all columns using text representation. This is slower but allows type conversions on the subscriber. Default is false.
enabled
If true, the subscription is enabled immediately. If false, the subscription is created but not activated. Default is true.
skip_schema
An array of schema names to exclude from structure and data synchronization. Default is ‘{}’ (no schemas skipped).
EXAMPLE
SELECT spock.sub_create('sub_n2_n1',
'host=127.0.0.1 port=5432 dbname=postgres');
SELECT spock.sub_create('sub_n2_n1',
'host=10.0.0.10 port=5432 dbname=postgres',
replication_sets := '{default}',
synchronize_structure := true,
synchronize_data := true);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.32 - spock.sub_disable
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_disable() function disables a subscription and disconnects
from the provider.
Synopsis
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.immediate- Iftrue, the subscription is disabled immediately; otherwise it is disabled at the end of the current transaction. The default isfalse.
Example
In the following example, the spock.sub_disable() function disables a
subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.33 - spock.sub_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_drop()
SYNOPSIS
spock.sub_drop (subscription_name name, ifexists boolean)
RETURNS
The OID of the dropped subscription.
DESCRIPTION
Disconnects and removes a subscription from the cluster.
This function terminates the replication connection for the specified subscription and removes all associated metadata from the Spock catalogs. It does not affect data that has already been replicated to the subscriber.
If ifexists is set to false (default), an error is raised when the specified subscription does not exist. If ifexists is true, the function returns successfully without error.
Returns NULL if any argument is NULL.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of the existing subscription to remove.
ifexists
If true, do not raise an error when the subscription does not exist. Default is false.
EXAMPLE
SELECT spock.sub_drop('sub_n2_n1');
SELECT spock.sub_drop('sub_n2_n1', true);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.34 - spock.sub_enable
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_enable() function enables a subscription. Replication workers
then resume normal processing for that subscription.
Synopsis
Description
The spock.sub_enable() function enables a subscription.
This fails if another subscription on this node already has origin forwarding active; see Origin Forwarding.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.immediate- Iftrue, the subscription is started immediately; otherwise the subscription will be started only at the end of the current transaction. The default isfalse.
Example
In the following example, the spock.sub_enable() function enables a
subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.35 - spock.sub_remove_repset
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_remove_repset() function removes a replication set from a
subscription.
Synopsis
Description
The spock.sub_remove_repset() function removes a replication set from a
subscription.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.replication_set- The name of the replication set to remove.
Example
In the following example, the spock.sub_remove_repset() function removes a
replication set named test from a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.36 - spock.sub_resync_table
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_resync_table() function resynchronizes one existing table.
Synopsis
Description
The spock.sub_resync_table() function resynchronizes one existing table.
After the resynchronization is scheduled, the function compares the cached
spock.node row of the subscription’s provider with the provider’s own row.
If they differ, it raises a WARNING that suggests
spock.node_refresh_info(). The check does not
change spock.node, and a provider that cannot be reached for the check
produces a WARNING without failing the resynchronization.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.relation- The name of an existing table, optionally schema qualified.truncate- Truncate the table before synchronization; the default value istrue. Omitting the argument truncates the target table. Passfalseto keep existing rows. In that case, conflicting incoming rows can cause errors.
Example
In the following example, the spock.sub_resync_table() function
resynchronizes a table named public.users for a subscription named
sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.37 - spock.sub_show_status
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_show_status() function displays the status and basic
information about a subscription.
Synopsis
Returns
A set of rows describing the current state of one or more subscriptions. Each row contains:
- the name of the subscription.
- the current replication status.
- the name of the provider node.
- the connection string used to reach the provider.
- the name of the logical replication slot used by the subscription.
- the replication sets associated with the subscription.
- the origins that are forwarded by this subscription.
Status Values
The following table describes each possible value for the status
column:
| Status | Description |
|---|---|
replicating | The apply worker is running and initial synchronization is complete; changes from the provider are being applied normally. |
initializing | The apply worker is running but initial synchronization has not yet completed; table data is still being copied from the provider. |
disabled | The subscription was explicitly disabled with spock.sub_disable(); the apply worker is not running. |
down | The subscription is enabled but the apply worker is not running; the worker may not have started yet or may have exited unexpectedly. |
unknown | The apply worker is running but no synchronization status record was found; this is a transient state that typically resolves quickly. |
Description
spock.sub_show_status() displays detailed runtime information about
Spock subscriptions on the current node.
If a specific subscription name is provided, only that subscription is
shown. If NULL (the default), the function returns status for all
subscriptions on the node.
This function is useful for monitoring replication health, validating configuration, and verifying which replication sets and origins are in use. The information is derived from Spock catalog metadata and the current state of logical replication workers.
This function does not modify any configuration.
Arguments
subscription_name- The optional name of an existing subscription. If no name is provided, the function shows the status for all subscriptions on the local node.
Example
To display the status of all subscriptions, run:
In the following example, the spock.sub_show_status() function displays the
status of a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.38 - spock.sub_show_table
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_show_table() function displays the synchronization status of a
table.
Synopsis
Description
The spock.sub_show_table() function shows the synchronization status of a
table.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.relation- The name of an existing table, optionally qualified.
Example
In the following example, the spock.sub_show_table() function displays the
synchronization status of a table named test for a subscription named
sub_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.39 - spock.sub_wait_for_sync
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_wait_for_sync() function waits until a specified subscription
has completed its initial schema and data synchronization.
Synopsis
Description
The spock.sub_wait_for_sync() function waits until the specified subscription
has completed its initial schema and data synchronization, and any pending
table resynchronizations have finished.
This function blocks the current session until the subscription is fully synchronized. The function monitors both the initial sync phase (if the subscription is newly created) and any tables that are undergoing individual resynchronization due to replication set changes or manual resync operations.
For optimal results, execute spock.wait_slot_confirm_lsn() on the provider
node after making replication set changes that trigger resyncs. This approach
ensures the provider has flushed all necessary changes before checking sync
status on the subscriber. Only after the provider confirms the LSN should you
call spock.sub_wait_for_sync() on the subscriber.
The function will continue waiting indefinitely until synchronization completes, so callers should ensure the subscription is actively processing and that there are no blocking issues preventing sync completion.
Arguments
The function accepts the following argument:
subscription_name- The name of the subscription to monitor for sync completion.
Example
In the following example, the spock.sub_wait_for_sync() function waits for a
subscription named sub_n2_n1 to complete synchronization:
For more information about using subscription synchronization with Zero-Downtime Add Node, see the ZODAN Tutorial.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.40 - spock.sync_event
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sync_event() function creates a synchronization event in the
replication stream and returns its Log Sequence Number (LSN).
Synopsis
Returns
The function returns the Log Sequence Number (LSN) of the created
synchronization event as pg_lsn.
Description
The spock.sync_event() function creates a synchronization event in the
replication stream and returns its LSN.
This function inserts a special synchronization marker into the logical
replication stream at the current write position. The returned LSN identifies
this marker’s location in the write-ahead log and can be used with functions
like spock.wait_slot_confirm_lsn() to verify that subscribers have processed
replication up to this point.
Synchronization events are useful for coordinating activities across multiple nodes in a replication topology. By creating a sync event on a provider and then waiting for subscribers to reach that LSN, you can ensure all nodes have processed a consistent set of changes before proceeding with operations that depend on synchronized state.
The sync event itself does not contain data or modify any tables; the event serves purely as a coordination marker in the replication stream.
This function modifies the replication stream by inserting a sync marker.
Arguments
transactional(optional, defaultfalse) - Whenfalse, the sync event marker is emitted immediately into the WAL stream, independent of the calling transaction. Whentrue, the marker is bound to the calling transaction and is only visible to subscribers if the transaction commits.
Example
In the following example, the spock.sync_event() function creates a
synchronization event and returns the LSN:
For more information about using synchronization events with Zero-Downtime Add Node, see the ZODAN Tutorial.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.41 - spock.sync_seq
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sync_seq() function synchronizes the current state of a sequence
to all subscribers.
Synopsis
Description
Captures the current value of a sequence on the provider node and pushes it into the replication stream so that subscribers can update their local copy to match. This ensures sequence values remain coordinated across nodes.
This function must be executed on the provider node. The sequence state update is embedded in the transaction where this function is called, and subscribers apply the update when they replicate that transaction.
Replication set filtering applies — only subscribers whose subscriptions include the replication set containing this sequence will receive the update.
Arguments
The function accepts the following argument:
relation- The name of the sequence to synchronize, optionally schema-qualified.
Example
In the following example, the spock.sync_seq() function synchronizes a
sequence named public.sales_order_no_seq:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.42 - spock.table_wait_for_sync()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.table_wait_for_sync()
SYNOPSIS
spock.table_wait_for_sync (subscription_name name, relation regclass)
RETURNS
void (returns nothing upon successful completion).
DESCRIPTION
Waits until the specified table has completed synchronization for the given subscription.
This function blocks the current session until the specified table finishes its synchronization process. This is useful when you need to ensure a specific table is fully synchronized before proceeding with operations that depend on its data.
Unlike spock.sub_wait_for_sync() which waits for all tables in a subscription to sync, this function targets a single table. This allows for more granular control when monitoring synchronization progress or when only specific tables are critical to downstream operations.
For optimal results, execute spock.wait_slot_confirm_lsn() on the provider node after making replication set changes that trigger table resyncs. This ensures the provider has flushed all necessary changes before checking sync status on the subscriber. Only after the provider confirms the LSN should you call spock.table_wait_for_sync() on the subscriber.
The function will continue waiting indefinitely until the table synchronization completes, so callers should ensure the subscription is actively processing and that there are no blocking issues preventing sync completion.
ARGUMENTS
subscription_name
The name of the subscription to monitor.
relation
The name of the table to wait for, specified as a regclass (can be schema-qualified).
EXAMPLE
SELECT spock.table_wait_for_sync('sub_n2_n1', 'public.mytable');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.43 - spock.version_num()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_version_num()
SYNOPSIS
spock.spock_version_num ()
RETURNS
The version number of the installed Spock extension as an integer.
DESCRIPTION
Returns the version number of the Spock extension as an integer.
This function queries the Spock extension and returns its version encoded as an integer value. The integer format allows for easy version comparison in SQL queries without string parsing.
The integer typically represents the version in a format like XXYYZZ where XX is the major version, YY is the minor version, and ZZ is the patch version. For example, version 3.1.0 might be represented as 30100.
This is a read-only query function that does not modify any data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command returns the current Spock extension version as an integer:
postgres=# SELECT spock.spock_version_num();
-[ RECORD 1 ]-----+------
spock_version_num | 50005
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.44 - spock.version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_version()
SYNOPSIS
spock.spock_version ()
DESCRIPTION
Returns the Spock version in a human-readable major/minor form (for example, 5.0.5).
EXAMPLE
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.45 - spock.wait_slot_confirm_lsn()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.wait_slot_confirm_lsn()
SYNOPSIS
spock.wait_slot_confirm_lsn (slotname name, target pg_lsn)
RETURNS
void (returns nothing upon successful completion).
DESCRIPTION
Waits until the specified replication slot has confirmed receipt of changes up to the target Log Sequence Number (LSN).
This function blocks the current session until the replication slot’s confirmed flush LSN reaches or exceeds the specified target LSN. This is useful for ensuring that a subscriber has received and acknowledged replication changes before proceeding with subsequent operations.
The confirmed flush LSN represents the position up to which the subscriber has successfully received, applied, and durably stored the replicated changes. This function provides a synchronization mechanism to coordinate activities between the provider and subscriber nodes.
If the replication slot does not exist, the function will raise an error. The function will continue waiting indefinitely until the target LSN is reached, so callers should ensure the target LSN is reachable and that the subscription is actively processing changes.
This function does not modify any data but may block for an extended period depending on replication lag and network conditions.
ARGUMENTS
slotname
The name of the replication slot to monitor.
target
The target Log Sequence Number to wait for. The function returns when the slot’s confirmed flush LSN reaches or exceeds this value.
EXAMPLE
The following command waits for a slot named spock_local_sync_346_79a to confirm that it has received changes to the target LSN (0/3000000):
SELECT spock.wait_slot_confirm_lsn('spock_local_sync_346_79a',
'0/3000000');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.1.46 - spock.xact_commit_timestamp_origin()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.xact_commit_timestamp_origin()
SYNOPSIS
spock.xact_commit_timestamp_origin (xid xid, OUT timestamp timestamptz, OUT roident oid)
RETURNS
A record containing transaction commit information:
- timestamp is the commit timestamp of the transaction.
- roident is the replication origin identifier of the transaction.
DESCRIPTION
Returns the commit timestamp and replication origin identifier for a given transaction ID.
This function queries PostgreSQL’s commit timestamp tracking system to retrieve when a specific transaction was committed and which replication origin it came from. The replication origin identifies the source node in a multi-node replication topology, allowing you to trace where changes originated.
The commit timestamp tracking feature (track_commit_timestamp) must be enabled in PostgreSQL for this function to return meaningful results. If commit timestamp tracking is disabled, the function may return NULL or raise an error.
The replication origin identifier (roident) will be 0 for transactions
committed locally on this node (i.e., not replicated in from another node).
For replicated transactions, it identifies the origin node from which the
changes were received. A NULL result for the timestamp or origin means the
origin metadata is unavailable or unknown (for example, because
track_commit_timestamp was not enabled at the time of the commit) — NULL
is distinct from 0 and does not indicate a local change.
This is a read-only query function that does not modify any data.
ARGUMENTS
xid
The transaction ID to query.
EXAMPLE
SELECT * FROM spock.xact_commit_timestamp_origin('12345'::xid);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.2 - Management Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can use the following settings to manage your replication clusters.
| Command | Description |
|---|---|
| spock.get_country | Returns the country code configured for the node. |
| spock_max_proto_version | Returns the maximum protocol version supported by Spock. Defined in the public schema so invoked without the spock. prefix. |
| spock_min_proto_version | Returns the minimum protocol version supported by Spock. Defined in the public schema, so invoked without the spock. prefix. |
| spock.node_info | Returns information about the local Spock node. |
| spock_version | Returns the version string of the Spock extension. Defined in the public schema so invoked without the spock. prefix. |
| spock_version_num | Returns the version number of Spock as an integer. Defined in the public schema so invoked without the spock. prefix. |
spock.get_country
Use spock.get_country to retrieve the country code configured for the node.
spock.get_country()
Returns the spock.country property that was set during node creation. You
can modify the property after configuration; modification requires a server
restart to apply the change.
This function retrieves the value of the spock.country configuration parameter for the current session. The country code is typically used in multi-region or geo-distributed replication topologies to identify the geographic location of nodes and apply region-specific routing or filtering rules.
This function takes no arguments.
spock_max_proto_version
Use spock_max_proto_version to retrieve the maximum protocol version
supported by Spock.
spock_max_proto_version()
Returns the maximum protocol version supported by the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns the highest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use the lower of the two maximum protocol versions. This ensures compatibility between nodes running different Spock releases.
spock_min_proto_version
Use spock_min_proto_version to retrieve the minimum protocol version
supported by Spock.
spock_min_proto_version()
Returns the minimum protocol version supported by the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns the lowest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use a protocol version that falls within the supported range of both nodes. The minimum protocol version defines the lower bound of compatibility.
spock.node_info
Use spock.node_info to retrieve information about the local Spock node.
spock.node_info()
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This function takes no arguments.
spock_version
Use spock_version to retrieve the version string of the Spock extension.
spock_version()
Returns the version number of the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns its version as a text string. The version string typically follows semantic versioning format (for example, “4.0.1” or “5.0.4”).
spock_version_num
Use spock_version_num to retrieve the version number of Spock as an
integer.
spock_version_num()
Returns the version number of the Spock extension as an integer.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns its version encoded as an integer value. The integer format allows for easy version comparison in SQL queries without string parsing.
The integer typically represents the version in a format like XXYYZZ where XX is the major version, YY is the minor version, and ZZ is the patch version. For example, version 3.1.0 might be represented as 30100.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.3 - Node Management
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Use commands listed in this section to manage the nodes in your replication cluster.
| Command | Description |
|---|---|
| spock.node_add_interface | Add an additional interface to a node. |
| spock.node_create | Create a spock node. |
| spock.node_drop | Drop a spock node. |
| spock.node_drop_interface | Remove an existing interface from a node. |
| spock.node_info | Returns information about the local Spock node. |
| spock.node_alter | Change this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set. |
| spock.node_refresh_info | Refresh this node’s cached copy of a peer’s (or every peer’s) location, country, and info. |
Creating a Node
To create a node with Spock, connect to the server with psql and use the
spock.node_create command:
Parameters include:
- a name for the node.
- the dsn of the server on which the node resides.
The DSN is similar to a connection string to the node you’re creating.
For example, the DSN to connect to the acctg database with an ip
address of 10.1.1.1, using credentials that belong to carol would
be: host=10.1.1.1 user=carol dbname=acctg.
The location, country, and info are all optional inputs to label nodes
and have a default of null.
For example, the following command:
Creates a node named n1 that connects to the accounting database on
178.12.15.12, authenticating with the credentials of a user named carol.
Dropping a Node
To drop a node with Spock, connect to the server with psql, and use the
spock.node_drop command:
Parameters include:
- the name of the node.
ifexistsis a boolean value that suppresses an error if the node does not exist when set totrue.
For example, the following command:
Drops a node named n1. If the node does not exist, an error message will
be suppressed because ifexists is set to true.
Automatic Node Metadata Propagation
A change to a node’s own location, country, or info – whether via
spock.node_alter or a raw
UPDATE spock.node SET ... WHERE node_id = (SELECT node_id FROM spock.node_info())
– propagates automatically to every node that subscribes to it directly.
No manual step is required for a direct subscriber to pick up the change.
The message is not forwarded through a cascade topology (Node A → Node B →
Node C): only Node B, as A’s direct subscriber, receives A’s change. Node C
normally has no spock.node row for A unless it subscribes to A, so there
is nothing for it to update.
A node that has a row for the changed node but did not apply the message
keeps the old values. This happens when the transaction carrying the message
is skipped (for example with skip_lsn) or discarded by the exception
handling. Run spock.node_refresh_info
on that node to catch up. A table resynchronization does not replay these
messages, but spock.sub_resync_table() warns when the provider’s row
differs from the cached one.
An incoming change is applied only if the node named in the message has
the same node_id locally as the node that sent it. Otherwise it is
skipped and logged as a WARNING: either the name is unknown locally
(rows are never created from these messages), or the name and the
sender’s node_id disagree with the local copy. This is a defensive
check against a corrupted or misconfigured peer, not something normal
operation triggers.
Node Management Functions
You can add and remove nodes dynamically with the following SQL functions.
spock.node_create
Use spock.node_create to create a replication node.
spock.node_create(node_name name, dsn text, location text DEFAULT NULL, country text DEFAULT NULL, info jsonb DEFAULT NULL)
Parameters:
node_nameis the name of the new node; only one node is allowed per database.dsnis the connection string to the node. For nodes that are supposed to be providers, this should be reachable from the subscription nodes.location(optional) is a text label for the node’s physical location.country(optional) is a text label for the node’s country.info(optional) is a JSON object for any additional node metadata. Atiebreakerkey overrides the node’s default conflict-resolution tiebreaker; see the Tiebreaker section in conflict_types.md for how each node caches this independently and what that means for changing it cluster-wide.
spock.node_drop
Use spock.node_drop to drop a replication node.
spock.node_drop(node_name name, ifexists bool)
Parameters:
node_nameis the name of an existing node.ifexistsspecifies the Spock extension behavior with regards to error messages. Iftrue, an error is not thrown when the specified node does not exist. The default isfalse.
spock.node_add_interface
Use spock.node_add_interface to add an interface to a node.
spock.node_add_interface(node_name name, interface_name name, dsn text)
When a node is created, the interface for it is also created using the dsn
specified in the spock.node_create command, and with the same name as the node.
This interface allows adding alternative interfaces with different connection
strings to an existing node.
Parameters:
node_nameis the name of an existing node.interface_nameis the name of a new interface to be added.dsnis the connection string to the node used for the new interface.
spock.node_drop_interface
Use spock.node_drop_interface to remove an existing interface from a node.
spock.node_drop_interface(node_name name, interface_name name)
Parameters:
node_nameis the name of an existing node.interface_nameis the name of an existing interface.
spock.node_info
Use spock.node_info to return information about the local Spock node.
spock.node_info()
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This is a read-only query function that does not modify data.
Returns one row with the following columns:
| Column | Type | Description |
|---|---|---|
node_id | oid | The object identifier of the local node. |
node_name | text | The name of the local node. |
sysid | text | The PostgreSQL system identifier for this instance. |
dbname | text | The name of the current database. |
replication_sets | text | Comma-separated list of replication sets associated with this node. |
location | text | Optional location label; NULL if not set during node creation. |
country | text | Optional country label; NULL if not set during node creation. |
info | jsonb | Optional JSON metadata; NULL if not set during node creation. |
spock.node_alter
Use spock.node_alter to change the local node’s own location,
country, and/or info, merging info rather than replacing it, with a
tiebreaker key (if present in the patch) validated as a whole JSON
number that fits a 32-bit integer.
spock.node_alter(p_location text DEFAULT NULL, p_country text DEFAULT NULL, p_info_patch jsonb DEFAULT NULL)
Unlike spock.node_refresh_info, this only ever targets the local node –
there is no node-name argument. It ends in the same UPDATE spock.node
that a hand-written UPDATE would use, so it propagates the same way; see
Automatic Node Metadata Propagation
above. See spock_node_alter.md for full
details and examples.
Parameters:
p_location(optional) replaces this node’slocation; left unchanged if omitted.p_country(optional) replaces this node’scountry; left unchanged if omitted.p_info_patch(optional) is merged into this node’s existinginfo; left unchanged if omitted. Atiebreakerkey inside it must be a JSON number representable as a 32-bit integer, or the call raises an error and changes nothing.
spock.node_refresh_info
Use spock.node_refresh_info to refresh this node’s cached copy of a
peer’s location, country, and info (including any tiebreaker key
within info).
spock.node_refresh_info(p_node_name name DEFAULT NULL)
spock.node is a local catalog: each node populates its row for a peer
once, either when that node is created or when a subscription to it is
first created. A direct subscriber picks up a peer’s later changes
automatically – see
Automatic Node Metadata Propagation
above – but the message is not forwarded, and it is lost if the
transaction carrying it is skipped or discarded.
spock.node_refresh_info is the way to catch such a node up on demand, in
bulk for every known peer at once, or to recover a specific peer’s info
without waiting on it to change again. See the Tiebreaker section in
conflict_types.md.
Parameters:
p_node_name(optional) is the name of a single peer node to refresh. If omitted, every node other than the local one is refreshed, best-effort: a node that fails to refresh for any reason (an unreachable or misconfigured interface, a dsn that now answers as a different node, or any other error from the remote fetch) logs a warning rather than aborting the rest.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.4 - Replication Set Management
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Replication sets provide a mechanism to control which tables in the database will be replicated and which actions on those tables will be replicated. Use the following commands to create and manage replication sets.
| Command | Description |
|---|---|
| spock.repset_create | Create a new replication set. |
| spock.repset_alter | Modify an existing replication set. |
| spock.repset_drop | Remove a replication set. |
| spock.repset_add_table | Adds a table to replication set. |
| spock.repset_add_all_tables | Adds all tables in a given schema(s). |
| spock.repset_remove_table | Remove a table from replication set. |
| spock.repset_add_seq | Adds a sequence to a replication set. |
| spock.repset_add_all_seqs | Adds all sequences from the given schemas. |
| spock.repset_remove_seq | Remove a sequence from a replication set. |
| spock.sub_add_repset | Adds a replication set to a subscriber. |
| spock.sub_remove_repset | Removes a replication set from a subscriber. |
Creating a Replication Set
To create a replication set with Spock, connect to the server with psql and
use the spock.repset_create command:
Parameters include:
replication_set_nameis the name of the replication set.
Use the four remaining parameters to specify the content type to replicate:
- when
replicate_insertistrue,INSERTstatements are replicated; the default istrue. - when
replicate_updateistrue,UPDATEstatements are replicated; the default istrue. - when
replicate_deleteistrue,DELETEstatements are replicated; the default istrue. - when
replicate_truncateistrue,TRUNCATEstatements are replicated; the default istrue.
For example, the following command:
Adds a replication set named accts that replicates all statements except
TRUNCATE statements.
Adding a Table to a Replication Set
To add a table to a replication set with Spock, connect to the server with
psql and invoke the spock.repset_add_table command:
Parameters include:
set_nameis the name of an existing replication set.relationis the name or OID of the table to add.synchronize_datais a boolean value that instructs the server to synchronize table data on all related subscribers; the default isfalse.columnsspecifies a list of columns to replicate; the default isNULL(all columns).row_filteris a row filtering expression; the default isNULL(no filtering).include_partitionsis a boolean value; specifytrueto include all partitions; the default istrue.
For example, the following command:
Adds a table named payables to a replication set named accts. Since no
columns are specified, all columns will be replicated.
Reserved Schemas and Extensions
Some schemas and extensions are reserved and are treated specially by Spock.
They are listed in the spock.reserved_object catalog, which is the single
source of truth for three behaviours:
exclude_from_dump: the object is left out of the structure-sync dump used when a subscription synchronizes structure. Restoring these on a subscriber that already has them would fail.block_in_repset: a table in this schema, or belonging to this extension, may not be added to a replication set.replicate_ddl: whenfalse, AutoDDL keeps the object’s DDL node-local – it runs where issued but is not shipped to other nodes. The default istrue.For an extension,
CREATE EXTENSION,ALTER EXTENSION,DROP EXTENSION,COMMENT ON EXTENSIONandSECURITY LABEL ON EXTENSIONare kept local; run them on each node. ADROP EXTENSIONthat names both a node-local extension and a replicated one is refused while DDL replication is on; drop them in separate statements.CREATE EXTENSION ... CASCADEof a replicated extension that requires a node-local one is also refused, even when every required extension is already installed; create the node-local extension on each node first, then run theCREATE EXTENSIONwithoutCASCADE.spock.replicate_ddl()refuses all of these statements for a node-local extension. Whatever a statement on a node-local extension does withCASCADEalso stays on the local node: objects that depend on the extension are dropped only there, and extensions thatCREATE EXTENSION ... CASCADEinstalls are installed only there.A statement that removes a node-local extension without naming it is not caught:
DROP EXTENSION ... CASCADEof an extension it requires,DROP SCHEMA ... CASCADEof a schema it was created in, orDROP OWNED BYits owner. Such a statement replicates, and each peer must then drop the node-local extension from its apply worker. Drop the node-local extension on each node first.For a schema, only DDL whose target schema Spock can identify is kept local:
CREATESCHEMA/TABLE/TABLE AS/SEQUENCE/VIEW/INDEX,ALTER TABLE, andDROPof those object kinds. Other DDL against the schema (for exampleGRANT,COMMENT,TRUNCATE, orALTER ... SET SCHEMA) is not classified and replicates as usual. A singleDROPis kept local only when every object it names is node-local; do not mix a node-local object and a replicated one in oneDROP, as the shipped command cannot be rewritten to drop only the replicated object.
Spock seeds the following built-in rows, and they cannot be removed or modified:
| Object | exclude_from_dump | block_in_repset | replicate_ddl |
|---|---|---|---|
spock | yes | yes | yes |
snowflake | yes | yes | yes |
lolor | yes | no | yes |
coldfront | yes | no | yes |
pgedge_ace (schema only) | yes | yes | no |
spock, snowflake, lolor and coldfront each have both a schema and an
extension row. The replicate_ddl column above is the value on the
schema row. The extension rows have replicate_ddl = true (replicated),
except lolor, whose extension row is false: lolor refuses to be created
or dropped by an apply worker, so CREATE, ALTER and DROP EXTENSION lolor are run on each node instead of being replicated.
exclude_from_dump/block_in_repset apply to both rows.
lolor is excluded from the dump but is intentionally allowed in replication
sets: its tables must replicate so that large objects survive a
DROP EXTENSION on every node, not only where the drop was issued.
coldfront is the pgEdge tiered storage extension. Every node creates its
objects with its own CREATE EXTENSION coldfront, so structure sync leaves
them out. Its tables stay allowed in replication sets because Coldfront adds
several of them to the default set itself, among them the bakery claim
tables and the tiered view registry, to coordinate writes across the mesh.
The cold data behind a tiered view lives in shared Iceberg storage outside
PostgreSQL and is not replicated by Spock.
pgedge_ace is the schema used by the pgEdge ACE utility. It is node-local
configuration/state, not application data: its DDL is kept local for the
classified statement kinds above (replicate_ddl=no), and its tables can
never be added to a replication set (block_in_repset=yes), so
CREATE SCHEMA pgedge_ace and the tables underneath it stay local to the
node where they were issued.
To reserve an additional schema or extension of your own, use
spock.reserved_object_add:
Use spock.reserved_object_remove('ace', 'schema') to drop your own entry.
Reserved objects are node-local configuration: apply the same additions on
each node of the cluster. Operator-added rows are preserved across
pg_dump/pg_restore; the built-in rows are always re-seeded.
Removing a Table from a Replication Set
To remove a table from a replication set with Spock, connect to the server
with psql and invoke the spock.repset_remove_table command:
Parameters include:
set_nameis the name of the replication set in which the table resides.relationis the name or OID of the table that will be removed.include_partitionsis a boolean value; specifytrueto also remove partitions of the partitioned table; the default istrue.
For example, the following command:
Removes a table named payables from a replication set named accts.
Replication Set Management Functions
The following functions are provided for managing replication sets:
spock.repset_create
Use spock.repset_create to create a new replication set.
spock.repset_create(set_name name, replicate_insert bool, replicate_update bool, replicate_delete bool, replicate_truncate bool)
Parameters:
set_nameis the unique name of the set.replicate_insertistrueifINSERTstatements are replicated; the default istrue.replicate_updateistrueifUPDATEstatements are replicated; the default istrue.replicate_deleteistrueifDELETEstatements are replicated; the default istrue.replicate_truncateistrueifTRUNCATEstatements are replicated; the default istrue.
spock.repset_alter
Use spock.repset_alter to change the parameters of an existing replication
set.
spock.repset_alter(set_name name, replicate_insert bool DEFAULT NULL, replicate_update bool DEFAULT NULL, replicate_delete bool DEFAULT NULL, replicate_truncate bool DEFAULT NULL)
Parameters:
set_nameis the name of an existing replication set that will be modified by this function.replicate_insertistrueifINSERTstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_updateistrueifUPDATEstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_deleteistrueifDELETEstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_truncateistrueifTRUNCATEstatements are replicated. PassNULL(the default) to leave the current value unchanged.
spock.repset_drop
Use spock.repset_drop to remove the specified replication set.
spock.repset_drop(set_name name, ifexists boolean DEFAULT false)
Parameters:
set_nameis the name of an existing replication set.ifexistscontrols whether dropping a non-existent replication set raises an error. Whentrue, no error is raised if the set is missing; the default isfalse.
spock.repset_add_table
Use spock.repset_add_table to add a table to a replication set.
spock.repset_add_table(set_name name, relation regclass, synchronize_data boolean DEFAULT false, columns text[] DEFAULT NULL, row_filter text DEFAULT NULL, include_partitions boolean DEFAULT true)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the table to be added to the set.synchronize_dataistrueif the table data is to be synchronized on all subscribers which are subscribed to the specified replication set; the default isfalse.columnsis the list of columns to replicate. Normally when all columns should be replicated, this will be set toNULL(the default).row_filteris a row filtering expression; the default isNULL(no filtering).include_partitionsistrueto also add partitions of a partitioned table; the default istrue.
Use caution when synchronizing data with a valid row filter. Using
synchronize_data=true with a valid row_filter is usually a one-time
operation for a table. Executing it again with a modified row_filter
won’t synchronize data to subscriber. You may need to call
spock.sub_resync_table() to fix it.
spock.repset_add_all_tables
Use spock.repset_add_all_tables to add all tables in the specified schemas
to the replication set.
spock.repset_add_all_tables(set_name name, schema_names text[], synchronize_data boolean DEFAULT false)
Only existing tables are added; tables that will be created in the future will not be added automatically.
Parameters:
set_nameis the name of an existing replication set.schema_namesis an array of names of existing schemas from which tables should be added.synchronize_datainstructs Spock to synchronize the table data on all nodes which are subscribed to the given replication set when set totrue; the default isfalse.
spock.repset_remove_table
Use spock.repset_remove_table to remove a table from a replication set.
spock.repset_remove_table(set_name name, relation regclass, include_partitions boolean DEFAULT true)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the table to be removed from the set.include_partitionsistrueto also remove partitions of the partitioned table; the default istrue.
spock.repset_add_seq
Use spock.repset_add_seq to add a sequence to a replication set.
spock.repset_add_seq(set_name name, relation regclass, synchronize_data boolean DEFAULT false)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the sequence to be added to the set.synchronize_datainstructs Spock to synchronize the sequence on all nodes which are subscribed to the given replication set when set totrue; the default isfalse.
spock.repset_add_all_seqs
Use spock.repset_add_all_seqs to add all sequences from the given schemas.
spock.repset_add_all_seqs(set_name name, schema_names text[], synchronize_data boolean DEFAULT false)
Only existing sequences are added; any sequences that will be created in the future will not be added automatically.
Parameters:
set_nameis the name of an existing replication set.schema_namesis an array of names of existing schemas from which sequences should be added.synchronize_dataspecifytrueto synchronize the sequence value immediately; the default isfalse.
spock.repset_remove_seq
Use spock.repset_remove_seq to remove a sequence from a replication set.
spock.repset_remove_seq(set_name name, relation regclass)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the sequence to be removed from the set.
You can view information about which table(s) is in which replication set by
querying the spock.tables view.
spock.sub_add_repset
Use spock.sub_add_repset to add a replication set to a subscriber.
spock.sub_add_repset(subscription_name name, replication_set name)
Does not synchronize replication; only activates consumption of events.
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of replication set to add.
spock.sub_remove_repset
Use spock.sub_remove_repset to remove a replication set from a subscriber.
spock.sub_remove_repset(subscription_name name, replication_set name)
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of replication set to remove.
spock.reserved_object_add
Use spock.reserved_object_add to reserve a schema or extension (see
Reserved Schemas and Extensions). If the
object is already reserved, its flags are updated. Built-in objects cannot be
changed.
spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump bool DEFAULT true, p_block_in_repset bool DEFAULT true, p_replicate_ddl bool DEFAULT true)
Parameters:
p_nameis the schema or extension name.p_kindis'schema'or'extension'.p_exclude_from_dumpkeeps the object out of the structure-sync dump; the default istrue.p_block_in_repsetblocks the object from replication sets; the default istrue.p_replicate_ddl: passfalseto keep the object node-local so AutoDDL does not ship its DDL to other nodes (aspgedge_aceand thelolorextension are). The default istrue, and an explicitNULLis taken astrue.
spock.reserved_object_remove
Use spock.reserved_object_remove to remove one of your own reserved objects.
Built-in objects are protected and cannot be removed.
spock.reserved_object_remove(p_name name, p_kind text)
Parameters:
p_nameis the schema or extension name.p_kindis'schema'or'extension'.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.11.5 - Subscription Management Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Each node in a multi-master scenario contains one or more subscriptions that identify the publisher node; the subscriber acts as the replication target for the publisher.
| Command | Description |
|---|---|
| spock.sub_create | Create a subscription. |
| spock.sub_drop | Drop a subscription. |
| spock.sub_disable | Disable a subscription and disconnect it from the provider. |
| spock.sub_enable | Enables a disabled subscription. |
| spock.sub_alter_interface | Switch the subscription to use a different interface to connect to the provider node. |
| spock.sub_alter_sync | Synchronize all unsynchronized tables in a single operation. |
| spock.sub_alter_options | Change one or more subscription options in a single atomic operation. |
| spock.sub_resync_table | Resynchronize a single table. |
| spock.sub_wait_for_sync | Wait for a subscription to finish synchronization after a spock.sub_create or spock.sub_alter_sync. |
| spock.table_wait_for_sync | Wait only for the subscription’s initial sync and a named table. |
| spock.sub_show_status | Shows status and basic information about subscription. |
| spock.sub_show_table | Shows synchronization status of a table. |
| spock.sub_add_repset | Adds a replication set to a subscriber. |
| spock.sub_remove_repset | Removes a replication set from a subscriber. |
Creating a Subscription
To create a subscription from the current node to a publisher node with Spock,
connect to the server with psql and invoke the spock.sub_create command:
Parameters include:
subscription_nameis the unique name of the subscription.provider_dsnis the connection string to a provider.replication_setsis an array of replication sets that you wish to subscribe to. The sets must already exist; the default is{default,default_insert_only,ddl_sql}.synchronize_structureis a boolean value that specifies if Spock should synchronize the structure from provider to the subscriber; the default isfalse.synchronize_dataspecifies if Spock should synchronize data from provider to the subscriber; the default isfalse.forward_originsis an array of origin names to forward. See Origin Forwarding below for supported values and the restriction on combining this with other enabled subscriptions.apply_delayspecifies how long to delay replication; the default is0seconds.- set
force_text_transfertotrueto force the provider to replicate all columns using a text representation (which is slower, but may be used to change the type of a replicated column on the subscriber); the default isfalse. enabledcontrols whether the subscription is started immediately after creation. The default istrue.skip_schemais an array of schema names whose changes should be ignored by the apply worker. The default is{}(an empty array, meaning no schemas are skipped).
For example, the following command:
Creates a subscription named accts that connects to the accounting
database on 178.12.15.12, authenticating with the credentials of a user
named carol. The payables replication set is subscribed to the new
subscription.
Dropping a Subscription
To drop a subscription with Spock, connect to the server with psql and invoke
the spock.sub_drop command:
Parameters include:
subscription_nameis the name of the existing subscription.- if
ifexistsistrue, an error is not thrown if the specified subscription does not exist; the default isfalse.
For example, the following command:
Drops a subscription named accts; if the subscription does not exist, an
error message will be suppressed by the true trailing parameter (ifexists = true).
Origin Forwarding
forward_origins controls whether a subscription’s apply worker also
processes transactions that did not originate on the immediate provider, but
were relayed through it from a peer further upstream (a cascade or multi-hop
topology). {} (the default) forwards only the provider’s own
locally-originated changes — the setting used for ordinary bidirectional
replication between two nodes, since forwarding a peer’s changes back to
itself would loop. {all} forwards every change regardless of origin.
A forwarding worker advances the replication origin of the local subscription matching the peer it’s relaying (for example, a subscription to that peer created disabled ahead of time, so it can later start from the right position instead of a full resync). At most one local subscription may match a given peer; if more than one does, replication fails with an ambiguous-match error. If the matching subscription is also enabled, its own apply worker owns the same origin, and the two would conflict. Spock avoids this by requiring that a subscription with forwarding active be the only enabled subscription on the node:
- Enabling forwarding (
{all}) on a subscription — viaspock.sub_createwithenabled := true,spock.sub_enable, orspock.sub_alter_optionson an already-enabled subscription — fails if another subscription is already enabled on this node. - Enabling a subscription (
spock.sub_createwithenabled := true, orspock.sub_enable) fails if another subscription on this node already has forwarding active. - Changing
forward_originson a subscription that stays disabled is always allowed; the restriction is only checked once the subscription is actually enabled.
Subscription Management Functions
You can use the following settings to control and manage your subscriptions.
spock.sub_create
Use spock.sub_create to create a subscription from current node to the
provider node.
spock.sub_create(subscription_name name, provider_dsn text, replication_sets text[], synchronize_structure boolean, synchronize_data boolean, forward_origins text[], apply_delay interval, force_text_transfer boolean, enabled boolean, skip_schema text[])
The command does not wait for completion before returning to the caller.
Parameters:
subscription_nameis the unique name of the subscription.provider_dsnis the connection string to a provider.replication_setsis an array of existing replication sets to which you are subscribing. The default is{default,default_insert_only,ddl_sql}.synchronize_structuretells Spock if it should synchronize the structure from the provider to the subscriber; the default isfalse.synchronize_datatells Spock to synchronize data from provider to the subscriber; the default isfalse.forward_originsis an array of origin names to forward. See Origin Forwarding above for supported values and the restriction on combining this with other enabled subscriptions.apply_delayis the number of seconds to delay replication; the default is0seconds.force_text_transferforces the provider to replicate all columns using a text representation (which is slower, but may be used to change the type of a replicated column on the subscriber) when set totrue. The default isfalse.enabledcontrols whether the subscription is started immediately after creation. The default istrue.skip_schemais an array of schema names whose changes should be ignored by the apply worker. The default is{}.
The subscription_name is used as application_name by the replication
connection. This means that it’s visible in the pg_stat_replication
monitoring view. It can also be used in synchronous_standby_names when
Spock is used as part of a synchronous replication setup.
Use spock.sub_wait_for_sync(subscription_name) to wait for the
subscription to asynchronously start replicating and complete any needed
schema and/or data sync.
spock.sub_drop
Use spock.sub_drop to disconnect the subscription and remove it from the
catalog.
spock.sub_drop(subscription_name name, ifexists bool)
Parameters:
subscription_nameis the name of an existing subscription.ifexiststells the Spock extension how to handle the error if the subscription does not exist. Iftrue, an error is not thrown if the subscription does not exist; the default isfalse.
spock.sub_disable
Use spock.sub_disable to disable a subscription and disconnect it from the
provider.
spock.sub_disable(subscription_name name, immediate bool)
Parameters:
subscription_nameis the name of an existing subscription.immediatetells Spock when to stop the subscription. If set totrue, the subscription is stopped immediately; if set tofalse(the default), it will be only stopped at the end of current transaction.
spock.sub_enable
Use spock.sub_enable to enable a disabled subscription.
spock.sub_enable(subscription_name name, immediate bool)
Parameters:
subscription_nameis the name of the existing subscription.immediatetells Spock when to start the subscription. If set totrue, the subscription is started immediately; if set tofalse(the default), it will only be started at the end of the current transaction.
This fails if another subscription on this node already has forwarding active; see Origin Forwarding above.
spock.sub_alter_interface
Use spock.sub_alter_interface to modify the subscription to use a different
interface to connect to provider node.
spock.sub_alter_interface(subscription_name name, interface_name name)
Parameters:
subscription_nameis the name of an existing subscription.interface_nameis the name of an existing interface of the current provider node.
spock.sub_alter_sync
Use spock.sub_alter_sync to synchronize all unsynchronized tables in all sets in a
single operation.
spock.sub_alter_sync(subscription_name name, truncate boolean DEFAULT false)
Tables are copied and synchronized one by one. The command does not wait for
completion before returning to the caller. Use spock.sub_wait_for_sync to
wait for completion.
Parameters:
subscription_nameis the name of an existing subscription.truncatetells Spock if it should truncate tables before copying. Iftrue, tables will be truncated before copy; the default isfalse.
spock.sub_resync_table
Use spock.sub_resync_table to resynchronize an existing table.
spock.sub_resync_table(subscription_name name, relation regclass)
The table may not be the target of any foreign key constraints.
After scheduling the resynchronization, the function raises a WARNING if
the cached spock.node row of the provider differs from the provider’s own
row; see spock.sub_resync_table.
This function will truncate the table immediately, and only then begin
synchronising it, so it will be empty while being synced. The command does
not wait for completion before returning to the caller; use
spock.table_wait_for_sync to wait for completion.
Parameters:
subscription_nameis the name of an existing subscription.relationis the name of an existing table, optionally qualified.
spock.sub_wait_for_sync
Use spock.sub_wait_for_sync to wait for a subscription to finish
synchronization after a spock.sub_create or spock.sub_alter_sync.
spock.sub_wait_for_sync(subscription_name name)
This function waits until the subscription’s initial schema/data sync, if any, are done, and until any tables pending individual resynchronisation have also finished synchronising.
Parameters:
subscription_nameis the name of an existing subscription.
For best results, run SELECT spock.wait_slot_confirm_lsn(NULL, NULL) on the
provider after any replication set changes that requested resyncs, and only
then call spock.sub_wait_for_sync on the subscriber.
spock.table_wait_for_sync
Use spock.table_wait_for_sync to wait only for the subscription’s initial
sync and the named table.
spock.table_wait_for_sync(subscription_name name, relation regclass)
Same as spock.sub_wait_for_sync, but waits only for the subscription’s
initial sync and the named table. Other tables pending resynchronisation are
ignored.
spock.wait_slot_confirm_lsn
Use spock.wait_slot_confirm_lsn to wait until all replication slots on the
current node have replayed up to the xlog insert position at time of call on
all providers.
SELECT spock.wait_slot_confirm_lsn(NULL, NULL)
Returns when all slots’ confirmed_flush_lsn passes the
pg_current_wal_insert_lsn() at time of call.
Options include:
- optionally may wait for only one replication slot (first argument).
- optionally may wait for an arbitrary log sequence number (LSN) passed
instead of the insert LSN (second argument); both are usually just left
NULL.
This function is very useful to ensure all subscribers have received changes up to a certain point on the provider.
spock.sub_show_status
Use spock.sub_show_status to show status and basic information about a
subscription.
spock.sub_show_status(subscription_name name DEFAULT NULL)
Parameters:
subscription_nameis the optional name of an existing subscription. If omitted (orNULL), the function will show the status of all subscriptions on the local node.
The function returns one row per subscription with these columns:
subscription_name, status, provider_node, provider_dsn,
slot_name, replication_sets, forward_origins.
spock.sub_show_table
Use spock.sub_show_table to show the synchronization status of a table.
spock.sub_show_table(subscription_name name, relation regclass)
Parameters:
subscription_nameis the name of an existing subscription.relationis the name of an existing table, optionally qualified.
spock.sub_add_repset
Use spock.sub_add_repset to add one replication set into a subscriber.
spock.sub_add_repset(subscription_name name, replication_set name)
Does not synchronize, only activates consumption of events.
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of a replication set to add to the specified subscription.
spock.sub_remove_repset
Use spock.sub_remove_repset to remove one replication set from a subscriber.
spock.sub_remove_repset(subscription_name name, replication_set name)
Parameters:
subscription_nameis the name of the existing subscription.replication_setis the name of replication set to remove.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.12 - Upgrading the Spock Extension
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
If you build the Spock extension from source, you can remove, build, and upgrade the Spock extension like you would any other Postgres extension.
If you’re upgrading a secure production environment, shut down each node sequentially and perform the following steps:
- Disable auto-DDL.
- Stop the Postgres server.
- Build the updated Spock binaries for your Postgres version.
- Restart the Postgres server; this triggers extension schema upgrade checks (Spock’s background worker detects the version mismatch and runs any required schema migrations automatically).
- Use the psql command line to verify the Spock version in use and the node status.
- After upgrading all of the nodes in your cluster, enable Auto-DDL and restart the service on each node.
A detailed description of each step in the upgrade process is provided below.
Disabling Auto-DDL
Before stopping a node, disable DDL replication to prevent schema changes during the upgrade. Connect to each node and run:
Or, set the following parameter in postgresql.conf on each node:
Then, reload the configuration:
This step is essential if old and new versions are incompatible.
Stopping the Postgres Server
Before upgrading the Spock binary, stop the Postmaster on the server that you’re working on:
This step is essential if old and new versions are incompatible.
Building the New Spock Binaries
Before building the extension, you’ll need to obtain updated Spock source code. If you regularly build the Spock extension from source code (available at https://github.com/pgEdge/spock), use git to obtain an updated source set; then:
The installation copies the following files:
spock.so→$(pg_config --pkglibdir)/;spock.control→$(pg_config --sharedir)/extension/;spock--5.0.1.sqlandspock--5.0.0--5.0.1.sql→$(pg_config --sharedir)/extension/.
Next, you should verify that the updated Spock files are installed. You can use the following commands to confirm the version update.
Check the library timestamp:
Check the control file:
Check that an upgraded .sql file exists; for example:
Restarting the Postgres Server
Then, use pg_ctl to restart the Postgres postmaster process:
When the server restarts, Spock’s database manager background worker
automatically detects the version mismatch and upgrades the extension schema
(with spock_manage_extension() in spock.c).
Verifying the Extension Upgrade
After building the extension, you can verify the version of the extension that is in use and the state of your replication cluster. Use the psql command line to invoke the commands that follow.
Connect to the database with psql:
Verify the Spock version that is in use:
Then, verify that the node is replicating. Check that subscriptions are active with the following commands:
Check the replication slots:
Check the node status:
Enabling Auto-DDL and Restarting the Service on Each Node
After upgrading all of the nodes in your cluster, connect to each node with psql and enable DDL replication:
Or you can modify the parameter in the postgresql.conf file:
Reload the configuration:
Then, on each node, restart the service:
Final Verification
After performing the steps listed above on each server in the cluster, use the following command to verify the replication status of each node:
You should confirm that:
- all nodes report consistent versions (the target version).
- replication lag is minimal or zero.
- no errors appear in PostgreSQL or Spock logs.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.13 - Recovery
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
4.4.2.13.1 - Recovering from Catastrophic Node Failure
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Suppose your cluster is running smoothly with five nodes — n1, n2, n3, n4, and n5 — all connected using Spock logical replication. Node n1 sends transactions to the other four nodes. Then something goes wrong: perhaps because of network delay, n2 has not yet received all of the transactions that n3, n4, and n5 have already applied. Before n2 can catch up, n1 crashes. You are left with n2 lagging behind the others, and no way for it to get the missing data from n1. This is a catastrophic node failure scenario.
Depending on how you run your cluster, more than one node may accept writes. Later in this document, we also show a multiple-node failure example where a second node had also originated transactions before failing.
In the following sections, we’ll walk through how to recover a node using Spock for replication with the Active Consistency Engine (ACE). In each scenario, we use a fully synchronized node as our source of truth. ACE repairs the missing data and can preserve the origin ID and commit timestamp for each repaired row so that replication metadata stays correct and your cluster remains consistent and conflict-free.
This document covers two cases:
- single node failure (one node fails and another is lagging)
- multiple node failure (two or more nodes fail and one or more survivors are behind).
The same idea applies in both cases; you identify what is missing on the surviving node(s), then repair the nodes using a node with complete data, preserving the origin ID and timestamp for every repaired row.
Single Node Failure vs. Multiple Node Failure
The following diagrams show the two scenarios and how to recover.
Scenario 1: One Node has Failed, and One Node is Lagging
In our first example, one node (n1) fails, while another node (n2) is lagging behind because it did not receive all of that node’s transactions. The other survivors (n3, n4, n5) have complete data.
flowchart LR
subgraph failed [Failed]
N1[n1 failed]
end
subgraph behind [Behind]
N2[n2 missing rows from n1]
end
subgraph source [Source of truth]
N3[n3 complete]
N4[n4 complete]
N5[n5 complete]
end
N1 -.->|was replicating to| N2
N3 -->|recover from| N2Implementing a Recovery
- Node n1 has failed.
- Node n2 is lagging.
Our source of truth has to be: n3, n4, or n5
Our first step is to clean up. First, we will use Spock commands to drop the subscriptions to n1, and then drop node n1 from the cluster.
Then, on our survivor (n2), and for each table, run:
table-diff --preserve-origin n1 --until <n1_failure_time>
Then, on our survivor (n2), for each table with differences, run the ACE
table-repair command, specifying the --recovery-mode,
--source-of-truth n3, and --preserve-origin options.
These steps ensure that n2 contains all of the rows that originated on n1.
Note: These are high-level steps. Detailed instructions for each step, including exact commands and options, are provided later in this document starting at Phase 1: Assess the Damage. In some cases, tables may still show differences after an initial repair; see the Troubleshooting section for guidance.
Scenario 2: Multiple Nodes have Failed, and One Node is Lagging
In our next example, we’ll assume multiple nodes have failed (for our example, we’ll use n1 and n4). If two (or more) nodes fail, leaving one or more survivors, the damaged survivor (node n2 is lagging, but not down) may be missing rows that originated from either n1 or n4. To recover, pick one fully synchronized survivor as the source of truth (we’ll use n3) and recover n2, adding data from both n1 and n4.
In this example, we’ll assume n4 was also accepting writes before it failed, so some rows in the cluster have an origin ID of n4.
flowchart LR
subgraph failed [Failed]
N1[n1 failed]
N4[n4 failed]
end
subgraph behind [Behind]
N2[n2 missing rows from n1 and n4]
end
subgraph source [Source of truth]
N3[n3 complete]
N5[n5 complete]
end
N1 -.->|was replicating to| N2
N4 -.->|was replicating to| N2
N3 -->|recover n2 for both n1 and n4| N2Implementing a Recovery
- Nodes n1 and n4 have failed.
- Node n2 is lagging.
Our source of truth has to be: n3 or n5
Our first step is to clean up the replication scenario. Drop the subscriptions to n1 and n4 before dropping the nodes from the cluster.
Then, on each surviving node, and for each table, run the table-diff command
against each failed node including the --preserve-origin and failure_time
options:
table-diff --preserve-origin n1 --until <n1_failure_time>
table-diff --preserve-origin n4 --until <n4_failure_time>
Each run will return one diff file per table/origin combination.
Then, on n2, for each table with differences, run table-repair
with --recovery-mode, --source-of-truth n3, and --preserve-origin.
These steps will ensure n2 contains all of the rows that originated on n1 and n4, with the origin ID and timestamp preserved for each.
In the case of a multiple-node failure, you run diff and repair once per failed origin. For each table, that means one diff (and one repair) for n1 and one diff (and one repair) for n4. The source of truth (n3) is the same for all repairs.
Implementing Repairs in Both Cases
flowchart TD
subgraph single [Single node failure]
S1[n1 fails, n2 behind]
S2[Drop n1. Diff vs n1. Repair n2 from n3.]
S1 --> S2
end
subgraph multi [Multiple node failure]
M1[n1 and n4 fail, n2 behind]
M2[Drop n1 and n4. Diff vs n1, then vs n4.]
M3[Repair n2 from n3 for n1 rows. Repair n2 from n3 for n4 rows.]
M1 --> M2 --> M3
endIn both cases you:
- Clean up the failed node(s) in Spock.
- Run table-diff on all tables—once per failed origin in the multiple-node case.
- Run table-repair with
--preserve-originand a single source of truth so that origin ID and commit timestamp are preserved for each repaired row.
What Happens in a Catastrophic Node Failure of a Single Node
When one node fails mid-replication, some of its transactions may have been applied on some subscribers but not others. In our single-failure example:
- n1 has failed and is no longer available.
- n2 received fewer transactions from n1 (for example, due to network delay) and is behind.
- n3, n4, and n5 received all of n1’s transactions and are fully synchronized.
You need to bring n2 back in line with n3, n4, and n5. ACE does this by
comparing tables across the surviving nodes, focusing only on data that
originated from n1 and was committed before the failure. It then repairs n2
using a chosen source of truth (in our example, n3). When you use the
--preserve-origin option, ACE preserves each repaired row’s origin ID
(the node that originally wrote the row) and commit timestamp (to
microsecond precision) so that replication metadata remains correct.
The following diagram shows the state at the moment of failure of our single node, n1:
sequenceDiagram
participant N1 as n1 (failed)
participant N2 as n2 (behind)
participant N3 as n3 (up to date)
participant N4 as n4 (up to date)
participant N5 as n5 (up to date)
Note over N1: Sends transactions to all
rect rgb(230, 240, 255)
N1->>N2: Partial replication (e.g. 3 of 5)
N1->>N3: Full replication (all 5)
N1->>N4: Full replication (all 5)
N1->>N5: Full replication (all 5)
end
N1--xN1: Crash (n1 offline)
Note over N2: Missing rows from n1
Note over N3..N5: Complete - use as source of truthBefore You Begin
Before you start the recovery process, make sure you have the following in place:
- ACE installed and configured on a host that can reach your surviving nodes. ACE is used to compare and repair table data across nodes. For building, installing, and configuring ACE, see the ACE repository and its documentation (including configuration).
- Access to your surviving nodes (n2, n3, n4, and n5). You’ll need to run ACE commands and, for Spock cleanup, connect to each node with a Postgres client.
- The approximate time when the failed node (or nodes) failed. You’ll use this as a cutoff when running ACE so that only data committed before the failure is considered.
- Origin tracking enabled. Your Spock cluster should have
track_commit_timestamp = onin Postgres so that ACE can use commit timestamps and origin ID for recovery and for preserving them when repairing rows.
Recovery is a multi-step process. Take your time, and run the
validation steps so you can confirm that all tables match before
resuming normal operations. To preserve the origin ID and commit
timestamp for repaired rows, include the --preserve-origin flag
with every table-repair command in Phase 4. In some cases, tables
may still show differences after an initial repair (for example, if
writes occurred during the diff or repair). The
Troubleshooting section at the end of this
document covers the most common causes and how to resolve them.
Overview of the Recovery Workflow
Recovery has five main phases; you should approach these phases in order:
Assess the damage – Check replication status and identify which nodes are behind and which are fully synchronized.
Spock cleanup – Drop subscriptions and slots for the failed node and remove the failed node from the cluster.
Identify all missing data – Run ACE table-diff on every replicated table to see which tables have differences and what is missing on n2.
Repair all affected tables – For each table that has differences, run ACE table-repair using n3 (or your chosen node) as the source of truth. Use
--preserve-originso that the origin ID and commit timestamp are preserved for every repaired row.Validate – Re-run table-diff on all repaired tables to confirm that n2 matches the other survivors.
Because n2 might be missing data from more than one table, you must check all of your tables, not just one. The sections below walk you through each phase and show you the commands to run.
Phase 1: Assess the Damage
Connect to your surviving nodes and check replication status. You need to
confirm which nodes are behind and which have all of the data. You can use
spock.sub_show_status()
to see subscription status and any lag.
For example, connect to n2 and run:
The output will list each subscription with its current status and lag. A
subscription that shows a large lag or a status of down or initializing
when it should be replicating indicates that the node is behind. For
example:
In this output, sub_n2_n1 is down — that confirms n2 lost its
connection to n1 (which has failed). The subscriptions to n3, n4, and n5
are still healthy. To gauge how far behind n2 is, query
spock.lag_tracker for replication lag
in bytes and time.
Determine the approximate time when the failed node (or nodes) failed. You’ll need this timestamp for the ACE commands in Phase 3 and 4. If you have logs or monitoring, use that; otherwise use the last known good time before the failure.
Phase 2: Spock Cleanup
Once you’ve confirmed that the failed node (in our case, n1) is gone and won’t be coming back in this recovery, you need to remove it from the cluster so that the remaining nodes no longer expect replication from or to n1.
On each surviving node (n2, n3, n4, n5):
Drop subscriptions that involved the failed node.
If a subscription was receiving from n1 or sending to n1, drop it using
spock.sub_drop(). For example, on n2 you might drop the subscription that connected n2 to n1.Remove the failed node from the cluster.
From one of the surviving nodes, call
spock.node_drop()to remove n1. This removes the node entry from the Spock catalog.
Dropping the node and subscriptions is irreversible; make sure you have identified the failed node correctly and that you do not need to bring n1 back before doing this.
After cleanup, your cluster has four nodes: n2, n3, n4, and n5. The next steps use ACE to fix the data on n2.
If two or more nodes failed (e.g. n1 and n4), you’ll perform these steps for each node.
Phase 3: Identify All of the Missing Data
To recover n2, you need to know which tables have differences and
what is missing. ACE’s
table-diff
command compares table data across nodes. When you run it with
--preserve-origin n1 and --until <timestamp>, it limits the comparison
to rows whose origin ID is n1 and whose commit timestamp is at or before
that time—exactly what you need after n1 has failed.
You must run table-diff for every table that is replicated in your
cluster. If you only run it for one table, you might repair that table but
leave others out of sync.
Step 1: Get a List of All Tables to Check
First, get the list of tables that participate in replication. You can get
this from the spock.tables view, which lists every table along with the
replication set (if any) it belongs to. Connect to any surviving node (for
example, n3) and run:
Alternatively, you can list all tables in the schema you replicate:
Use this list for the next step. In the examples below, we’ll use tables
like customers, orders, and products; replace these with your actual
schema and table names.
Step 2: Run table-diff on Every Table
For each table in your list, run ACE table-diff with the failed node as
the origin and your failure timestamp as the cutoff. Replace
2026-02-11T14:30:00Z with the time when n1 failed, and replace
mycluster with your ACE cluster name.
For a single table (for example, public.customers):
What these options do:
--nodes n2,n3,n4,n5– Compare only the surviving nodes (n2 and the nodes that have full data).--preserve-origin n1– Only consider rows whose origin ID is n1, so you don’t mix in later local writes on the survivors.--until 2026-02-11T14:30:00Z– Only consider rows committed at or before this time (use RFC3339 format).--output json– Writes a diff report to a JSON file that you’ll use for repair.
ACE returns a diff file with a name that contains the schema and table name;
for example, public_customers_diffs-20260211143000.json. Repeat the diff
command for every other table; for example:
Step 3: Review the Diff Reports
After running table-diff on all tables, check the output. ACE will report whether each table has differences. For tables that do have differences, note the name of the diff file (it will include the table name and a timestamp). You’ll use those files when you perform the repair steps. Tables that have no differences don’t need repair.
If you have a multiple node failure (e.g. n1 and n4 both failed), run table-diff once per failed origin per table. For example, if your survivors are n2, n3, n5. For each table you run two diffs (one from each node) and get two diff files:
Review the diff reports; then in Phase 4, run table-repair for each of these diff files using same source of truth (e.g. n3).
If you have multiple tables, you can script the diff step. The following example loops through a list of table names (customize the list to match your schema):
Phase 4: Repair All Affected Tables
For each table that had differences in Phase 3, run ACE table-repair
using the diff file that was produced. You must run repair in recovery
mode and include --preserve-origin so that repaired rows keep their
original origin ID and commit timestamp. Without
--preserve-origin, repaired rows would get n2’s origin ID and a new
commit time, which can cause replication conflicts and incorrect ordering.
With --preserve-origin, ACE writes each repaired row with the same origin
ID and commit timestamp it had on the source of truth, so n2’s replication
metadata stays correct.
Choose one node as the source of truth for repair. In our scenario, n3 (and
n4 and n5) have the complete data, so we chose n3. You can let ACE
auto-select the source of truth based on which survivor has the highest
origin LSN for n1, or you can set it explicitly with --source-of-truth n3.
Repair Command for Each Table
For each table that had differences, run the following command, replacing
the diff filename and table name with the ones from your table-diff run:
--diff-file– The JSON file produced by table-diff for this table.--nodes n2,n3,n4,n5– The surviving nodes (n2 will be repaired; n3 is the source of truth).--recovery-mode– Required when the diff was created with--preserve-origin; tells ACE this is a catastrophic-failure recovery.--source-of-truth n3– Use n3’s copy of the data to repair n2. You can omit this and let ACE choose the survivor with the highest LSN for n1, but if there are ties or missing LSNs, you must specify the source.--preserve-origin– Preserves the origin ID and commit timestamp for each repaired row (to microsecond precision). Repaired rows on n2 will show the same origin ID and commit time as on the source of truth, so replication metadata stays correct.
Repeat for every table that had differences, for example:
Multiple node failure (e.g. n1 and n4 both failed): You have one diff
file per (table, failed origin). Run table-repair for each of those
diff files, using the same source of truth (n3) and --preserve-origin
every time. ACE writes a new filename for each table-diff run; use the file
from your n1 diff run for the first repair and the file from your n4 diff
run for the second. Example for one table:
In both commands the source of truth is n3; origin ID and commit timestamp are preserved for every repaired row.
Always use --preserve-origin when repairing after a catastrophic node
failure. This option ensures that the origin ID and commit
timestamp are preserved for every repaired row. If you omit it,
repaired rows will have n2’s origin ID and a new timestamp, which can
cause replication conflicts and incorrect conflict resolution.
For more details on recovery mode and how origin ID and timestamp preservation works, see the ACE repository and the ACE docs: Using ACE for CNF recovery and the table-repair command reference.
Phase 5: Validate That All Tables Match
After repairing every affected table, verify that n2 now matches n3, n4,
and n5. Re-run table-diff for each repaired table without
--preserve-origin and --until. That compares the full table content
across the survivors:
If ACE reports that the tables match, n2 has been successfully recovered.
At this point you can resume normal operations: re-enable or recreate any
subscriptions that were dropped during cleanup (for example, subscriptions
from n2 to n3, n4, and n5 so that n2 receives new writes), and allow
application traffic to flow again. If writes were occurring on other nodes
during the repair, a final table-diff run (without --preserve-origin or
--until) will confirm that n2 has caught up completely.
If any table still shows differences, review the diff report and consider re-running repair for that table or checking for ongoing writes during the diff. See the Troubleshooting section for common causes and remedies.
flowchart LR
subgraph before [Before Recovery]
N2_before[n2 missing data]
N3_before[n3 complete]
N4_before[n4 complete]
N5_before[n5 complete]
end
subgraph after [After Recovery]
N2_after[n2 repaired]
N3_after[n3 complete]
N4_after[n4 complete]
N5_after[n5 complete]
end
before --> afterWhy Preserve Origin ID and Timestamp?
The repairs that ACE writes to n2 originated on n1. Each row has an origin ID (that identifies which node wrote it) and a commit timestamp (that identifies when it was committed). Spock uses these for conflict resolution and to keep replication consistent.
If you repair without --preserve-origin, the repaired rows get n2’s
origin ID and a new commit timestamp. That can cause:
- Replication conflicts – If n1 ever comes back or you add another node with n1’s history, the cluster may see the same row with different origin IDs and timestamps and report conflicts.
- Incorrect ordering – Spock uses commit timestamps and origin ID for conflict resolution (for example, last-write-wins). Wrong timestamps or origin IDs can lead to wrong outcomes.
- Lost data lineage – You lose an accurate record of which node produced which data.
If you repair with --preserve-origin, ACE keeps the original origin
ID and commit timestamp (to microsecond precision) for each repaired row.
The repaired rows on n2 then match the replication metadata they had on the
source of truth, so conflict resolution and data lineage stay correct.
For catastrophic node failure recovery, always use --preserve-origin when
you run table-repair.
Important Considerations when using ACE
Review the following considerations before performing a recovery with ACE.
Multi-Table Recovery
When performing a recovery between nodes with multiple tables:
- Check every table – Run table-diff on all replicated tables, not just one. Only then will you see the full picture of what is missing on n2.
- Prioritize if needed – If you have many tables, you can repair critical tables first, then the rest. Just ensure you eventually run diff and repair for every affected table.
- Same cutoff for all – Use the same
--untiltimestamp for every table so that you’re consistently fencing at the same failure time. - Same source of truth – Using one node (e.g., n3) as source of truth for all tables keeps the process simple. If you have a reason to use different sources per table, you can, but document it so you don’t get confused later.
Large Tables
For very large tables, ACE supports options such as --table-filter to
restrict the comparison to a subset of rows. This allows you to run diff
and repair in chunks. See the
ACE table-diff command documentation
for details.
When to Specify –source-of-truth
If you omit --source-of-truth, ACE will try to pick the survivor with the
highest origin LSN for n1. If LSN information is missing on the survivors
or there’s a tie, ACE will ask you to specify the source. In that case,
choose any node that you know has the most complete data set (in our
example, n3, n4, or n5).
Catastrophic Failure vs. Network Partition
A catastrophic node failure means the node is gone (crashed, unrecoverable). A network partition might mean the node is still running but temporarily unreachable. If you’re only dealing with a partition, you might prefer to wait for connectivity to return or to fail over in a planned way rather than dropping the node and doing ACE recovery. Use this procedure when you’ve decided that the node is permanently lost for this cluster.
Troubleshooting
ACE says LSN Information is Missing
Specify --source-of-truth explicitly (e.g. --source-of-truth n3) so
ACE doesn’t need to probe LSNs.
More than One node is behind
Run diff and repair commands for all potentially lagging nodes in
--nodes. The source of truth should be a node that has full data; repair
will fix the others.
Auto source-of-truth selection fails or ties
Provide --source-of-truth <node_name> with the name of a node you know has
the complete data.
Origin metadata missing for some rows
ACE may log a warning and repair those rows without preserving origin ID and
timestamp. Ensure track_commit_timestamp = on and that the diff was run
with --preserve-origin; check the diff file and ACE logs.
Tables still differ after repair
Re-run table-diff without --preserve-origin to see the current state. If
writes occurred during repair, run diff again and repair if needed. For large
tables, consider performing a chunked repair with --table-filter.
Source node fails mid-replay
If the node you chose as your source of truth (e.g., n3) fails or becomes unavailable while ACE is still running repairs, stop the repair immediately and switch to a different fully-synchronized survivor before continuing.
- Confirm which remaining nodes still have complete data (re-run
spock.sub_show_status()on each one and check for lag). - Pick a new source of truth (e.g., n4 or n5) and re-run
table-repairwith--source-of-truth n4for any tables that were not yet fully repaired.
If your cluster has only three nodes and the source-of-truth node also fails mid-replay, you may have no fully-synchronized survivor left. In that situation you cannot guarantee a complete, conflict-free repair and some data loss is possible. Minimize this risk by keeping at least one additional warm standby or by pausing application writes before starting the recovery.
Recovery fails entirely (non-Spock failure)
If the recovery cannot be completed — for example, because the lagging node itself has suffered hardware or OS failure during the repair process — you may need to rebuild it from scratch rather than repair it in place. In that case, remove the damaged node from the cluster and add a fresh replacement using the ZODAN node-management procedures:
- Remove the damaged node – Use
spock.node_drop()(and drop related subscriptions) on the surviving nodes to clean up the cluster registry. - Add a replacement node – Use ZODAN’s
add_nodeprocedure to bring a new node into the cluster. ZODAN handles slot creation, initial sync, and subscription wiring automatically. See the ZODAN documentation and the ZODAN tutorial for step-by-step instructions.
Post-Recovery Validation Checklist
After completing all repair steps, work through the following checklist before returning the cluster to normal production traffic.
Replication Status
- Run
SELECT * FROM spock.sub_show_status();on every node and confirm all subscriptions showreplicatingwith zero (or near-zero) lag. - Confirm that subscriptions dropped during Phase 2 cleanup have been re-created and are active.
- Verify that the recovered node (n2) appears in
SELECT * FROM spock.node;on all surviving nodes and that its DSN is correct.
Replication Slot Cleanup
- Run
SELECT slot_name, active, restart_lsn FROM pg_replication_slots;on each node and confirm there are no stale or inactive slots left over from the failed node or from the recovery process. - If any orphaned slots remain (for example, a slot for n1 that was
never dropped), remove them with
SELECT pg_drop_replication_slot('<slot_name>');on the node that owns the slot.
Data Integrity Check
Re-run
table-diffon all repaired tables without--preserve-originor--untilto confirm the full table content matches across all nodes:Confirm ACE reports no differences for every table.
Spot-check row counts on the recovered node against a known-good survivor for critical tables:
If
track_commit_timestamp = on, verify that origin IDs and commit timestamps on repaired rows match the source of truth (usepg_xact_commit_timestamp()andspock.xact_commit_timestamp_origin()).
Final Sign-off
- Monitor replication lag for at least 15–30 minutes after re-enabling application traffic to confirm the recovered node is keeping up.
- Review PostgreSQL logs on the recovered node for any replication errors or warnings.
- Document the recovery: nodes affected, failure time used for
--until, source of truth used, and any tables that required re-repair.
Summary
In summary, the basic steps required to recover a lagging or damaged node vary only based on how many nodes you need to repair or rebuild:
In the event of a single node failure:
Assess the damage – Identify which nodes are behind and determine when the failure occurred.
Clean up Spock – Drop subscriptions to the failed node and remove it from the cluster.
Identify missing data – Run ACE table-diff on all replicated tables with
--preserve-origin node_nameand--until <failure_time>.Repair affected tables – Run ACE table-repair with the following command options:
--recovery-mode--source-of-truth n3--preserve-origin(critical for maintaining replication metadata)
Validate the recovery – Re-run table-diff to confirm all tables match across surviving nodes.
The process is similar for a multi-node failure with these key differences:
Assess the damage – Identify which nodes are behind and when each failure occurred.
Clean up Spock – Drop subscriptions to all failed nodes and remove all of the failed nodes from the cluster.
Identify missing data – Run table-diff once for each failed origin, for each table:
--preserve-origin n1with n1’s failure time--preserve-origin n4with n4’s failure time
Repair affected tables – Run table-repair for each diff file produced:
- Use the same
--source-of-truth(e.g., n3) for all repairs - Always include
--preserve-origin
- Use the same
Validate recovery – Re-run table-diff to confirm all tables match
Critical Reminder
In both scenarios, always use --preserve-origin to ensure that origin ID
and commit timestamp are preserved for every repaired row. Check all
replicated tables to ensure the lagging node is fully recovered.
See also
- ACE (Active Consistency Engine) on GitHub — build, install, and configure ACE; command reference and architecture docs are in the repository.
- ACE documentation —
configuration, CNF recovery, and command reference (e.g.
table-diff,table-repair).
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.14 - Logical Slot Failover
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock creates logical replication slots on each provider node. For high availability with a physical standby, these slots must be synchronized to the standby so that replication can resume without data loss after a failover.
How It Works
When a primary server fails and a physical standby is promoted, any active logical subscribers must be able to continue replicating from the new primary. This requires the logical replication slots, which track each subscriber’s replication position, to be present and up to date on the standby before the failover occurs.
Without slot synchronization, a failover would require manual slot recreation and a full re-sync of all subscriber tables.
PostgreSQL Version Behaviour
| PostgreSQL | Slot sync mechanism | Spock worker |
|---|---|---|
| 15, 16 | Spock built-in spock_failover_slots worker | Registered on every node; synchronizes only while in recovery |
| 17 | Spock worker or native sync_replication_slots | Yields to native if enabled |
| 18+ | Native sync_replication_slots (required) | Not registered |
The mechanism changes with the version, but the requirement does not: a slot
sync worker is running on every node of the cluster, primary and standby
alike. It is started before the server knows which role it will hold, so on a
primary it stays resident and idle, waking only to check whether the server
has entered recovery. Spock’s own worker is registered from
shared_preload_libraries and occupies one max_worker_processes slot;
PostgreSQL’s native worker is a dedicated postmaster process outside that
pool. Budget a worker for it on every node either way - see
Sizing Postgres Resources for Spock.
On PostgreSQL 17+, Spock marks every logical slot with the FAILOVER flag
at creation time. This enables PostgreSQL’s built-in slotsync worker to pick
them up automatically.
On PostgreSQL 18+, Spock’s own failover worker is not registered at all.
The native slotsync worker is the only mechanism that copies the slots.
Spock’s walsender hold-back (spock.pg_standby_slot_names with
spock.standby_slots_min_confirmed) stays available on every version, since
synchronized_standby_slots can only wait for all of its slots.
Which settings you need
There are two sync paths, and each needs a different set of settings. Both paths also assume the base Spock settings are already in place.
Base settings (all versions, every node)
These are the settings Spock needs to replicate at all. They are covered in Installing and Configuring Spock.
Size these for your cluster rather than copying the numbers - see
Sizing Postgres Resources for Spock. Slots, walsenders, and
origins scale with the number of other nodes multiplied by the number of
replicated databases in the instance, and max_replication_slots and
max_wal_senders should be set to the same value. Note that a physical
standby adds a slot to that value on the primary, and that a slot sync worker
occupies one max_worker_processes slot on every node.
On PostgreSQL 18, also size max_active_replication_origins (default 10) to at
least the number of subscriptions this node applies - (nodes - 1) x replicated databases in a full mesh - plus some headroom. Setting it equal to
max_replication_slots is the simplest safe choice.
Native path (PostgreSQL 17 with sync_replication_slots = on, and PostgreSQL 18)
Core PostgreSQL copies the slots. Set these in addition to the base settings.
| Setting | Node | Value | Purpose |
|---|---|---|---|
sync_replication_slots | standby | on | Turns on the core slot sync worker. Required on 18, optional on 17. |
hot_standby_feedback | standby | on | Stops the primary from removing catalog rows the slots still need. |
primary_slot_name | standby | physical slot name | The physical slot the standby streams through. |
primary_conninfo | standby | connection string with dbname | How the standby reaches the primary. |
synchronized_standby_slots | primary | physical slot name | Holds logical walsenders back until every listed standby has the changes. With more than one standby, use the two Spock settings below instead when “any N of them” is wanted; use only one of the two mechanisms. |
spock.pg_standby_slot_names | primary | '' | Physical slots that must confirm an LSN before logical replication advances. Optional. |
spock.standby_slots_min_confirmed | primary | -1 | How many of those slots must confirm. -1 means all; 1 keeps replicating while one standby of several is down. |
slot failover = true | primary | per slot | Only slots with this flag are synced. Spock 6.0.0 sets it at creation; older slots are handled during upgrade. |
With spock.standby_slots_min_confirmed lower than the number of listed
slots, subscribers can receive changes that some standbys do not have yet.
After a failure, promote the standby with the highest
pg_last_wal_receive_lsn(): it has every change sent to a subscriber.
Promoting a standby that is further behind leaves subscribers with rows the
new primary never had.
A standby inherits spock.pg_standby_slot_names from whichever file carries
it, including a postgresql.conf or postgresql.auto.conf that
pg_basebackup copies. After a promotion the new primary has none of the
physical slots it names, so with -1 every logical walsender waits for them
until wal_sender_timeout and warns; create the slots there or clear the
setting, as for synchronized_standby_slots in the runbook below. A
walsender that is waiting does not notice a server shutdown before that
timeout either.
The physical slot must exist on the primary before the standby connects:
Spock worker path (PostgreSQL 15, 16, and 17 when sync_replication_slots is off)
The Spock background worker on the standby copies the slots. Set these in addition to the base settings.
| Setting | Node | Default | Purpose |
|---|---|---|---|
hot_standby_feedback | standby | on (you set it) | Required before the worker will synchronize anything, and stops the primary from removing needed catalog rows. |
primary_slot_name | standby | physical slot name | The physical slot the standby streams through. |
primary_conninfo | standby | connection string | How the standby reaches the primary. |
spock.synchronize_slot_names | standby | name_like:%% | Which slots to sync. All by default. |
spock.drop_extra_slots | standby | on | Drop standby slots that no longer exist on the primary. |
spock.primary_dsn | standby | '' | Connection to the primary. Falls back to primary_conninfo when empty. |
spock.pg_standby_slot_names | primary | '' | Physical slots that must confirm an LSN before logical replication advances. Optional. |
spock.standby_slots_min_confirmed | primary | -1 | How many of those slots must confirm. -1 means all. |
spock.failover_slots_naptime | standby | 1000 | Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000). |
spock.failover_slots_feedback_naptime | standby | 10000 | Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000). |
spock.failover_slots_recreate_invalidated | standby | on | Drop and recreate a synchronized slot whose copy was invalidated on the standby. off leaves it as it is and reports it once. PG15-17 only; ignored on PG17 with native slot sync and on PG18+ (SIGHUP). |
spock.failover_slots_database | standby | '' | Database the worker connects to so it can decode each copy on the standby and give it a consistent snapshot. Off by default; without it, transactions can be lost after a promotion. PG16-17 only, ignored on PG18+; on PG16 it must be the slots’ database (restart). |
hot_standby_feedback = on plus a physical slot named by primary_slot_name is
the important pair. Without both, the primary can remove catalog rows a slot
still needs, and the slot is invalidated with a message about conflicting with
recovery.
Setup: PostgreSQL 17 and 18 (Native)
This is the native slot sync path. It is the only option on PostgreSQL 18. On
PostgreSQL 17 it is optional: the Spock worker runs by default, and setting
sync_replication_slots = on on the standby tells Spock to step aside and let
core PostgreSQL do the sync instead. Native sync only copies slots that have
failover = true. Spock 6.0.0 sets that flag when it creates a slot. If you
have slots from an older Spock release, see the upgrade section below. To
switch a PostgreSQL 17 standby the Spock worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker
instead: setting sync_replication_slots = on alone leaves most or all
slots unsynchronized.
1. Create a physical replication slot on the primary
2. Configure the primary (postgresql.conf)
3. Configure the standby (postgresql.conf)
4. Verify slot synchronization
On the standby, confirm that Spock’s logical slots are synchronized:
All Spock slots should show synced = true and failover = true.
5. After failover
After promoting the standby, subscribers only need to update their connection string to point to the new primary. Replication resumes from the last synchronized LSN with no data loss and no slot recreation required.
Important: if the promoted node has synchronized_standby_slots or
spock.pg_standby_slot_names set, you must adjust it before replication will
resume: both name physical slots the new primary does not have. See
Runbook: clear synchronized_standby_slots after promotion
below.
Switching a PostgreSQL 17 standby from the Spock worker
Copies that the Spock worker made on the standby have synced = false.
Native slot sync will not take over a slot of the same name, and keeps
failing until those copies are gone. To switch:
On the primary, list the slots the standby should carry. The Spock worker copies every logical slot that
spock.synchronize_slot_namesmatches (all of them by default), but native slot sync copies only slots withfailover = true:spock.slot_enable_failover()sets the flag on Spock’s own slots (see Upgrading Spock to 6.0.0). Set it on any other slot you want kept, for example withALTER SUBSCRIPTION ... SET (failover = true)on a PostgreSQL subscriber, with the subscription disabled while you run it. A slot without it is not synchronized after the switch. Leave the primary’s standby holdback (spock.pg_standby_slot_namesorsynchronized_standby_slots) as it is; if neither is set, see step 2 of the native setup.On the standby, check
wal_level = logicaland thatprimary_conninfoincludesdbname. Native slot sync opens a normal database connection withprimary_conninfo, not a replication one, so its user needs apg_hba.confentry andCONNECTon that database on the primary; the Spock worker may have connected as someone else throughspock.primary_dsn. Then setsync_replication_slots = onand reload. The Spock worker stops synchronizing.Wait one
spock.failover_slots_naptime, then list the copies the Spock worker made on the standby. A pass that was already running can outlast the wait and make a copy after the drop; step 4 finds it.A copy has the same name as a slot on the primary. A slot that exists only on the standby, such as one created there for decoding on the standby, is not a copy: leave it. A copy that shows
active = trueis in use, and the drop fails until the process inactive_pidstops using it; stop that client, or end it withpg_terminate_backend(active_pid). Drop each copy by name:Run the query from Verify slot synchronization until every slot with
failover = trueon the primary appears on the standby withsynced = trueand noinvalidation_reason. If a drop in step 3 failed, or a copy still showssynced = false, drop it again. If no slot appears, check the standby’s log for slot sync connection errors. Native slot sync keeps a new copy temporary, and out of this query, until the slot’s consumer on the primary has moved past the position the standby reserved for it; meanwhile the standby logs “could not synchronize replication slot”. A slot whose subscriber is idle, paused or down can stay that way until the subscriber catches up.
Until native slot sync has recreated a slot, the standby has no usable copy of it, so do not promote the standby in between.
Runbook: clear synchronized_standby_slots after promotion
When synchronized_standby_slots is configured (Setup step 2 above), the
provider’s walsenders hold back logical decoding until every physical slot
named in that list has confirmed flush of the relevant LSN. This is what
keeps a physical standby from falling behind a logical subscriber, but it
has a sharp edge on failover.
The setting is meant for the primary, but the standby often has it too:
- it was already in the primary’s
postgresql.auto.confwhen the standby was built withpg_basebackup, which copies that file, - the same
postgresql.confis deployed to every node, or - a cluster manager such as Patroni applies one configuration to every member (see Running Under Patroni).
If the standby has it, then once it is promoted the setting still lists the
physical slot(s) that fed replication to that node before promotion. Those
slots are now orphaned: nothing is consuming them any more, so they never
confirm, and the promoted node’s walsenders sit blocked waiting on them
indefinitely. The practical symptom is that logical replication to
subscribers freezes immediately after a promotion that otherwise looked
successful. Check on the promoted node with SHOW synchronized_standby_slots;.
When it is set, clearing it is a mandatory post-promotion step, not optional cleanup:
The physical slot itself lives on the server that created it. In the setup
above that is the old primary, so drop spock_standby_slot there once that
node is rebuilt or retired:
Under Patroni the member slots are Patroni’s: it removes a departed member’s
slot after member_slots_ttl, so do not drop them by hand.
If the new topology has its own physical standby(s), set
synchronized_standby_slots to the physical slot(s) for that standby
instead of clearing it to ''. The point is to remove references to
orphaned slots, not to leave the setting pointing at slots nothing will ever
consume.
Add this step to your failover runbook alongside the subscriber DSN update described above; skipping it is the most common cause of “failover succeeded but replication stopped” reports when native failover slots are in use.
Running Under Patroni (PostgreSQL 17+)
Patroni manages replication slots itself, and the way it does so decides which of Spock’s two mechanisms can work under it.
- Member slots. With
postgresql.use_slots: true(the default) Patroni creates one physical slot per replica on that replica’s upstream, named after the member (see naming below), and drops it once the member has been gone formember_slots_ttl(default30min). On a switchover the new leader creates fresh slots for the others. - Permanent slots. Slots listed under
slots:in the dynamic configuration survive switchover. Permanent logical slots are copied from the leader to each replica by stopping and restarting the replica, then advanced everyloop_waitseconds. That is Patroni’s own answer to logical slot failover, written before PostgreSQL had one. - Unknown slots. On a replica, Patroni drops logical slots it does not
manage. Since Patroni 4.1.0 it leaves slots created with
failover = truealone, with one exception on PostgreSQL 17 and later: on a replica it removes failover slots whosesyncedis false, which is what a former leader’s own slots look like after a switchover, so that PostgreSQL’s slotsync worker can recreate them as synchronized copies of the new leader’s. Patroni 4.1.4 fixed a crash in that path.
Spock’s built-in spock_failover_slots worker is unreliable under Patroni.
It copies logical slots to the standby by hand and relies on the standby’s
physical slot, through hot_standby_feedback, to pin catalog_xmin on the
primary. Patroni drops and recreates that physical slot as the topology
changes, which lets vacuum on a busy primary remove catalog rows a copied
slot still needs; the slot is then invalidated (invalidation_reason = rows_removed) and the subscriber has to resynchronize from scratch.
The path that works is PostgreSQL’s own: Spock creates its logical slots
with the FAILOVER flag, so with sync_replication_slots = on the slotsync
worker keeps them current on every member, and Patroni, from 4.1.0 on,
stays out of their way. On PostgreSQL 18 this is the only path, because
Spock’s worker is not registered there. On PostgreSQL 17 Spock’s worker
runs unless sync_replication_slots = on is set, so under Patroni set it;
for a member the Spock worker has already been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker.
The mechanism is the one described under
Setup: PostgreSQL 17 and 18 (Native);
this section is about where those settings go in a Patroni configuration
and what a switchover does to them.
Requirements: Patroni 4.1.4 or later, on PostgreSQL 17 or later. On an
older Patroni release, protect the slots with an ignore_slots entry in the
dynamic configuration, so that Patroni neither drops nor copies them:
Required settings
| Setting | Value | Where | Restart? | Why |
|---|---|---|---|---|
sync_replication_slots | on | dynamic config | No (reload) | PostgreSQL’s slotsync worker copies flagged slots to every replica |
hot_standby_feedback | on | dynamic config | No (reload) | Required by slot synchronization; pins catalog_xmin so vacuum cannot remove rows a slot needs. Patroni turns it on by itself only when permanent logical slots are configured, so set it |
wal_level | logical | dynamic config | Yes | Required for logical decoding and for slot synchronization |
output_plugin_libraries | include spock_output | dynamic config, every member | No (reload) | Only on servers that have the parameter (see below). A synchronized slot keeps spock_output as its plugin, so a member missing this setting cannot serve replication once promoted |
postgresql.use_slots | true | Patroni config | n/a | The default. Patroni creates the member slot each replica streams through and sets primary_slot_name to it, which slot synchronization requires |
max_replication_slots / max_wal_senders | sized to cluster | dynamic config | Yes | Member slots plus Spock’s logical slots on every node; see Sizing |
synchronized_standby_slots | standby member slot name(s) | dynamic config or callback | No (reload) | Optional but recommended; holds the leader’s walsenders back until the standby has the WAL. See the sharp edge |
Two requirements of slot synchronization need no action under Patroni: the
primary_conninfo Patroni writes for a replica always carries dbname, and
primary_slot_name is the member slot.
“Dynamic config” means Patroni’s DCS-backed configuration:
bootstrap.dcs.postgresql.parameters when you first bootstrap the cluster,
and patronictl edit-config for a running one. The next subsection shows the
full bootstrap block.
Where the settings go (bootstrap)
Cluster-wide PostgreSQL parameters belong in Patroni’s dynamic configuration
(bootstrap.dcs.postgresql.parameters at bootstrap, patronictl edit-config
afterwards) so every member, current and future leader, agrees on them.
Set them there, not in a per-node postgresql.conf.
output_plugin_libraries arrived with PostgreSQL’s 2026 security fix
(CVE-2026-6471, back-patched to every supported major): a library may not be
used as an output plugin unless it is listed there, and the default excludes
spock_output. A synchronized slot keeps spock_output as its plugin, so a
member without this setting looks healthy while it is a replica and then fails
to serve replication the moment it is promoted — the failure surfaces during a
switchover, which is the worst time to find it. It is PGC_SUSET, so Patroni
reloads it without a restart.
Do not set it on a release that predates the fix: an unrecognised parameter
stops the server from starting, and pushing one through the DCS stops every
member. Check first, on each member, with
SELECT current_setting('output_plugin_libraries', true) — a NULL result means
the parameter does not exist.
Do not declare the Spock logical slots as Patroni permanent logical
slots (the slots: block). That is the hand copying the native path
replaces: Patroni would restart replicas to copy the slots and advance them
itself, in competition with the slotsync worker. Leave the slots: block to
physical slots you need preserved, and the logical slots to PostgreSQL.
Slot names
Patroni derives a member’s slot name from the member name: lowercased, with
- and . turned into _, any other character outside [a-z0-9_] spelled
as u followed by its four-digit code point, and cut at 63 characters. A
member pg-node.1 streams through slot pg_node_1. Whatever names the slots
in synchronized_standby_slots has to follow the same rule, which is why the
sample callback below asks Patroni for the name rather than computing it.
The switchover sharp edge: synchronized_standby_slots
synchronized_standby_slots names the physical slot(s) the leader’s
walsenders must wait for, so that no logical subscriber gets ahead of the
standby that may be promoted. Under Patroni those are the member slots, so
on a two-member cluster with leader n2 and replica r1 the leader needs:
The edge is that this value is role-specific while Patroni’s dynamic
configuration is cluster-wide. Hardcode 'r1' and switch over so that r1
becomes leader, and the new leader waits for a slot named after itself, which
does not exist on it: its walsenders block and logical replication freezes.
This is the failure the
post-promotion runbook
describes, and under Patroni it recurs on every switchover unless handled.
The same wait applies to any listed member that is down. Its slot stays on
the leader, inactive, until member_slots_ttl expires and Patroni drops it,
and a slot that is inactive or missing blocks alike. A standby that stops
therefore stops logical replication until it is back or removed from the
list.
Three ways to handle it:
Automate it with a callback and a periodic reconcile. Patroni runs the
on_role_changecallback on promotion and demotion with the argumentson_role_change <role> <scope>; the role isprimaryorreplica(masteron releases before 4.0). On becoming leader the script setssynchronized_standby_slotsto the slots of the other members that are up and reloads; on becoming a replica it clears it.That callback alone is not enough, because Patroni does not run it when a standby that was down comes back, nor when one goes away. A standby that rejoins after a promotion would stay off the list, and subscribers could advance ahead of it. So the same script is also run periodically on every member, from cron or a systemd timer, as
set_synchronized_standby_slots.sh reconcile <scope>: it asks Patroni for the member’s current role and brings the setting up to date, touching it only when it differs. A standby is protected from the first reconcile after it streams again; choose the interval accordingly.A reference implementation ships with Spock at
samples/set_synchronized_standby_slots.sh. It reads the member name frompatroni.yml, derives slot names with Patroni’s own function, skips members that are not running or streaming, and leaves the setting untouched when the member list cannot be read. It supports Patroni’s own member slots only, withuse_slotson and no hand-madeprimary_slot_name. Review and adapt it before production use.Let Patroni manage it. Patroni’s development branch has a
manage_synchronized_standby_slotsoption that keepssynchronized_standby_slotsequal to the synchronous standbys ofsynchronous_standby_names; it needssynchronous_modeand is not in a released version at the time of writing (4.1.5 is the latest). Once it ships, prefer it to the callback on clusters that run synchronous replication.Leave it unset and accept the trade-off. Nothing freezes on switchover, but the leader no longer waits for the standby before letting subscribers advance, so a subscriber can be slightly ahead of the standby at the moment of promotion and the new leader marginally behind it. For zero data loss, use one of the two options above.
What a switchover does
patronictl switchoverdemotes the leader and promotes a replica.- On the new leader the synchronized Spock slots become usable; the subscribers only need their DSN pointed at it, as described under After failover.
- The old leader rejoins as a replica. Its own Spock slots carry
failover = trueandsynced = false; Patroni 4.1.0 and later drops them there, and the slotsync worker recreates them as synchronized copies from the new leader. - Whatever manages
synchronized_standby_slotshas to run: the callback fires on both nodes, or you apply the runbook by hand.
Verify
After bootstrap, and again after a switchover, confirm every replica carries the flagged, synchronized slots:
synced and failover should both be true and invalidation_reason
NULL. If failover is false, the slot was created by a Spock release
before 6.0.0 and the upgrade could not flag it. See
Upgrading Spock to 6.0.0 for how to handle it.
On the leader, SHOW synchronized_standby_slots should name the slots of
the replicas that are up, and patronictl list should show them streaming.
Setup: PostgreSQL 15 and 16 (Spock Worker)
On PostgreSQL 15 and 16, the spock_failover_slots background worker
periodically copies slot state from the primary. The worker is registered on
every node, but it only does this work while the server is in recovery; on a
primary it idles.
Requirements
hot_standby_feedback = onon the standby (required before the worker will synchronize anything)- The standby must be able to connect to the primary
Configuration GUCs
| GUC | Default | Description |
|---|---|---|
spock.synchronize_slot_names | name_like:%% | Slot name patterns to sync (all by default) |
spock.drop_extra_slots | on | Drop standby slots not matching the pattern |
spock.primary_dsn | '' | DSN to connect to primary (falls back to primary_conninfo) |
spock.pg_standby_slot_names | '' | Physical slots that must confirm LSN before logical replication advances |
spock.standby_slots_min_confirmed | -1 | How many slots from pg_standby_slot_names must confirm (-1 = all) |
spock.failover_slots_naptime | 1000 | Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000) |
spock.failover_slots_feedback_naptime | 10000 | Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000) |
spock.failover_slots_recreate_invalidated | on | Drop and recreate a synchronized slot whose copy was invalidated on the standby; off leaves it as it is and reports it once. PG15-17 only; ignored on PG17 with native slot sync and on PG18+ (SIGHUP) |
spock.failover_slots_database | '' | Database the worker connects to so it can decode each copy on the standby and give it a consistent snapshot; off by default. PG16-17 only, ignored on PG18+; on PG16 the slots’ database (restart) |
Example (postgresql.conf on standby)
Upgrading Spock to 6.0.0
New slots created by Spock 6.0.0 already have failover = true. Slots created
by an older Spock release do not, and native slot sync on PostgreSQL 17 and 18
ignores slots that do not have the flag. The upgrade turns the flag on for those
existing slots.
This section covers only the failover part of the upgrade. For the full procedure (disabling auto-DDL, installing the new binaries, and restarting each node), follow Upgrading the Spock Extension first. The steps below run after the 6.0.0 binaries are installed.
1. Run the extension update
PostgreSQL walks the version chain (5.0.8 to 5.0.9 to 5.0.10 to 5.0.11 to
5.0.12 to 5.0.13 to 5.0.14 to 6.0.0) and runs each step in order. The 5.0.14
to 6.0.0 step calls
spock.slot_enable_failover() for you.
spock.slot_enable_failover() behaves as follows:
- On PostgreSQL 16 and older it does nothing, because the flag does not exist.
- On a standby it does nothing, because the flag can only be set on a primary.
- It sets
failover = trueon each Spock logical slot that does not already have it. - It skips any slot that is in use at that moment and prints a NOTICE naming the slot.
- It returns the number of slots it changed.
2. Handle any skipped slots
A slot that is actively streaming to a subscriber cannot be changed while it is held, so the function leaves it alone and tells you which one. To set the flag on those slots, pause the subscribers that hold them and run the function again on the primary:
3. Verify
On the primary, every Spock slot should now show failover as true:
The upgrade does not change any PostgreSQL settings. On PostgreSQL 18,
configure native slot sync on the standby yourself as described in
Setup: PostgreSQL 17 and 18 (Native):
sync_replication_slots = on, dbname in primary_conninfo, and the
physical slot listed in synchronized_standby_slots on the primary. To switch a
PostgreSQL 17 standby to the native path, follow
Switching a PostgreSQL 17 standby from the Spock worker.
Monitoring
Check slot sync status (PG17+)
Check if native slotsync worker is active (PG17+)
Check spock worker is running (PG15/16)
This row is present on primaries too, where the worker is resident but idle,
so a hit here confirms only that the worker was registered - not that slots
are being synchronized. Confirm that on the standby by comparing
confirmed_flush_lsn against the primary, and look for the
slot synchronization from primary now active message in the standby log.
FAQ
Q: Do I need to do anything after a failover?
On PG17+: update the subscriber’s host= in their DSN, and, if the promoted
node has synchronized_standby_slots set, clear/adjust it as described in the
runbook above.
No slot recreation is needed.
On PG15/16: Spock’s worker on the standby (now primary) stops
synchronizing slots, since the server is no longer in recovery. The worker
process itself remains, idle, and still holds its max_worker_processes slot.
Subscribers reconnect automatically.
Q: What if sync_replication_slots is not configured on PG18?
Spock’s worker is not registered on PG18. If sync_replication_slots = on
is not set, logical slots will not be synchronized to standbys, and a
failover will require manual slot recreation and table re-sync.
Q: Can I use both mechanisms on PG17?
No. If sync_replication_slots = on is set on PG17, Spock’s worker detects
this and skips its sync loop, deferring to the native worker entirely. To
switch a standby the Spock worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.15 - Limitations and Restrictions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock has several limitations and restrictions that users should be aware of when designing and implementing replication scenarios.
Superuser Privileges Are Required
Currently, the Spock extension requires superuser privileges to configure replication and administration.
UNLOGGED and TEMPORARY Tables Are Not Replicated
UNLOGGED and TEMPORARY tables will not and cannot be replicated, much
like with physical streaming replication.
One Database at a Time
To replicate multiple databases you must set up individual provider or subscriber relationships for each. There is no way to configure replication for all databases in a PostgreSQL install at once.
PRIMARY KEY or REPLICA IDENTITY Required
UPDATEs and DELETEs cannot be replicated for tables that lack a PRIMARY KEY or other valid replica identity such as using an index, which must be
unique, not partial, not deferrable, and include only columns marked NOT
NULL. Replication has no way to find the tuple that should be updated or
deleted since there is no unique identifier.
REPLICA IDENTITY FULL is not supported as a standalone replication identity
for UPDATE or DELETE operations. However, it is supported when used in
conjunction with Delta-Apply columns on tables that have a primary key. For
tables without a primary key or Delta-Apply configuration, UPDATE and DELETE
operations require a PRIMARY KEY or explicit REPLICA IDENTITY USING INDEX.
Only One Unique Index or Constraint or PK
If more than one upstream is configured or the downstream accepts local
writes, only one UNIQUE index should be present on downstream replicated
tables. Conflict resolution can only use one index at a time, so conflicting
rows may ERROR if a row satisfies the PRIMARY KEY but violates a UNIQUE
constraint on the downstream side.
You can have additional unique constraints upstream if the downstream consumer gets writes from that upstream and nowhere else. The rule is that the downstream constraints must not be more restrictive than those on the upstream(s).
Partial secondary unique indexes are permitted, but will be ignored for conflict resolution purposes.
spock.check_all_uc_indexes is an experimental
GUC that
adds INSERT conflict resolution by allowing Spock to consider all unique
constraints, not just the primary key or replica identity.
Unique Constraints Must Not Be Deferrable
Deferrable unique constraints and primary keys are silently skipped during INSERT conflict resolution. This means that if your only unique constraint on a table is deferrable, INSERT conflicts will not be detected, potentially leading to duplicate rows on subscriber nodes.
On the downstream end, spock may also emit the error:
Recommendation: Ensure all tables have at least one non-deferrable unique constraint (preferably the primary key) for reliable conflict detection.
No Replication Queue Flush
There is no support for freezing transactions on the master and waiting until all pending queued xacts are replayed from slots.
This means that care must be taken when applying table structure changes. If there are committed transactions that are not yet replicated and the table structure of the provider and subscriber are changed at the same time in a way that makes the subscriber table incompatible with the queued transactions replication will stop.
Administrators should either ensure that writes to the provider are stopped
before making schema changes, or use the spock.replicate_ddl function to
queue schema changes so they are replayed at a consistent point on the
subscriber.
In multi-master configurations, using spock.replicate_ddl alone is not
sufficient. The subscriber may be generating new transactions with the old
structure after the schema change is committed on the provider. Users must
ensure writes are stopped on all nodes and all slots are caught up before
making schema changes.
FOREIGN KEYS
Foreign keys constraints are not enforced for the replication process - what
succeeds on provider side gets applied to subscriber even if the FOREIGN KEY
would be violated.
TRUNCATE
Using TRUNCATE ... CASCADE will only apply the CASCADE option on the
provider side.
(Properly handling this would probably require the addition of ON TRUNCATE CASCADE
support for foreign keys in PostgreSQL).
TRUNCATE ... RESTART IDENTITY is replicated. The sequence restart is
applied on subscriber nodes. Note that this may cause sequence value
divergence if sequences are not managed via pgEdge Snowflake.
Sequences
We strongly recommend that you use pgEdge Snowflake Sequences rather than using the legacy sequences described below.
The state of sequences added to replication sets is replicated periodically
and not in real-time. Dynamic buffer is used for the value being replicated
so that the subscribers actually receive future state of the sequence. This
minimizes the chance of subscriber’s notion of sequence’s last_value
falling behind but does not completely eliminate the possibility.
It might be desirable to call sync_sequence to ensure all subscribers have
up to date information about given sequence after big events in the database
such as data loading or during the online upgrade.
It is generally recommended to use bigserial and bigint types for
sequences on multi-node systems as smaller sequences might reach end of the
sequence space fast.
Users who want to have independent sequences on provider and subscriber can
avoid adding sequences to replication sets and create sequences with step
interval equal to or greater than the number of nodes. And then setting a
different offset on each node. Use the INCREMENT BY option for CREATE SEQUENCE or ALTER SEQUENCE, and use setval(...) to set the start point.
Triggers
Apply process and the initial COPY process both run with
session_replication_role set to replica which means that ENABLE REPLICA
and ENABLE ALWAYS triggers will be fired.
PostgreSQL Version Differences
Spock can replicate across PostgreSQL major versions. Despite that, long term cross-version replication is not considered a design target, though it may often work. Issues where changes are valid on the provider but not on the subscriber are more likely to arise when replicating across versions.
It is safer to replicate from an old version to a newer version since PostgreSQL maintains solid backward compatibility but only limited forward compatibility. Initial schema synchronization is only supported when replicating between same version of PostgreSQL or from lower version to higher version.
Replicating between different minor versions makes no difference at all.
Database Encoding Differences
Spock does not support replication between databases with different encoding.
The encoding must match on all nodes in the cluster. While UTF-8 is
commonly used and recommended for international character support, any
encoding is acceptable as long as it is consistent across all nodes.
Large Objects
PostgreSQL’s logical decoding facility does not support decoding changes to large objects; we recommend using the LOLOR extension to manage large objects.
Note that DDL limitations apply, so extra care needs to be taken when using
replicate_ddl_command().
Delta-Apply Column Requirements
Columns configured for Delta-Apply conflict resolution must have a NOT NULL
constraint. If a NULL value is encountered during delta application, the apply
worker will error with:
Ensure all Delta-Apply columns are defined with NOT NULL before enabling
this feature.
Mixed Spock and Native Logical Replication
Spock uses its own 16-bit node_id (derived from node name hash) to track transaction origins in commit timestamps, rather than PostgreSQL’s RepOriginId. Both ID spaces overlap (0-65535), which can cause ambiguity if Spock and native PostgreSQL logical replication run on the same database.
Recommendation: Avoid running Spock and native logical replication subscriptions on the same database.
Row and Column Filters
Row and column filters have the following limitations.
System Columns Cannot Be Filtered
System columns (such as oid or xmin) cannot be used in row filters or
column filters. Column and row filters work correctly on tables with OIDs,
but the system columns themselves cannot be filtered.
Row Filter Expression Constraints
Row filters are normal PostgreSQL expressions with the same limitations as CHECK constraints.
A row filter can call random() or now(). random() is VOLATILE and can change on each call. now() is STABLE within a transaction, but different transactions can see different values. Consider when the expression is evaluated to avoid inconsistent results and replication errors.
Row Filter Session Context
Row filters run in the replication session context, not the original
session context. This means that session-specific expressions (like
CURRENT_USER) will have replication session values, not the original
session values.
Column Filter Behavior
When using column filters, note the following behaviors:
- Dropping a filtered column automatically removes it from the filter.
- New columns are not automatically included in existing filters.
- Column filters must be updated manually to include new columns.
Partitioned Tables
Partitioned tables have specific replication limitations.
New Partitions Not Automatically Replicated
When partitions are added after initial synchronization, they must be
added manually using the spock.repset_add_partition() function.
The parent table is synchronized during initial sync, but individual partitions are not synced directly. New partitions created after sync require explicit addition to the replication set.
Detached Partitions Not Automatically Removed
Detaching a partition does not automatically remove it from replication.
You must use spock.repset_remove_partition() to update cluster metadata
and remove the partition from the replication set.
DDL Replication Limitations
Some DDL statements are intentionally not replicated.
DDL Statements Not Replicated
The following types of DDL statements are not replicated:
CREATE DATABASE- Database creation is not replicated.CREATE TABLE...AS...- This statement is replicated but may be unsafe because the table is replicated before being added to the replication set.
In multi-node clusters with three or more nodes, some DDL statements (such
as DROP TABLE) may cause replication issues.
DDL Replication Best Practices
For best results, enable automatic DDL replication only when the schema matches exactly on all nodes. This means either all databases have no objects, or all databases have exactly the same objects with all tables in the replication sets.
Spock Schema
The spock schema is managed internally by Spock and has the following
restriction.
Direct Modification Prohibited
Do not delete, create, or modify files in the spock schema directly. Use
Spock functions and procedures to manage replication. Direct schema
modification can corrupt replication metadata and cause replication
failures.
Read-Only Mode
Read-only mode has the following limitation.
Read-Only at SQL Level Only
The spock.readonly parameter enforces read-only restrictions at the SQL
level for non-superusers. However, background processes (checkpointer,
background writer, WAL writer, and autovacuum) continue to run and may
write to disk.
This means that database files are not truly read-only, and some disk writes may still occur even when read-only mode is enabled.
Replication Position Skipping
Using spock.sub_alter_skiplsn() to skip replication positions has the
following critical limitation.
Skipped Data Not Replayed or Repaired
The spock.sub_alter_skiplsn() operation does not replay or repair
skipped data. Any changes between the old LSN and the specified LSN are
permanently ignored by the subscriber.
Use this function only when you understand the data implications and accept that skipped changes will be lost on the subscriber node.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16 - Internals
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
4.4.2.16.1 - Design proposals
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
4.4.2.16.1.1 - Eliminating the Spock checkpoint hook and per-commit WAL flush for spock.progress
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Date: 2026-04-21 (revised 2026-05-01 to reflect as-built behavior) Status: Implemented
Two design changes from the original proposal, both expanding scope:
remote_commit_tsis recovered post-crash via apg_commit_tsscan, not left NULL. The original design accepted NULL as a freshness regression; the implementation runs a backward scan ofpg_commit_tsfor the relevant origin and repopulates the field. Promoted from a “follow-up” to a goal sospock.progressshows an accurate timestamp after a crash. The recoveredprev_remote_tsis also intended to be useful for the planned parallel-apply rework.- The RMGR (id 144) is kept, retargeted from apply-progress recovery to per-event progress records. The original design deleted it entirely. The shipped version retains the registration and emits one WAL record per affected
SpockGroupHashentry at eachresource.datdump call site (clean shutdown,add_node, table-sync). Each record carries the fullSpockApplyProgresssnapshot for that entry. The records are not required for state recovery; they exist so apg_waldumptrace shows the exact progress snapshot persisted at each event LSN — useful for incident reconstruction over time. A singleXLogFlushat the end of each emit batch gives WAL durability symmetric withresource.dat’sdurable_rename().Sections below are updated to reflect what shipped.
Problem
Spock currently maintains the spock.progress view via three coupled mechanisms:
- A custom WAL RMGR (
src/spock_rmgr.c) that emits aSPOCK_RMGR_APPLY_PROGRESSrecord on every applied remote-origin commit and callsXLogFlushsynchronously (in addition to theXLogFlushthat core’sCommitTransactionCommandalready performs). - A
Checkpoint_hook(registered insrc/spock.c:1248) that dumps the in-memorySpockGroupHashtoPGDATA/spock/resource.datat every Postgres checkpoint. This requires a patch to Postgres core (src/backend/access/transam/xlog.candsrc/include/access/xlog.h) to add the hook callout. - A load/redo path that seeds shmem from
resource.datduringshmem_startup_hookand overwrites with WAL redo ofAPPLY_PROGRESSrecords during recovery.
This design has two costs:
- A Postgres core patch (4 lines across 2 files) must be maintained for each supported Postgres version.
- An extra synchronous
XLogFlushon every applied remote-origin commit, purely to persist monitoring data — doubling the fsync pressure of the apply hot path.
Investigation showed that Spock’s apply worker already uses Postgres’s native replication origins (replorigin_session_get_progress) to determine the resume LSN on reconnect. The correctness-critical “where do I resume from” question is handled entirely by stock logical-replication protocol. The checkpoint hook and WAL RMGR exist only to preserve additional monitoring-level fields (remote_commit_ts, remote_insert_lsn, received_lsn, last_updated_ts) across crashes. The checkpoint hook in particular was added (commit a4b93e8) to handle the case where apply workers are idle across a checkpoint — keepalive-driven advances of remote_insert_lsn are never WAL-logged, so the hook is the only path that preserves them.
Goal
Remove the Postgres core patch (Checkpoint_hook) and the extra per-commit XLogFlush, while preserving user-visible spock.progress behavior across clean and crash restarts. Recover remote_commit_ts after crash via a backward scan of pg_commit_ts for the relevant origin so the view shows an accurate timestamp; the recovered prev_remote_ts is also intended to be useful for the planned parallel-apply rework.
Non-goals
- Changing the
spock.progresscolumn schema or the SQL-level API. - Altering apply-worker resume semantics (which are already handled by Postgres replication origins and need no change).
- Removing or reshaping the
SpockGroupHashshmem layout or theSpockApplyProgressstruct. - Recovering
last_updated_tsprecisely (apply-time timestamp). Post-crash, set to the recoveredremote_commit_ts(the publisher’s commit timestamp) — a lower bound on local apply time that under-reports lag rather than zeroing it. Refreshes on the next applied commit.
Design overview
The shipped design keeps resource.dat as a snapshot written at three call sites — clean shutdown (supervisor before_shmem_exit), add_node, and table-sync — and replaces WAL-based durability with three components:
- Replication origins as the source of truth for
remote_commit_lsn. At apply-worker startup, read the origin’s LSN and reconcile shmem against it. Ifresource.datholds a stale LSN for an entry (file_lsn < origin_lsn), the file’s timestamp fields for that entry are cleared to NULL pending recovery by step 3. - A forced keepalive on apply-worker (re)connect. The subscriber sends a status-update message with
replyRequested=trueimmediately afterspock_start_replicationreturns. Postgres’s walsender responds with a ‘k’ keepalive carrying its currentsentPtr. The apply worker’s existing keepalive handler populatesremote_insert_lsnandreceived_lsnin shmem within milliseconds of reconnect, rather than waiting forwal_sender_timeout / 2(default 30s) to elapse. - A backward
pg_commit_tsscan to recoverremote_commit_tsper origin. When reconcile detects stale or absent state, a follow-on routinerecover_progress_timestamps_from_commit_ts()walkspg_commit_tsbackward from the latest xid, filtering on the publisher’s origin id, and writes the max-by-ts back into shmem. Termination at 1000 commits seen for the origin or 1M xids total scanned, whichever first.last_updated_tsis set to the same recoveredremote_commit_tsso the XOR invariant inprogress_update_structholds; using the publisher’s commit_ts (rather than the subscriber’s wall clock) gives a lower bound on local apply time that under-reports lag instead of hiding it as zero.
Together these handle every shmem field without WAL or checkpoint-time persistence:
| Field | Source | When authoritative |
|---|---|---|
remote_commit_lsn | Replication origin (replorigin_session_get_progress) | At apply-worker startup, always correct |
remote_commit_ts | resource.dat if validated against origin LSN; else pg_commit_ts scan | Preserved across clean restart; recovered post-crash; NULL only on fresh first start (no commits yet) |
remote_insert_lsn | Forced ‘k’ keepalive | Within ~ms of apply worker connect |
received_lsn | Same | Same |
last_updated_ts | GetCurrentTimestamp() at each update; post-crash set to the recovered remote_commit_ts | Always advances during apply; post-crash pinned to the recovered publisher commit_ts as a lower bound on local apply time (under-reports lag rather than zeroing it); refreshes on next applied commit |
prev_remote_ts | Set together with remote_commit_ts (same value) | Same as remote_commit_ts — recovered alongside |
Architecture
Startup flow
Phase 1 — shmem_startup_hook (pre-recovery).
Runs via spock_group_shmem_startup(), unchanged from today except that the spock RMGR no longer carries apply-progress records so WAL recovery has no state-bearing Spock records to redo:
- Create the empty
SpockGroupHashHTAB. - Call
spock_group_resource_load()to loadPGDATA/spock/resource.datif present and valid (version andsystem_identifiermatch). Each record is upserted into the hash viaspock_group_progress_update(). - No state-bearing WAL redo for Spock records. The RMGR (id 144) is retained but its only record type is a dump-event marker whose redo handler emits a
LOGline and does not touch shmem.
At the end of phase 1, shmem contains either an empty hash or the contents of the last clean shutdown’s resource.dat. Values may be stale if a crash occurred since that shutdown.
Phase 2 — per-apply-worker reconciliation.
In spock_apply_main(), after replorigin_session_setup() returns the session’s origin but before spock_start_replication() is called, each worker reconciles its own shmem entry. reconcile_progress_with_origin() returns a ReconcileResult enum so the caller can gate Phase 3 (the recovery scan) on whether reconcile detected staleness.
- Compute the shmem key:
(MyDatabaseId, MySubscription->target->id, MySubscription->origin->id). - Fetch
origin_lsn = replorigin_session_get_progress(false). - Acquire
SpockCtx->apply_group_master_lockin exclusive mode; HASH_ENTER for the entry:- Entry absent. Initialize with
remote_commit_lsn = origin_lsn, other fields zero/NULL. Result:RECONCILE_FILE_ABSENT. - Entry present,
file_lsn == origin_lsn. File is in sync with the origin. Keepremote_commit_tsandlast_updated_tsas loaded. Result:RECONCILE_FILE_IN_SYNC. - Entry present,
file_lsn < origin_lsn. File is stale for this entry. Overwriteremote_commit_lsnwithorigin_lsn; clearremote_commit_tsandlast_updated_tsto 0; bumpremote_insert_lsnandreceived_lsnup to at leastorigin_lsnto preserve theinsert_lsn >= commit_lsninvariant (the forced keepalive will refresh them shortly). Result:RECONCILE_FILE_STALE. - Entry present,
file_lsn > origin_lsn. Anomalous; shouldn’t occur in normal flow. Log a warning and preferorigin_lsn(same body as STALE). Result:RECONCILE_FILE_ANOMALY.
- Entry absent. Initialize with
- Release the lock and return the result.
Phase 2 lives in the apply worker (not the shmem_startup_hook) because the startup hook runs before catalogs and subscriptions are readable.
Phase 3 — pg_commit_ts scan to recover remote_commit_ts.
If reconcile returned anything other than RECONCILE_FILE_IN_SYNC, run recover_progress_timestamps_from_commit_ts(entry, target_origin) where target_origin = MySubscription->origin->id (the publisher’s spock node id, which is what pg_commit_ts records for applied xacts on the subscriber — handle_origin() overwrites replorigin_session_origin per-message with that value).
The scan walks backward from ReadNextTransactionId() - 1 in batches of SPOCK_TS_RECOVERY_BATCH_SIZE (1000), calling TransactionIdGetCommitTsData(xid, &ts, &origin) for each xid. Filter: origin == target_origin. Track per-origin running_max_ts and seen_count. Terminate when:
seen_count >= SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN(1000), ortotal_scanned >= SPOCK_TS_RECOVERY_SCAN_LIMIT(1M), or- backward scan reaches
FirstNormalTransactionId.
The 1000-commits-per-origin termination is justified by concurrency width: the publisher’s max in-flight xacts is bounded well below 1000 by max_connections and pooler limits, so any commit older than the 1000th observed has a strictly smaller commit_ts than the max already seen — even under parallel apply where xid order ≠ commit_ts order on the subscriber.
If running_max_ts > 0, write it under the master lock to remote_commit_ts, prev_remote_ts, and last_updated_ts (XOR invariant in progress_update_struct requires remote_commit_ts and last_updated_ts to be both zero or both non-zero). Using the recovered publisher commit_ts for last_updated_ts rather than the subscriber’s wall clock gives a lower bound on local apply time, which under-reports lag instead of hiding it. The next applied commit refreshes last_updated_ts to the actual subscriber-side GetCurrentTimestamp(). If running_max_ts == 0, log a WARNING and proceed with NULL.
The constants are #defines in src/spock_progress_recovery.c (SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN, SPOCK_TS_RECOVERY_SCAN_LIMIT, SPOCK_TS_RECOVERY_BATCH_SIZE). Convert to GUCs only if profiling motivates tuning.
A LOG line is emitted on completion in either path: “ts recovery: file in sync with origin, skipping scan” (skip) or “ts recovery: scanned N xids, found K commits, recovered remote_commit_ts” (run). LOG rather than INFO because INFO is client-only and does not reach the server log for a bgworker.
track_commit_timestamp = on is required. Spock already enforces this via the spock.conflict_resolution GUC’s check_hook (the only allowed value last_update_wins requires it), which fires at postmaster start. The recovery scan therefore does not need its own guard — by the time it runs, the GUC is guaranteed on.
Phase 4 — forced keepalive.
Immediately after spock_start_replication() returns, before entering the receive loop, the apply worker calls a new helper:
This sends an ‘r’ status-update message with replyRequested=true but leaves send_feedback()’s static bookkeeping untouched. The walsender’s ProcessStandbyReplyMessage sees the flag and calls WalSndKeepalive(false, InvalidXLogRecPtr), which emits a ‘k’ with the publisher’s current sentPtr. The subscriber’s existing keepalive handler routes it through UpdateWorkerStats, populating remote_insert_lsn and received_lsn in shmem.
Runtime flow
Commit path (handle_commit in src/spock_apply.c:992-1023).
Delete the spock_apply_progress_add_to_wal(&sap) call. The surrounding SpockApplyProgress construction remains; spock_group_progress_update_ptr() continues to update shmem. Net: one fewer XLogFlush per applied remote-origin commit.
Keepalive path.
Unchanged. UpdateWorkerStats() updates remote_insert_lsn / received_lsn in shmem for every incoming message.
spock_group_progress_force_set_list() (add_node path).
Used during add_node to populate the new node’s view of mesh-peer progress from read_peer_progress() output. These entries are deduplication state for forwarded transactions in a mesh (not just monitoring), so they must be crash-durable before the first clean shutdown.
Transformation:
- Remove the per-entry
spock_apply_progress_add_to_wal(sap)call. - Per entry: acquire master lock → mutate shmem → release lock (no I/O under the lock).
- After the loop: call
spock_group_resource_dump()once to persist all entries atomically viadurable_rename.
Rationale: resource.dat is a full-snapshot dump, not an incremental format, so N per-entry dumps would rewrite the entire file N times. A single post-loop dump gives equivalent durability (add_node is all-or-nothing at the admin level) with O(1) file writes.
spock_group_progress_update_list() (table-sync path).
Same transformation as force_set_list: drop the per-entry WAL call, add a single spock_group_resource_dump() after the loop.
Shutdown flow
The clean-shutdown dump runs from the supervisor’s before_shmem_exit callback (spock_supervisor_on_exit in src/spock.c), not from postmaster context. The supervisor first poll-waits for sibling apply/sync workers to clear their PGPROC slots (~5 s ceiling), then calls spock_group_resource_dump() followed by spock_rmgr_log_resource_dump(SPOCK_DUMP_SHUTDOWN, NULL). Running in the supervisor process is required for the WAL emit (postmaster has no backend slot for XLogInsert); the drain wait ensures the file dump and the SHUTDOWN forensic records both reflect each worker’s last update to SpockGroupHash. This is the sole remaining runtime producer of resource.dat on clean exit.
Code changes
Delete
spock_checkpoint_hook()function insrc/spock_group.c(no longer registered or referenced).extern void spock_checkpoint_hook(...)declaration ininclude/spock_group.h.- The apply-progress recovery contents of
src/spock_rmgr.c(the redo handler that replayedSPOCK_RMGR_APPLY_PROGRESSrecords into shmem). The file itself is retained — see “Trim, do not delete” below. - The
spock_apply_progress_add_to_wal()emit helper.
Remove one-liners
src/spock.c—Checkpoint_hook = spock_checkpoint_hook;.src/spock_apply.c:handle_commit—spock_apply_progress_add_to_wal(&sap);.src/spock_group.c:spock_group_progress_update_list—spock_apply_progress_add_to_wal(sap);.src/spock_group.c:spock_group_progress_force_set_list—spock_apply_progress_add_to_wal(sap);.#include "spock_rmgr.h"ininclude/spock_group.h(was a circular include with no consumer).
Trim, do not delete
src/spock_rmgr.c— replace the apply-progress recovery contents with a single record typeSPOCK_RMGR_RESOURCE_DUMP. New emit helperspock_rmgr_log_resource_dump(event, changed_entries)is called at each of the threeresource.datdump call sites. Each call emits one WAL record per progress entry, carrying the fullSpockApplyProgresssnapshot for that entry so apg_waldumptrace shows exactly what state was on disk at each event LSN — useful for incident reconstruction over time. A singleXLogFlushat the end of each emit batch covers all records.- For
SHUTDOWNandADD_NODE: caller passesNULLforchanged_entries; the helper walksSpockGroupHashand emits a record per entry. Both events reflect changes across all subscriptions. - For
TABLE_SYNC: caller passes the same list ofSpockApplyProgress *it just used to update shmem. Only the affected subscription’s entries are emitted, since table-sync is per-subscription. - Redo handler emits a
LOGline per record showing event type, sequence in batch, key, LSNs, andcommit_ts. Records are not used for state recovery.
- For
include/spock_rmgr.h— replace declarations to match the trimmed contents (SPOCK_RMGR_ID = 144,SPOCK_RMGR_RESOURCE_DUMP = 0x10,SpockResourceDumpReccarryingevent_type+entry_seq/entry_total+ the embeddedSpockApplyProgress,SpockResourceDumpEvent, the emit helper).src/spock.c—spock_rmgr_init()call retained in_PG_init. Header include retained.
Modify
src/spock_progress_recovery.candinclude/spock_progress_recovery.h(new module) — single public entry pointspock_init_progress_state(XLogRecPtr origin_lsn). File-static internals: theReconcileResultenum,reconcile_progress_with_origin(),recover_progress_timestamps_from_commit_ts(), and theSPOCK_TS_RECOVERY_*#defines.src/spock_apply.c— add a new helperrequest_initial_status_update(PGconn *conn, XLogRecPtr startpos)that emits an ‘r’ message withreplyRequested=truewithout touchingsend_feedback’s static state.src/spock_apply.c:spock_apply_main— betweenreplorigin_session_setupandspock_start_replication, callspock_init_progress_state(origin_lsn)once; this internally runs reconcile and (if reconcile detected staleness) thepg_commit_tsscan. Afterspock_start_replicationreturns, callrequest_initial_status_update.src/spock_group.c:spock_group_progress_force_set_list— drop the WAL call; add a singlespock_group_resource_dump()followed byspock_rmgr_log_resource_dump(SPOCK_DUMP_ADD_NODE, ...)after the loop.src/spock_group.c:spock_group_progress_update_list— same withSPOCK_DUMP_TABLE_SYNC.src/spock.c:spock_supervisor_main— registerspock_supervisor_on_exitviabefore_shmem_exit. The callback poll-waits for apply/sync workers to detach via a new helperspock_any_apply_worker_running()(insrc/spock_worker.c), then callsspock_group_resource_dump()followed byspock_rmgr_log_resource_dump(SPOCK_DUMP_SHUTDOWN, NULL). The previous postmaster-contextspock_on_shmem_exitinsrc/spock_shmem.cis removed entirely; both file and WAL dumps now have a single owner that runs in the supervisor process whereXLogInsertis permitted.
Keep unchanged
- Clean-shutdown gating semantics (only dumps if
code == 0) — preserved inspock_supervisor_on_exit. spock_group_resource_load(),spock_group_resource_dump()— load/dump file-format code.SpockApplyProgressandSpockGroupEntrystruct layouts.spock.progressSQL view andget_apply_group_progress()function.
Postgres core patch removal
The patch can be reverted entirely after the Spock-side removal. Four lines across two files:
postgresql/src/backend/access/transam/xlog.c:173—Checkpoint_hook_type Checkpoint_hook = NULL;.postgresql/src/backend/access/transam/xlog.c:7648-7649— 2-lineif (Checkpoint_hook) Checkpoint_hook(...)invocation insideCreateCheckPoint.postgresql/src/include/access/xlog.h:218-219— typedef +extern PGDLLIMPORTdeclaration.
No other Spock or Postgres-patch code depends on Checkpoint_hook.
Edge cases
Forced keepalive: publisher never responds. Not blocking. The apply worker proceeds into its normal receive loop; remote_insert_lsn / received_lsn stay at seeded values (or NULL) until a ‘k’ or ‘w’ arrives via Postgres’s own wal_sender_timeout / 2 cadence. Worst case matches current behavior.
Startup: origin exists but resource.dat is missing. Phase 2 initializes a fresh shmem entry with remote_commit_lsn = origin_lsn and NULL timestamps. Equivalent to first-time start.
Startup: resource.dat entry for a subscription that was dropped. Old entry sits in shmem; no apply worker reconciles it. Matches current behavior. Optional follow-up: purge unknown entries after catalog is readable.
Startup: origin LSN is InvalidXLogRecPtr. Subscription exists but nothing has been applied. Reconcile still runs first: if the loaded resource.dat entry has file_lsn > 0 it is treated as ANOMALY (file ahead of origin) — commit_lsn is overwritten to 0, timestamps cleared, insert/received bumped to 0. If file_lsn == 0 the IN_SYNC branch keeps the file as-is. The pg_commit_ts scan is then skipped via the XLogRecPtrIsInvalid(origin_lsn) short-circuit in spock_init_progress_state, since a fresh origin has no progress to recover and pg_commit_ts rows from a prior subscription would only backfill stale historical timestamps.
add_node retry. Failed mid-loop leaves shmem partially updated and the file untouched (dump runs only after the loop completes). Second run’s unconditional overwrite (init_progress_fields then progress_update_struct) replaces partial state; dump runs after the loop. Fine.
add_node interrupted after dump. All entries persisted; re-run is idempotent.
Multiple apply workers. Each worker reconciles its own key under the master lock. No cross-worker interference. Forced keepalive is per-connection.
Post-crash with publisher offline. remote_commit_ts is recovered from the subscriber’s pg_commit_ts (which survives the crash) by the Phase 3 scan. Recovery does not depend on the publisher being reachable. The only situation that yields NULL is one where pg_commit_ts itself has no entries for this origin within the last 1M xids — typically a fresh subscription that has not yet applied any commits.
Recovery scan finds nothing. If the subscriber has no pg_commit_ts entries with roident == target_origin in the last 1M xids, running_max_ts stays 0. We log a WARNING and proceed with NULL remote_commit_ts. This is rare and matches the fresh-subscription case anyway.
Recovery scan picks up unrelated commits. The filter roident == MySubscription->origin->id is the publisher’s spock node id, not subscription-unique. Sibling subscriptions to the same publisher, or a dropped/recreated subscription with old commits still in the 1M-xid window, can contribute to running_max_ts. Under monotonic publisher clocks the max-by-ts naturally prefers the most recent commit (current sub), so the failure mode is narrow: clock skew between drop and recreate, or scenarios where stale commits are newer than current ones. Impact is forensic-only — prev_remote_ts is not consumed today (apply-group ordering is disabled). The planned parallel-apply rework is the natural place to revisit.
Concurrency width vs. termination bound. The scan stops after observing 1000 commits per origin, which is correct only if max in-flight concurrent xacts on the publisher is bounded below 1000. PostgreSQL’s max_connections defaults to 100, and pooled deployments cap effective concurrency well below that. If a deployment ever exceeds it, the constant is a single #define to bump.
Publisher clock skew (NTP step-back). running_max_ts is the max-by-ts. If the publisher’s clock steps backward such that commit_ts order disagrees with commit order, the recovered prev_remote_ts may not match the next transaction’s required_commit_ts from the publisher. Theoretical only — the apply-group ordering machinery that consumes prev_remote_ts is currently disabled. The planned parallel-apply rework will revisit. Out of scope for this design.
Shmem hash full during force_set_list. Warn and continue (existing behavior unchanged). Post-loop dump persists whichever entries made it in.
Concurrent shutdown during reconciliation. Worker completes its update under the lock, releases, exits on next CHECK_FOR_INTERRUPTS. Shutdown hook dumps resource.dat with the reconciled values. Reconciliation-then-dump cannot leave shmem more stale than the file.
Testing
Modified existing tests
tests/tap/t/008_rmgr.pl— rewrote Phase 4 assertions for the new reconcile semantics. Covers the multi-origin case (Scenario A: file has stale entry, Scenario B: file has no entry for an origin). The test issues aCHECKPOINTbefore SIGKILL so the apply worker’s WAL is durable past batch-2; without this, walwriter-cadence races could leave recovery’s origin LSN at batch-1 and reconcile would take the IN_SYNC path instead of STALE.tests/tap/t/022_rmgr_progress_post_checkpoint_crash.pl— rewrote to assert that reconcile detectsfile_lsn < origin_lsnafter a crash, advancesremote_commit_lsnfrom the replication origin, and (with the recovery scan) thatremote_commit_tsis recovered non-NULL post-crash. Also asserts CHECKPOINT does NOT updateresource.dat(regression guard against re-introducing the checkpoint hook).
New tests
023_forced_keepalive_timing.pl— setwal_sender_timeout=10minso the timer-driven path is disabled; assertremote_insert_lsnpopulates within 1 second (proves the forced keepalive, not the timer, drove the refresh).026_no_double_wal_flush.pl— countpg_stat_wal.wal_syncdelta over 30 applied commits; assert delta < N (no per-commit forced fsync on the apply hot path).027_remote_commit_ts_recovery.pl— apply commits, clean restart, more commits, CHECKPOINT, SIGKILL, restart; assertremote_commit_tsis non-NULL post-crash (recovered via thepg_commit_tsscan).029_remote_commit_ts_recovery_clean_shutdown.pl— clean restart only; assert the skip-pathLOGline (“file in sync with origin, skipping scan”) fires and the run-path log does not, andremote_commit_tsis preserved.
Deferred / not implemented
track_commit_timestamp = offtest. Cannot occur in practice because spock’s existingspock.conflict_resolutionGUC validation aborts the postmaster at startup if the GUC is off. The recovery scan is unreachable in that scenario.- Idle-cluster test (no commits in last 1M xids). Would require either >1M unrelated xids of activity or a temporary constant override. Both too heavy for v1.
add_nodeinterrupted mid-loop test. Out of scope for this design; covered by existingadd_nodeintegration tests.
Regression safety checks
spock.progresscolumn set unchanged.read_peer_progress()SQL function output unchanged.- Downstream tools reading
spock.progress(spockctrl, monitoring scripts) see no schema or column-type changes.
Follow-ups (out of scope)
- Convert
SPOCK_TS_RECOVERY_*#defines to GUCs if any deployment ever needs to tune them. - Generalize the forensic RMGR record into a small audit-event family covering more rare events (
add_node/drop_nodelifecycle, subscription state transitions, sync start/end). Sketched separately in2026-05-01-spock-audit-rmgr-design.md. - Revisit the parallel-apply ordering coordinate. The current
commit_ts-based approach is exposed to publisher clock skew; alternatives will be considered alongside the parallel-apply rework. - Multi-origin shared scan: a single backward pass that populates all origins’ shmem entries at once, gated by a per-origin “recovery done” flag in
SpockGroupEntry. Worth doing only if profiling shows per-worker scan cost matters. - Purging
resource.datentries that reference subscriptions that no longer exist. - Removing the obsolete
updated_by_decodefield from theSpockApplyProgressstruct layout. (prev_remote_tsis still actively used as the wait/signal coordinate for the parallel-apply machinery — keep until that rework lands.)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16.1.2 - Spock Node Monitoring: Design of the spock_monitor subsystem
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Date: 2026-09-23
Status: Implemented, regression tested
Component: src/spock_monitor.c, include/spock_monitor.h
PostgreSQL: 15 to 19
A Word version of this document is kept next to it as
spock-monitor-design.docx.
1. Summary
Operators of a Spock cluster have had to read the PostgreSQL server log to answer routine questions: is every subscription replicating, did a worker restart overnight, why was a subscription disabled, how much WAL is a slot holding back, did the extension get upgraded. The catalog and the existing statistics views describe configuration and cumulative counters but not state changes or failures.
The monitoring subsystem records state changes as events and keeps
per-subscription activity counters in shared memory, and exposes them
together with worker, slot and replication progress through eleven views in
the spock schema. A query against spock.node_status or
spock.subscription_status gives the complete picture of a node;
spock.events gives the recent history. The module is also the single home
of all monitoring C code, absorbing the channel counters, the apply group
progress function and the slot confirmation wait.
2. Goals and non-goals
Goals
- Replace log reading for day to day operation: every notable state change is queryable.
- One row per node, per subscription, per worker and per slot, with column names that need no legend.
- Cheap on the apply hot path: a spinlock and a few integer adds per message, no catalog writes, no WAL.
- Safe in error paths: recording an error must never allocate memory, block or raise.
- Same source on every supported PostgreSQL version; version specific data such as the PG18 conflict counters degrade to NULL.
- One module for all monitoring code, with PostgreSQL naming and layout conventions.
Non-goals
- Durability across a postmaster restart. Events and counters live in shared memory only; the catalog and pgstat remain the durable stores.
- Transactional semantics. An event is recorded when the reporting code runs, whether or not its transaction commits.
- Cluster wide aggregation. Each node reports about itself; a fleet view is left to external tooling that reads the views on every node.
3. Architecture
The subsystem has three layers: shared memory structures written by spock
processes, C functions that read them and return rows, and SQL views that
join those rows with the catalogs and with core views such as
pg_stat_replication and pg_stat_activity.
| Layer | Elements | Owner |
|---|---|---|
| Shared memory | Event ring (SpockMonitorShmem), per-subscription counters (SpockMonitorStatsHash) | spock_monitor.c, allocated by spock_shmem.c |
| Producers | Worker attach and detach, apply loop, sync worker, output plugin, node and subscription management functions, exception handler, extension manager, emit_log_hook | One call at each site |
| SQL functions | get_worker_status, get_events, get_apply_stats, get_slot_groups, get_monitor_summary, reset_events, reset_subscription_stats, get_channel_stats, reset_channel_stats, apply_group_progress, wait_slot_confirm_lsn | spock_monitor.c |
| Views | system_status, node_status, subscription_status, subscription_stats, worker_status, slot_status, peer_status, replication_set_status, settings, table_sync_status, events | sql/spock--6.0.0.sql and the 5.x upgrade script |
Producers never format SQL or touch the catalog. They call one of a handful
of functions declared in spock_monitor.h, which copy fixed size data into
shared memory under a lock. Readers take a consistent copy of each entry
and build tuples outside any spinlock.
4. Shared memory
4.1 Event ring
Events are stored in a fixed size ring inside one ShmemInitStruct
allocation named spock monitor. The capacity is the
spock.event_history_size GUC (default 1024, PGC_POSTMASTER).
The header holds the LWLock, the time shared memory was initialized
(reported as spock_started_at), the next event id, and head and count
indexes. Appending when full advances the head, so the oldest event is
dropped. Event ids keep increasing across resets, which lets a poller detect
both new events and gaps. The ring is cluster wide; the views filter on the
current database and keep events without a database, such as those of the
supervisor.
Each event type has a fixed name and severity in a table indexed by the
enum, so adding a type means adding one enum member and one table row.
Severities are info, warning and error; warning covers state changes
an operator would want to know about even when they were requested, such as
a subscription being disabled, repair mode being switched on or a
transaction being skipped.
4.2 Per-subscription counters
Counters live in a fixed size shared hash keyed by (dboid, subid), sized
at max(64, 4 * max_worker_processes) entries. The multiple leaves room for
disabled subscriptions whose history should survive while they are down.
Every counter carries the time of its last increment. That one rule gives
the view its last_worker_start, last_provider_connect,
last_xact_applied and last_apply_error columns without separate fields,
and keeps the reader generic: two small tables in spock_get_apply_stats()
map counters to count columns and to timestamp columns, checked at compile
time against the column enum.
| Counter | Incremented when |
|---|---|
worker_starts | An apply worker attaches to its shared memory slot. |
worker_failures | An apply worker detaches after an error exit. |
sync_worker_starts, sync_worker_failures | The same for sync workers, so a resync is told apart from an apply worker restart. |
provider_connects | START_REPLICATION succeeded in the apply worker. |
provider_disconnects | apply_work() classified an error as connection loss. A sync worker’s failed connection is recorded as an event and as the last error but not counted here, so the two counters pair. |
idle_timeouts | spock.apply_idle_timeout forced a reconnect. |
messages_received, bytes_received | A data message was read from the stream. |
xacts_applied | A remote transaction committed locally. |
xacts_skipped | A transaction was skipped through sub_skip_lsn. |
xacts_discarded | A transaction was discarded under transdiscard. |
apply_errors, sync_errors | An ERROR was raised in an apply or sync worker (section 6). |
deadlocks, lock_timeouts, constraint_violations, resource_errors | The same errors classified by SQLSTATE. |
tables_synced | A sync worker finished a table without failure. |
A worker caches a pointer to its entry in MySpockMonitorStats when it
attaches. Entries in a HASH_FIXED_SIZE shared hash are never moved, so the
pointer stays valid for the life of the process. Counting is then a
spinlock, an add and a timestamp. Backends that only record events do not
touch the hash.
Subscription ids come from a cycling sequence, so an id can be reused. Each entry counts the workers attached to it. Dropping a subscription removes the entry at once when no worker is attached; otherwise the entry is only marked dropped and the last worker to detach removes it, so a worker never writes through a pointer into a freed element. A worker that attaches to an entry marked dropped, because the id was reused, resets it.
4.3 Locking
- One LWLock in the tranche
spock_monitorprotects the ring and the hash structure. Individual entries have a spinlock for their counters. - The monitor lock is a leaf: no other lock is taken while holding it. It
may be acquired while
SpockCtx->lockis held, never the other way round. - The error reporting path uses
LWLockConditionalAcquireand skips the event if the lock is busy, so error reporting can never block. - Readers hold the monitor lock only while copying the ring or the entries into local memory, so that error reporting, which only tries the lock, is not held off while a result is formatted.
5. Instrumentation points
Each producer adds one call at the place where the state change is already logged, so the event and the log line always agree.
| Event type | Call site |
|---|---|
node_created, node_dropped | spock_create_node(), spock_drop_node() after the catalog change |
subscription_created, subscription_dropped | spock_create_subscription(), spock_drop_subscription() |
subscription_enabled, subscription_disabled | spock_alter_subscription_enable(), spock_alter_subscription_disable(), spock_disable_subscription() in the exception handler |
subscription_altered | Interface change, replication set add and remove, skip_lsn, options, synchronize and resynchronize table |
worker_started, worker_stopped, worker_failed | spock_worker_attach() and spock_worker_detach(); the failure detail carries the last recorded error message |
worker_error | emit_log_hook, for any ERROR or FATAL in a spock worker |
provider_connected, provider_disconnected | spock_start_replication(); the connection loss branch of apply_work() |
transaction_skipped, transaction_discarded | stop_skipping_changes(); the transdiscard branch of handle_commit() |
sync_started, sync_finished, sync_failed | spock_sync_main() and spock_sync_worker_finish() |
slot_created, stream_started, stream_stopped | pg_decode_startup() with and without is_init; pg_decode_shutdown() |
apply_paused, apply_resumed | spock_pause_apply_workers(), spock_resume_apply_workers() |
repair_mode_enabled, repair_mode_disabled | spock_repair_mode() |
extension_upgraded | spock_manage_extension() after ALTER EXTENSION UPDATE |
Worker start and stop are recorded in the generic attach and detach code,
so the manager, every apply worker and every sync worker are covered by two
call sites. The detach hook runs before SpockCtx->lock is taken, which
keeps the lock order simple.
6. Error capture
Rather than instrumenting each error site, the module hooks the existing
emit_log_hook installed by spock.c. spock_monitor_report_error() is
called for every report and applies these rules:
- Ignore unless the process is a spock worker (
MySpockWorkeris set) or a walsender running the spock output plugin, and shared memory is attached. - Ignore levels below ERROR and at or above PANIC; a PANIC path must not take locks.
- Treat connection class errors (connection failure, admin shutdown,
cannot connect now and the related codes) as a lost peer, never as an
apply error. In a worker the hook records them as
provider_disconnectedwith the message kept as the last error, which covers failures at connect or START_REPLICATION time that no handler catches.apply_work()uses the same predicate for its connection-loss branch and reports through the same function before rethrowing; it flags the rethrow so the hook does not count it again. In a walsender such an error is the subscriber going away and nothing is recorded. - In a walsender, record a
stream_errorevent with the slot name, the SQLSTATE and the message. The output plugin marks the process at startup and clears the mark at shutdown. Only a walsender is marked: a regular backend decoding a slot through the SQL functions gets no shutdown call when decoding fails, and its later errors must not be reported as stream errors. - For apply and sync workers, bump
apply_errorsorsync_errorsand the matching class counter (deadlock, lock timeout, constraint violation, resource error), and store the message, SQLSTATE, pid and the current origin LSN as the last error. - Record a
worker_errorevent with the message and SQLSTATE, using a conditional lock acquire.
The message stored is the error message followed by the DETAIL and CONTEXT
lines, so a constraint violation carries the failing row and the apply
context. The function is guarded against re-entry and does no allocation:
the text is formatted with snprintf into fixed buffers.
An ERROR caught by a PG_CATCH is never emitted: PostgreSQL longjmps
before EmitErrorReport(), and the apply worker’s handler copies and
flushes the error. The hook therefore only sees errors that end the worker.
The two paths of apply_work() that swallow an error, the first exception
that enters replay and the sub_disable path, call
spock_monitor_report_error() on the copied ErrorData themselves; the
paths that rethrow leave it to the hook so that an error is counted once.
Under sub_disable the replay ends with a synthetic error requesting the
disable; the worker remembers that the transaction’s first error was
already reported and does not report that one. Row level errors during a
discard replay are not counted again, so apply_errors counts failed
transactions rather than failed rows.
7. SQL surface
7.1 Functions
Functions return raw shared memory rows and are the tooling interface. Set
returning functions use InitMaterializedSRF and OUT parameters; the C
code checks the column count against its enum with an assertion.
| Function | Returns |
|---|---|
spock.get_worker_status() | Every worker slot in the cluster plus the supervisor, with database_id |
spock.get_events() | Every event in the ring, oldest first, with database_id |
spock.get_apply_stats() | Counters of every subscription of the current database, with PG18 conflict counters |
spock.get_slot_groups() | Slot groups with attached walsenders |
spock.get_monitor_summary() | One row: start time, supervisor pid, slot and capacity usage |
spock.get_system_info() | One row: host name, operating system, CPU, memory, load averages, statvfs() of the data directory and of pg_wal, postmaster start, PostgreSQL and spock versions |
spock.get_pending_exceptions() | Exception log slots with a recorded error: the transactions being retried, with failed_action_number, the position of the failing change in its transaction |
spock.report_section(title, query, expanded) | The rows of a query as text, values in PostgreSQL text form |
spock.node_report(recent) | The whole node as a text report, one section per view |
spock.reset_events() | Empties the ring; ids keep increasing |
spock.reset_subscription_stats(subid) | Resets activity and, on PG18, conflict counters of one or all subscriptions |
spock.redact_dsn(text) | Connection string with the password hidden, keyword and URI forms |
7.2 Views
Views are named by what they show: *_status for state, *_stats for
counters. Columns use full words, never abbreviations, and the same word for
the same thing everywhere (subscription_name, provider_node,
worker_pid, replication_lag_bytes).
| View | Rows | Built from |
|---|---|---|
spock.system_status | Exactly one | get_system_info(), pg_stat_activity, pg_prepared_xacts, pg_stat_replication, pg_database, pg_stat_database, pg_stat_archiver, spock.wal_size_bytes() |
spock.node_status | Exactly one | get_monitor_summary(), local_node, pg_extension, aggregates over the other views, spock.wal_size_bytes() |
spock.subscription_status | One per subscription | subscription, node, node_interface, local_sync_status, get_worker_status() (lateral, running worker preferred), pg_stat_activity, progress, replication_origin_status(), subscription_stats |
spock.subscription_stats | One per subscription | get_apply_stats() and channel_summary_stats, counters coalesced to zero |
spock.worker_status | One per worker | get_worker_status(), pg_stat_activity, pg_blocking_pids() for the session holding a lock the worker waits for |
spock.slot_status | One per spock slot | pg_replication_slots, pg_stat_replication, get_slot_groups(), current or replay WAL position |
spock.table_sync_status | One per sync row | local_sync_status with readable kind and status |
spock.peer_status | One per node and subscription | node, node_interface, subscription_status |
spock.replication_set_status | One per replication set | replication_set with counts over its tables, sequences and subscriptions |
spock.settings | One per parameter | pg_settings, spock parameters and the core replication parameters, DSNs redacted |
spock.events | One per event | get_events(), subscription and node for the provider name |
The status text of a subscription is computed in SQL with the same rule as
spock.sub_show_status(): replicating, initializing or unknown while
a worker runs, otherwise disabled or down. Computing it in the view
keeps node_status usable before a local node exists, where the function
would raise an error.
The slot view uses only columns present in pg_replication_slots since
PostgreSQL 15, because one SQL script serves every version. It falls back
to pg_last_wal_replay_lsn() on a standby so it never raises during
recovery.
7.3 The report
spock.node_report() is a plpgsql function that calls
spock.report_section() once per view. The formatter runs the query twice:
once through row_to_json to learn the column names in query order, then
with every column cast to text so that values appear as PostgreSQL prints
them rather than as JSON. Each section’s query runs inside its own
exception block, so a failing view produces one error line instead of
aborting the report. Passwords never appear: the views already redact
connection strings, and spock.settings redacts the DSN parameters.
The exception handler keeps one shared slot per subscription with the
commit LSN of the transaction in flight and the first error raised for it.
spock.get_pending_exceptions() reports only slots with an error, because
the LSN alone is set for every transaction.
8. Compatibility and upgrade
- The same SQL section is appended to
spock--6.0.0.sqland tospock--5.0.14--6.0.0.sql. Every catalog column the views reference exists since 5.0.6, so an upgraded node ends with the same objects as a fresh install. spock.get_apply_worker_status()is kept for existing callers, as a SQL function overspock.get_worker_status()returning the 5.x columns and rows. Its C symbol stays as a stub that raises an error, because pg_upgrade from 5.x recreates the old C binding before the extension update replaces it.spock_monitoring.cis removed.spock.wait_slot_confirm_lsn(),spock.get_channel_stats(),spock.reset_channel_stats()andspock.apply_group_progress()keep their SQL definitions and C symbols and now live inspock_monitor.c.spock.reset_subscription_stats()keeps its SQL definition and C symbol, so the existing upgrade script needs no change, but it now resets both counter sets and no longer raises before PostgreSQL 18.- Conflict counters are fetched through the pgstat entry under
PG_VERSION_NUM >= 180000and are NULL otherwise. - Shared memory grows by the ring plus the hash.
SpockMonitorStatsEntryis 800 bytes, dominated by its 512-bytelast_error_messageand the two per-counter arrays, so the hash costs roughly that plus dynahash overhead for each subscription tracked, bounded bymax(64, 4 * max_worker_processes)entries.SpockMonitorEventis 560 bytes, dominated by its 512-bytedetail, so the ring costsspock.event_history_size * 560bytes: 560 kB at the default 1024, and a megabyte or more if the setting is raised. Size shared memory from that figure rather than from the event count alone.
9. Testing
The regression test tests/regress/sql/monitor.sql runs after basic and
checks, on the provider, node_status, worker_status, slot_status and
the provider side events, and on the subscriber, subscription_status,
worker_status, table_sync_status, subscription_stats after real
traffic, the events of subscription creation and worker start, both reset
functions, and that disabling and enabling a subscription produces the
expected events and a worker restart that is visible in the counters.
Values that vary between runs are compared, not printed. The full suite of
41 tests passes on PostgreSQL 18.
10. Limitations and future work
- The views and the functions they call (
get_system_info(),get_events(),get_apply_stats(),get_pending_exceptions(),replication_origin_status(), which stands in for the superuser-onlypg_replication_origin_status) are granted topg_monitor; a superuser or a member of that role reads them.wal_size_bytes()stays callable by any role, as the total WAL size is not sensitive. The reset functions are superuser only. - The subscription stats hash is bounded at
max(64, 4 * max_worker_processes)entries. Past that,spock_monitor_attach_stats()returns NULL and logs it; the worker carries on and the subscription operates normally, but its counters are not recorded:spock.subscription_statsstill has its row, with every counter read as 0 and every timestamp as NULL, so a subscription past the bound looks idle rather than unrecorded.spock.node_status.channel_stats_fullreports the same condition for the channel counter hash. - The ring is cluster wide, so a database with heavy activity can age out the events of a quiet one. A per-database ring would remove this at the cost of more shared memory.
- Events and counters are lost at postmaster restart. If history across restarts is wanted, a background worker could periodically append events to a spock catalog table.
pg_replication_slotscolumns added in PostgreSQL 17 (failover,invalidation_reason,inactive_since) are not shown; a version conditional view would be needed.- Replication set changes on the provider (table added or removed) are not events; they are visible in the catalog and could be added with two call sites.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16.2 - Historical plans
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
4.4.2.16.2.1 - remote_commit_ts Recovery via pg_commit_ts Scan — Implementation Plan
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: After crash recovery, scan pg_commit_ts backward to recover the most-recent remote_commit_ts per origin so spock.progress shows accurate values post-crash; the recovered prev_remote_ts is also intended to be useful for the planned parallel-apply rework.
Architecture: New file-static function recover_progress_timestamps_from_commit_ts() in src/spock_apply.c, called from spock_apply_main after reconcile_progress_with_origin and before spock_start_replication, gated on a new ReconcileResult enum so the scan only runs when the loaded resource.dat is stale or missing. Termination after observing 1000 commits per origin or scanning 1M xids total. Hard error if track_commit_timestamp is off.
Tech Stack: C (Postgres extension), Postgres SLRU API (TransactionIdGetCommitTsData), Perl TAP tests (existing SpockTest module).
Pre-flight:
File Structure
| File | Role | Change |
|---|---|---|
src/spock_apply.c | Apply worker main, reconcile, new recovery function | Modify |
tests/tap/t/027_remote_commit_ts_recovery.pl | Happy path | Create |
tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl | Skip-path verification | Create |
tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl | Error-path verification | Create |
No header changes — ReconcileResult is file-static.
Task 1: Refactor reconcile_progress_with_origin to return ReconcileResult
Why first: The recovery function needs to know which reconcile branch was taken so it can skip when the file is in sync. Threading the enum through is purely structural with no behavioral change, so it’s safe to land first.
Files:
Modify:
src/spock_apply.c— add enum near other forward declarations (~line 245-260), change function signature atsrc/spock_apply.c:2937-2938, update caller atsrc/spock_apply.c:4216.Step 1.1: Add the enum near the existing forward declarations
Locate the forward declarations block at src/spock_apply.c:248-257:
Replace the last line with the enum and updated declaration:
- Step 1.2: Update the function definition to return the enum
At src/spock_apply.c:2937, change:
to:
In the body (current src/spock_apply.c:2944-3043), each branch must return the appropriate enum value.
- The early-return at the top (
!SpockGroupHash || !SpockCtx) — change toreturn RECONCILE_FILE_ABSENT;. The hash isn’t set up; treat as absent. - The
entry == NULLcase (hash full) — changereturn;toreturn RECONCILE_FILE_ABSENT;and continue with the existing WARNING. - The
if (!found)branch — after the existing log line,result = RECONCILE_FILE_ABSENT;. - The
else if (entry->progress.remote_commit_lsn == origin_lsn)branch —result = RECONCILE_FILE_IN_SYNC;. - The
else if (entry->progress.remote_commit_lsn < origin_lsn)branch —result = RECONCILE_FILE_STALE;. - The final
else(anomaly) branch —result = RECONCILE_FILE_ANOMALY;.
Concretely, declare ReconcileResult result; near the top of the function, set it in each branch, and return it after LWLockRelease.
- Step 1.3: Update the caller to receive the result
At src/spock_apply.c:4216, change:
to:
The variable is unused for now; Task 4 wires it up. Suppress the unused-variable warning by adding (void) reconcile_result; directly below the call, with a comment /* used in Task 4 */.
- Step 1.4: Build and verify no behavioral regression
Expected: clean build, no new warnings.
Expected: all subtests pass (this test exercises the reconcile path most heavily).
- Step 1.5: Commit
Task 2: Add the recovery constants
Files:
Modify:
src/spock_apply.c— add#defines near the top of the file, after the existing macros / includes.Step 2.1: Add the three
#defines
Find an appropriate spot near the top of src/spock_apply.c (after the includes, near other apply-side #defines if present, or otherwise just before the forward declarations). Add:
- Step 2.2: Build to verify
Expected: clean build (no use sites yet, but the macros exist).
- Step 2.3: Commit
Task 3: Write the failing happy-path test (027)
Why before implementation: Establishes the regression target — running this test against main (or after Task 2) must fail; running it after Task 4 must pass.
Files:
Create:
tests/tap/t/027_remote_commit_ts_recovery.plStep 3.1: Create the test file
Write tests/tap/t/027_remote_commit_ts_recovery.pl with the following content:
Make it executable:
- Step 3.2: Run the test — confirm it fails as expected
Expected: the test FAILS at the “post-crash remote_commit_ts is NOT NULL” assertion. Without the recovery scan, the field remains NULL after crash (current behavior).
- Step 3.3: Commit
Task 4: Implement the scan and wire the call site
Files:
Modify:
src/spock_apply.c— addrecover_progress_timestamps_from_commit_tsfunction and call it fromspock_apply_main. Add INFO logs.Step 4.1: Add the forward declaration
Near the existing forward declarations (src/spock_apply.c:248-260, the same block where Task 1 added ReconcileResult), add:
- Step 4.2: Add the include for
commit_ts.h
Near the top of src/spock_apply.c (in the #include block), add:
- Step 4.3: Implement the scan function
Add the function after reconcile_progress_with_origin (i.e., after the existing block ending at src/spock_apply.c:3043):
- Step 4.4: Wire the call site in
spock_apply_main
At src/spock_apply.c:4216 (where Task 1 introduced reconcile_result), replace:
with:
Note on target_origin: replorigin_session_origin is the standard Postgres global, set by replorigin_session_setup(originid) at src/spock_apply.c:4212, two lines before the reconcile call. It is the correct RepOriginId to filter by.
- Step 4.5: Build and run test 027
Expected: all subtests pass. The “post-crash remote_commit_ts is NOT NULL” assertion now succeeds.
- Step 4.6: Run the existing crash-recovery regression to ensure no regression
Expected: both pass. Note that 022’s assertion is($post_commit_ts, '', "remote_commit_ts is NULL post-crash...") is now WRONG — recovery populates it. You must update 022 in this same task.
- Step 4.7: Update test 022 to reflect new behavior
In tests/tap/t/022_rmgr_progress_post_checkpoint_crash.pl at the assertion block (around line 191-197), change:
to:
Also update the file header comment block where it says remote_commit_ts is NULL post-crash to reflect the recovery behavior.
- Step 4.8: Re-run 022 to confirm the update
Expected: all subtests pass.
- Step 4.9: Commit
Task 5: Write the failing track_commit_timestamp off test (030)
Files:
Create:
tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.plStep 5.1: Create the test
Write tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl:
Note: the log path may need adjusting based on how SpockTest configures log_directory / log_filename. Inspect tests/tap/SpockTest.pm if $sub_dir/log/postgresql-1.log doesn’t match. The pattern matching for the error message is tolerant (case-insensitive, just looks for “track_commit_timestamp” near “on”).
- Step 5.2: Run the test — confirm it fails as expected
Expected: the test FAILS at the “logged ERROR about track_commit_timestamp” check, because Task 4 has no guard. Without the guard, the recovery scan calls TransactionIdGetCommitTsData which returns false for every xid (no commit_ts data) and the scan logs “no commits found” instead of erroring.
- Step 5.3: Commit
Task 6: Add the track_commit_timestamp guard
Files:
Modify:
src/spock_apply.c— add the guard at the top ofrecover_progress_timestamps_from_commit_ts.Step 6.1: Add the guard
At the top of recover_progress_timestamps_from_commit_ts (added in Task 4.3), insert immediately after the variable declarations:
The variable track_commit_timestamps (note plural) is the standard Postgres GUC global, declared in access/commit_ts.h (already included in Task 4.2).
- Step 6.2: Build
Expected: clean build.
- Step 6.3: Run test 030 — should now pass
Expected: all subtests pass.
- Step 6.4: Run test 027 to confirm no regression
Expected: all subtests pass.
- Step 6.5: Commit
Task 7: Add the clean-shutdown skip-path test (029)
Files:
Create:
tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.plStep 7.1: Create the test
Write tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl:
- Step 7.2: Run the test
Expected: all subtests pass. The skip-path INFO log was added in Task 4 and the recovery function is gated on RECONCILE_FILE_IN_SYNC — both already in place by this point.
- Step 7.3: Commit
Task 8: Final regression sweep
- Step 8.1: Run the full TAP suite
Expected: all tests pass, including 008, 022, 023, 026, and the three new tests (027, 029, 030).
- Step 8.2: Verify the commit log
Expected: a clean linear sequence — refactor, constants, test 027 (failing), implement, test 030 (failing), guard, test 029.
- Step 8.3: No commit needed; the work is complete.
If this lands as a PR, the user will decide whether to fold the design doc into the PR (currently uncommitted in the working tree).
Self-Review
- Spec coverage: every section of the spec maps to a task: enum and skip-gating (Task 1, 4), constants (Task 2), scan logic (Task 4),
track_commit_timestampguard (Task 6), INFO logs (Task 4, 7), tests 027/029/030 (Tasks 3, 7, 5). Test 028 (idle/empty cluster) is deferred per the spec’s discussion that triggering “no commits found” in a TAP test requires either a constant override or 1M+ unrelated xids — both are too heavy for v1. - Type consistency:
ReconcileResultenum (Task 1) is used in Task 4’s call site.target_originisRepOriginId.running_max_tsisTimestampTz. Constants areint64-safe via the(int64) total_scannedcast. - Placeholder scan: every step has executable code or commands. The only soft spot is the log-path detection in tests 029 and 030 — handled with a comment instructing the implementer to inspect
SpockTest.pmif the default path doesn’t match.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16.3 - Design decisions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Explanations of why things are done the way they are.
Why does spock_output exist when there’s wal2json etc?
spock_output does plenty more than convert logical decoding change
messages to a wire format and send them to the client.
It handles format negotiations, sender-side filtering using pluggable hooks (and the associated plugin handling), etc. The protocol itself is also important, and incorporates elements like binary datum transfer that can’t be easily or efficiently achieved with json.
Custom binary protocol
Why do we have a custom binary protocol inside the walsender / copy both protocol, rather than using a json message representation?
Speed and compactness. It’s expensive to create json, with lots of allocations. It’s expensive to decode it too. You can’t represent raw binary in json, and must encode it, which adds considerable overhead for some data types. Using the obvious, easy to decode json representations also makes it difficult to do later enhancements planned for the protocol and decoder, like caching row metadata.
The protocol implementation is fairly well encapsulated, so in future it should be possible to emit json instead for clients that request it. Right now that’s not the priority as tools like wal2json already exist for that.
Column metadata
The output plugin sends metadata for columns - at minimum, the column names - before each row that first refers to that relation.
The reason metadata must be sent is that the upstream and downstream table’s attnos don’t necessarily correspond. The column names might, and their ordering might even be the same, but any column drop or column type change will result in a dropped column on one side. So at the user level the tables look the same, but their attnos don’t match, and if we rely on attno for replication we’ll get the wrong data in the wrong columns. Not pretty.
That could be avoided by requiring that the downstream table be strictly maintained by DDL replication, but:
- We don’t want to require DDL replication
- That won’t work with multiple upstreams feeding into a table
- The initial table creation still won’t be correct if the table has dropped
columns, unless we (ab)use
pg_dump’s--binary-upgradesupport to emit tables with dropped columns, which we don’t want to do.
So despite the bandwidth cost, we need to send metadata.
Support for type metadata is penciled in to the protocol so that clients that don’t have table definitions at all - like queueing engines - can decode the data. That’ll also permit type validation sanity checking on the apply side with logical replication.
The upstream expects the client to cache this metadata and re-use it when data is sent for the relation again. Cache size controls, an LRU and purge notifications will be added later; for now the client must cache everything indefinitely.
Relation metadata cache size controls
The relation metadata cache will have downstream size control added. The downstream will send a parameter indicating that it supports caching, and the maximum cache size desired.
Since there is no downstream-to-upstream communication after the startup params there’s no easy way for the downstream to tell the upstream when it purges cache entries. So the downstream cache is a slave cache that must depend strictly on the upstream cache. The downstream tells the upstream how to manage its cache and then after that it just follows orders.
To keep the caches in sync so the upstream never sends a row without knowing the downstream has metadata for it cached the downstream must always cache relation metadata when it receives it, and may not purge it from its cache until it receives a purge message for that relation from the upstream. If a new metadata message for the same relation arrives it must replace the old entry in the cache.
The downstream does not have to promptly purge or invalidate cache entries when it gets purge messages from the upstream. They are just notifications that the upstream no longer expects the downstream to retain that cache entry and will re-send it if it is required again later.
Not an extension
There’s no extension script for spock_output. That’s by design. We’ve tried really hard to avoid needing one, allowing applications using spock_output to entirely define any SQL level catalogs they need and interact with them using the hooks.
That way applications don’t have to deal with some of their catalog data being in spock_output extension catalogs and some being in their own.
There’s no issue with dump and restore that way either. The app controls it entirely and spock_output doesn’t need any policy or tools for it.
spock_output is meant to be a re-usable component of other solutions. Users shouldn’t need to care about it directly.
Hooks
Quite a bit of functionality that could be done directly in the output plugin is instead delegated to pluggable hooks. Replication origin filtering for example.
That’s because spock_output tries hard not to know anything about the topology of the replication cluster and leaves that to applications using the plugin.
Hook entry point as a SQL function
The hooks entry point is a SQL function that populates a passed internal
struct with hook function pointers.
The reason for this is that hooks are specified by a remote peer over the network. We can’t just let the peer say “dlsym() this arbitrary function name and call it with these arguments” for fairly obvious security reasons. At bare minimum all replication using hooks would have to be superuser-only if we did that.
The SQL entry point is only called once per decoding session and the rest of the calls are plain C function pointers.
The startup reply message
The protocol design choices available to spock are constrained by being
contained in the copy-both protocol within the fe/be protocol, running as a
logical decoding plugin. The plugin has no direct access to the network socket
and can’t send or receive messages whenever it wants, only under the control of
the walsender and logical decoding framework.
The only opportunity for the client to send data directly to the logical
decoding plugin is in the START_REPLICATION parameters, and it can’t send
anything to the client before that point.
This means there’s no opportunity for a multi-way step negotiation between client and server. We have to do all the negotiation we’re going to in a single exchange of messages - the setup parameters and then the replication start message. All the client can do if it doesn’t like the offer the server makes is disconnect and try again with different parameters.
That’s what the startup message is for. It reports the plugin’s capabilities and tells the client which requested options were honoured. This gives the client a chance to decide if it’s happy with the output plugin’s decision or if it wants to reconnect and try again with different options. Iterative negotiation, effectively.
Unrecognised parameters MUST be ignored by client and server
To ensure upward and downward compatibility, the output plugin must ignore parameters set by the client if it doesn’t recognise them, and the client must ignore parameters it doesn’t recognise in the server’s startup reply message.
This ensures that older clients can talk to newer servers and vice versa.
For this to work, the server must never enable new functionality such as protocol message types, row formats, etc without the client explicitly specifying via a startup parameter that it understands the new functionality. Everything must be negotiated.
Similarly, a newer client talking to an older server may ask the server to enable functionality, but it can’t assume the server will actually honour that request. It must check the server’s startup reply message to see if the server confirmed that it enabled the requested functionality. It might choose to disconnect and report an error to the user if the server didn’t do what it asked. This can be important, e.g. when a security-significant hook is specified.
Support for transaction streaming
Presently logical decoding requires that a transaction has committed before it can begin sending it to the client. This means long running xacts can take 2x as long, since we can’t start apply on the replica until the xact is committed on the master.
Additionally, a big xact will cause large delays in apply of smaller transactions because logical decoding reorders transactions into strict commit order and replays them in that sequence. Small transactions that committed after the big transaction cannot be replayed to the replica until the big transaction is transferred over the wire, and we can’t get a head start on that while it’s still running.
Finally, the accumulation of a big transaction in the reorder buffer means that storage on the upstream must be sufficient to hold the entire transaction until it can be streamed to the replica and discarded. That is in addition to the copy in retained WAL, which cannot be purged until replay is confirmed past commit for that xact. The temporary copy serves no data safety purpose; it can be regenerated from retained WAL is just a spool file.
There are big upsides to waiting until commit. Rolled-back transactions and subtransactions are never sent at all. The apply/downstream side is greatly simplified by not needing to do transaction ordering, worry about interdependencies and conflicts during apply. The commit timestamp is known from the beginning of replay, allowing for smarter conflict resolution behaviour in multi-master scenarios. Nonetheless sometimes we want to be able to stream changes in advance of commit.
So we need the ability to start streaming a transaction from the upstream as its changes are seen in WAL, either applying it immediately on the downstream or spooling it on the downstream until it’s committed. This requires changes to the logical decoding facilities themselves, it isn’t something spock_output can do alone. However, we’ve left room in spock_output to support this when support is added to logical decoding:
Flags in most message types let us add fields if we need to, like a HAS_XID flag and an extra field for the transaction ID so we can differentiate between concurrent transactions when streaming. The space isn’t wasted the rest of the time.
The upstream isn’t allowed to send new message types, etc, without a capability flag being set by the client. So for interleaved xacts we won’t enable them in logical decoding unless the client tells us the client is prepared to cope with them by sending additional startup parameters.
Note that for consistency reasons we still have to commit things in the same order on the downstream. The purpose of transaction streaming is to reduce the latency between the commit of the last xact before a big one and the first xact after the big one, minimising the duration of the stall in the flow of smaller xacts perceptible on the downstream.
Transaction streaming also makes parallel apply on the downstream possible, though it is not necessary to have parallel apply to benefit from transaction streaming. Parallel apply has further complexities that are outside the scope of the output plugin design.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16.4 - spock Output Plugin
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This is the logical decoding
output plugin
for spock. Its purpose is to extract a change stream from a PostgreSQL
database and send it to a client over a network connection using a
well-defined, efficient protocol that multiple different applications can
consume.
The primary purpose of spock_output is to supply data to logical
streaming replication solutions, but any application can potentially use its
data stream. The output stream is designed to be compact and fast to decode,
and the plugin supports upstream filtering of data (through hooks) so that only
the required information is sent.
Only one database is replicated, rather than the whole PostgreSQL install. A subset of that database may be selected for replication, currently based on table and on replication origin. Filtering by a WHERE clause can be supported easily in future.
No triggers are required to collect the change stream and no external ticker or other daemon is required. The stream of changes is accumulated using replication slots, as supported in PostgreSQL 9.4 or newer, and sent on top of the PostgreSQL streaming replication protocol.
Unlike block-level (“physical”) streaming replication, the change stream from
spock_output is compatible across different PostgreSQL
versions and can even be consumed by non-PostgreSQL clients.
Because logical decoding is used, only the changed rows are sent on the wire. There’s no index change data, no vacuum activity, etc transmitted.
The use of a replication slot means that the change stream is reliable and crash-safe. If the client disconnects or crashes it can reconnect and resume replay from the last message that client processed. Server-side changes that occur while the client is disconnected are accumulated in the queue to be sent when the client reconnects. This reliability also means that server-side resources are consumed whether or not a client is connected.
Why another output plugin?
See DESIGN.md for a discussion of why using one of the existing
generic logical decoding output plugins like wal2json to drive a logical
replication downstream isn’t ideal. It’s mostly about speed.
Architecture and high level interaction
The output plugin is loaded by a PostgreSQL walsender process when a client
connects to PostgreSQL using the PostgreSQL wire protocol with connection
option replication=database, then uses
the CREATE_REPLICATION_SLOT ... LOGICAL ... or START_REPLICATION SLOT ... LOGICAL ... commands to start streaming changes. (It can also be used via
SQL level functions
over a non-replication connection, but this is mainly for debugging purposes).
The client supplies parameters to the START_REPLICATION SLOT ... LOGICAL ...
command to specify the version of the spock protocol it supports,
whether it wants binary format, etc.
The output plugin processes the connection parameters and the connection enters
streaming replication protocol mode, sometimes called “COPY BOTH” mode because
it’s based on the protocol used for the COPY command. PostgreSQL then calls
functions in this plugin to send it a stream of transactions to decode and
translate into network messages. This stream of changes continues until the
client disconnects.
The only client-to-server interaction after startup is the sending of periodic
feedback messages that allow the replication slot to discard no-longer-needed
change history. The client must send feedback, otherwise pg_xlog on the
server will eventually fill up and the server will stop working.
Usage
The overall flow of client/server interaction is:
- Client makes PostgreSQL fe/be protocol connection to server
- Connection options must include
replication=databaseanddbname=[...]parameters - The PostgreSQL client library can be
libpqor anything else that supports the replication sub-protocol - The same mechanisms are used for authentication and protocol encryption as for a normal non-replication connection
- Connection options must include
- Client issues
IDENTIFY_SYSTEM- Server responds with a single row containing system identity info
- Client issues
CREATE_REPLICATION_SLOT slotname LOGICAL 'spock'if it’s setting up for the first time- Server responds with success info and a snapshot identifier
- Client may at this point use the snapshot identifier on other connections while leaving this one idle
- Client issues
START_REPLICATION SLOT slotname LOGICAL 0/0 (...options...)to start streaming, which loops:- Server emits
spockmessage block encapsulated in a replication protocolCopyDatamessage - Client receives and unwraps message, then decodes the
spockmessage block - Client intermittently sends a standby status update message to server to confirm replay
- Server emits
- … until client sends a graceful connection termination message on the fe/be protocol level or the connection is broken
The details of IDENTIFY_SYSTEM, CREATE_REPLICATION_SLOT and START_REPLICATION are discussed in the replication protocol docs and will not be repeated here.
Make a replication connection
To use the spock plugin you must first establish a PostgreSQL FE/BE
protocol connection using the client library of your choice, passing
replication=database as one of the connection parameters. database is a
literal string and is not replaced with the database name; instead the database
name is passed separately in the usual dbname parameter. Note that
replication is not a GUC (configuration parameter) and may not be passed in
the options parameter on the connection, it’s a top-level parameter like
user or dbname.
Example connection string for libpq:
'user=postgres replication=database sslmode=verify-full dbname=mydb'
The plug-in name to pass on logical slot creation is 'spock'.
Details are in the replication protocol docs.
Get system identity
If required you can use the IDENTIFY_SYSTEM command, which reports system
information:
systemid | timeline | xlogpos | dbname | dboid
---------------------+----------+-----------+--------+-------
6153224364663410513 | 1 | 0/C429C48 | testd | 16385
(1 row)
Details are in the replication protocol docs.
Create the slot if required
If your application creates its own slots on first use and hasn’t previously connected to this database on this system you’ll need to create a replication slot. This keeps track of the client’s replay state even while it’s disconnected.
The slot name may be anything your application wants up to a limit of 63 characters in length. It’s strongly advised that the slot name clearly identify the application and the host it runs on.
Pass spock as the plugin name.
e.g.
CREATE_REPLICATION_SLOT "reporting_host_42" LOGICAL "spock";
CREATE_REPLICATION_SLOT returns a snapshot identifier that may be used with
SET TRANSACTION SNAPSHOT
to see the database’s state as of the moment of the slot’s creation. The first
change streamed from the slot will be the change immediately after this
snapshot was taken. The snapshot is useful when cloning the initial state of a
database being replicated. Applications that want to see the change stream
going forward, but don’t care about the initial state, can ignore this. The
snapshot is only valid as long as the connection that issued the
CREATE_REPLICATION_SLOT remains open and has not run another command.
Send replication parameters
The client now sends:
START_REPLICATION SLOT "the_slot_name" LOGICAL (
'Expected_encoding', 'UTF8',
'Max_proto_major_version', '1',
'Min_proto_major_version', '1',
...moreparams...
);
to start replication.
The parameters are very important for ensuring that the plugin accepts
the replication request and streams changes in the expected form. spock
parameters are discussed in the separate spock protocol documentation.
Process the startup message
spock_output will send a CopyData message containing its
startup message as the first protocol message. This message contains a
set of key/value entries describing the capabilities of the upstream output
plugin, its version and the Pg version, the tuple format options selected,
etc.
The downstream client may choose to cleanly close the connection and disconnect at this point if it doesn’t like the reply. It might then inform the user or reconnect with different parameters based on what it learned from the first connection’s startup message.
Consume the change stream
spock_output now sends a continuous series of CopyData
protocol messages, each of which encapsulates a spock protocol message
as documented in the separate protocol docs.
These messages provide information about transaction boundaries, changed rows, etc.
The stream continues until the client disconnects, the upstream server is restarted, the upstream walsender is terminated by admin action, there’s a network issue, or the connection is otherwise broken.
The client should send periodic feedback messages to the server to acknowledge that it’s replayed to a given point and let the server release the resources it’s holding in case that change stream has to be replayed again. See “Hot standby feedback message” in the replication protocol docs for details.
Disconnect gracefully
Disconnection works just like any normal client; you use your client library’s usual method for closing the connection. No special action is required before disconnection, though it’s usually a good idea to send a final standby status message just before you disconnect.
Tests
There are two sets of tests bundled with spock_output: the pg_regress
regression tests and some custom Python tests for the protocol.
The pg_regress tests check invalid parameter handling and basic
functionality. They’re intended for use by the buildfarm using an in-tree
make check, but may also be run with an out-of-tree PGXS build against an
existing PostgreSQL install using make clean installcheck.
The Python tests are more comprehensive, and examine the data sent by
the extension at the protocol level, validating the protocol structure,
order and contents. They can run using the SQL-level logical decoding
interface or, with a psycopg2 containing https://github.com/psycopg/psycopg2/pull/322,
with the walsender / streaming replication protocol. The Python-based tests
exercise the internal binary format support, too. See test/README.md for
details.
The tests may fail on installations that are not utf-8 encoded because the payloads of the binary protocol output will have text in different encodings, which aren’t visible to psql as text to be decoded. Avoiding anything except 7-bit ascii in the tests should prevent the problem.
Changeset forwarding
It’s possible to use spock_output to cascade replication between multiple
PostgreSQL servers, in combination with an appropriate client to apply the
changes to the downstreams.
There are two forwarding modes:
Forward everything. Transactions are replicated whether they were made directly on the immediate upstream or some other node upstream of it. This is the only option when running on 9.4. All rows from transactions are sent.
Selected by not setting a row or transaction filter hook.
Filtered forwarding. Transactions are replicated unless a client-supplied transaction filter hook says to skip this transaction. Row changes are replicated unless the client-supplied row filter hook (if provided) says to skip that row.
Selected by installing a transaction and/or row filter hook (see “hooks”).
The server will enable changeset origin
information. It will set forward_changeset_origins to true in the startup
reply message to indicate this. It will then send changeset origin messages
after the BEGIN for each transaction, per the protocol documentation. Origin
messages are omitted for transactions originating directly on the immediate
upstream to save bandwidth. If forward_changeset_origins is true then
transactions without an origin are always from the immediate upstream that’s
running the decoding plugin.
Clients may use this facility to form arbitrarily complex topologies when combined with hooks to determine which transactions are forwarded. An obvious case is bi-directional (mutual) replication.
Selective replication
By specifying a row filter hook it’s possible to filter the replication stream server-side so that only a subset of changes is replicated.
Hooks
spock_output exposes a number of extension points where applications can
modify or override its behaviour.
All hooks are called in a memory context that lasts for the duration of the logical decoding session. They may switch to longer lived contexts if needed, but are then responsible for their own cleanup.
Hook setup function
The downstream must specify the fully-qualified name of a SQL-callable function
on the server as the value of the hooks.setup_function client parameter.
The SQL signature of this function is
CREATE OR REPLACE FUNCTION funcname(hooks internal, memory_context internal)
RETURNS void STABLE
LANGUAGE c AS 'MODULE_PATHNAME';
Permissions are checked. This function must be callable by the user that the output plugin is running as. The function name must be schema-qualified and is parsed like any other qualified identifier.
The function receives a pointer to a newly allocated structure of hook function pointers to populate as its first argument. The function must not free the argument.
If the hooks need a private data area to store information across calls, the
setup function should get the MemoryContext pointer from the 2nd argument,
then MemoryContextAlloc a struct for the data in that memory context and
store the pointer to it in hooks->hooks_private_data. This will then be
accessible on future calls to hook functions. It need not be manually freed, as
the memory context used for logical decoding will free it when it’s freed.
Don’t put anything in it that needs manual cleanup.
Hooks other than the hook setup function and the startup hook are called in a short-lived memory context. If they want to preserve anything they allocate after the hook returns they must switch to the memory context that was passed to the setup function and allocate it there.
Each hook has its own C signature (defined below) and the pointers must be directly to the functions. Hooks that the client does not wish to set must be left null.
An example is provided in examples/hooks and the argument structs are defined
in spock_output/hooks.h, which is installed into the PostgreSQL source
tree when the extension is installed.
Each hook that is enabled results in a new startup parameter being emitted in the startup reply message. Clients must check for these and must not assume a hook was successfully activated because no error is seen.
Hook functions are called in the context of the backend doing logical decoding.
Except for the startup hook, hooks see the catalog state as it was at the time
the transaction or row change being examined was made. Access to non-catalog
tables is unsafe unless they have the user_catalog_table reloption set. Among
other things this means that it’s not safe to invoke arbitrary functions,
user-defined procedures, etc, from hooks.
Startup hook
The startup hook is called when logical decoding starts.
This hook can inspect the parameters passed by the client to the output plugin as in_params. These parameters must not be modified.
It can add new parameters to the set to be returned to the client in the
startup parameters message, by appending to List out_params, which is
initially NIL. Each element must be a DefElem with the param name
as the defname and a String value as the arg, as created with
makeDefElem(...). It and its contents must be allocated in the
logical decoding memory context.
For walsender based decoding the startup hook is called only once, and cleanup might not be called at the end of the session.
Multiple decoding sessions, and thus multiple startup hook calls, may happen in a session if the SQL interface for logical decoding is being used. In that case it’s guaranteed that the cleanup hook will be called between each startup.
When successfully enabled, the output parameter hooks.startup_hook_enabled is
set to true in the startup reply message.
Unlike the other hooks, this hook sees a snapshot of the database’s current state, not a time-traveled catalog state. It is safe to access all tables from this hook.
Also unlike other hooks, the startup hook is called in a memory context with the same lifetime of the decoding session. It’s called in the same context as the one that’s passed to the hook setup hook.
Transaction filter hook
The transaction filter hook can exclude entire transactions from being decoded and replicated based on the node they originated from.
It is passed a const TxFilterHookArgs * containing:
- The hook argument supplied by the client, if any
- The
RepOriginIdthat this transaction originated from
and must return boolean, where true retains the transaction for sending to the client and false discards it. (Note that this is the reverse sense of the low level logical decoding transaction filter hook).
The hook function must not free the argument struct or modify its contents.
The transaction filter hook is only called on PostgreSQL 9.5 and above. It is ignored on 9.4.
Note that individual changes within a transaction may have different origins to the transaction as a whole; see “Origin filtering” for more details. If a transaction is filtered out, all changes are filtered out even if their origins differ from that of the transaction as a whole.
When successfully enabled, the output parameter
hooks.transaction_filter_enabled is set to true in the startup reply message.
Memory allocated in this hook is freed at the end of the call.
Row filter hook
The row filter hook is called for each row. It is passed information about the table, the transaction origin, and the row origin.
It is passed a const RowFilterHookArgs* containing:
- The hook argument supplied by the client, if any
- The
Relationthe change affects - The change type - ‘I’nsert, ‘U’pdate or ‘D’elete
It can return true to retain this row change, sending it to the client, or false to discard it.
The function must not free the argument struct or modify its contents.
Note that it is more efficient to exclude whole transactions with the transaction filter hook rather than filtering out individual rows.
When successfully enabled, the output parameter
hooks.row_filter_enabled is set to true in the startup reply message.
Memory allocated in this hook is freed at the end of the call.
Shutdown hook
The shutdown hook is called when a decoding session ends. You can’t rely on this hook being invoked reliably, since a replication-protocol walsender-based session might just terminate. It’s mostly useful for cleanup to handle repeated invocations under the SQL interface to logical decoding.
You don’t need a hook to free memory you allocated, unless you explicitly
switched to a longer lived memory context like TopMemoryContext. Memory
allocated in the hook context will be automatically freed when the decoding
session shuts down.
Limitations
The advantages of logical decoding in general and spock_output in
particular are discussed above. There are also some limitations that apply to
spock_output, and to Pg’s logical decoding in general.
Notably:
Mostly one-way communication
Per the protocol documentation, the downstream can’t send anything except replay progress messages to the upstream after replication begins, and can’t re-initialise replication without a disconnect.
To achieve downstream-to-upstream communication, clients can use a regular libpq connection to the upstream then write to tables or call functions. Alternately, a separate replication connection in the opposite direction can be created by the application to carry information from downstream to upstream.
See “Protocol flow” in the protocol documentation for more information.
Doesn’t replicate global objects/shared catalog changes
PostgreSQL has a number of object types that exist across all databases, stored in shared catalogs. These include:
- Roles (users/groups)
- Security labels on users and databases
Such objects cannot be replicated by spock_output. They’re managed with DDL that
can’t be captured within a single database and isn’t decoded anyway.
Global object changes must be synchronized via some external means.
Physical replica failover
Logical decoding cannot follow a physical replication failover because replication slot state is not replicated to physical replicas. If you fail over to a streaming replica you have to manually reconnect your logical replication clients, creating new slots, etc. This is a core PostgreSQL limitation.
Also, there’s no built-in way to guarantee that the logical replication slot from the failed master hasn’t replayed further than the physical streaming replica you failed over to. You could receive changes on your logical decoding stream from the old master that never made it to the physical streaming replica. This is true (albeit very unlikely) even if the physical streaming replica is synchronous because PostgreSQL sends the replication data anyway, then just delays the commit’s visibility on the master. Support for strictly ordered standbys would be required in PostgreSQL to avoid this.
To achieve failover with logical replication you cannot mix in physical standbys. The logical replication client has to take responsibility for maintaining slots on logical replicas intended as failover candidates and for ensuring that the furthest-ahead replica is promoted if there is more than one.
Can only replicate complete transactions
Logical decoding can only replicate a transaction after it has committed. This usefully skips replication of rolled back transactions, but it also means that very large transactions must be completed upstream before they can begin on the downstream, adding to replication latency.
Replicates only one transaction at a time
Logical decoding serializes transactions in commit order, so spock_output cannot replay interleaved concurrent transactions. This can lead to high latencies when big transactions are being replayed, since smaller transactions get queued up behind them.
Unique index required for inserts or updates
To replicate INSERTs or UPDATEs it is necessary to have a PRIMARY KEY
or a (non-partial, columns-only) UNIQUE index on the table, so the table
has a REPLICA IDENTITY. Without that spock_output doesn’t know what
old key to send to allow the receiver to tell which tuple is being updated.
UNLOGGED tables aren’t replicated
Because UNLOGGED tables aren’t written to WAL, they aren’t replicated by
logical or physical replication. You can only replicate UNLOGGED tables
with trigger-based solutions.
Unchanged fields are often sent in UPDATE
Because there’s no tracking of dirty/clean fields when a tuple is updated, logical decoding can’t tell if a given field was changed by an update. Unchanged fields can only by identified and omitted if they’re a variable length TOASTable type and are big enough to get stored out-of-line in a TOAST table.
Troubleshooting and debugging
Non-destructively previewing pending data on a slot
Using the json mode of spock_output you can examine pending transactions
on a slot without consuming them, so they are still delivered to the usual
client application that created/owns this slot. This is best done using the SQL
interface to logical decoding, since it gives you finer control than using
pg_recvlogical.
You can only peek at a slot while there is no other client connected to that slot.
Use spock_slot_peek_changes to examine the change stream without
destructively consuming changes. This is extremely helpful when trying to
determine why an error occurs in a downstream, since you can examine a
transaction in json (rather than binary) format. It’s necessary to supply a
minimal set of required parameters to the output plugin.
e.g. given setup:
CREATE TABLE discard_test(blah text);
SELECT 'init' FROM pg_create_logical_replication_slot('demo_slot', 'spock_output');
INSERT INTO discard_test(blah) VALUES('one');
INSERT INTO discard_test(blah) VALUES('two1'),('two2'),('two3');
INSERT INTO discard_test(blah) VALUES('three1'),('three2');
you can peek at the change stream with:
SELECT location, xid, data
FROM spock_slot_peek_changes('demo_slot', NULL, NULL,
'min_proto_version', '1', 'max_proto_version', '1',
'startup_params_format', '1', 'proto_format', 'json');
The two NULLs mean you don’t want to stop decoding after any particular
LSN or any particular number of changes. Decoding will stop when there’s nothing
left to decode or you cancel the query.
This will emit a key/value startup message then change data rows like:
location | xid | data
0/4E8AAF0 | 5562 | {"action":"B", has_catalog_changes:"f", xid:"5562", first_lsn:"0/4E8AAF0", commit_time:"2015-11-13 14:26:21.404425+08"}
0/4E8AAF0 | 5562 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"one"}}
0/4E8AB70 | 5562 | {"action":"C", final_lsn:"0/4E8AB30", end_lsn:"0/4E8AB70"}
0/4E8ABA8 | 5563 | {"action":"B", has_catalog_changes:"f", xid:"5563", first_lsn:"0/4E8ABA8", commit_time:"2015-11-13 14:26:32.015611+08"}
0/4E8ABA8 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two1"}}
0/4E8ABE8 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two2"}}
0/4E8AC28 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two3"}}
0/4E8ACA8 | 5563 | {"action":"C", final_lsn:"0/4E8AC68", end_lsn:"0/4E8ACA8"}
....
The output is the LSN (log sequence number) associated with a change, the top level transaction ID that performed the change, and the change data as json.
You can see the transaction boundaries by xid changes and by the “B"egin and “C"ommit messages, and you can see the individual row “I"nserts. Replication origins, commit timestamps, etc will be shown if known.
See http://www.postgresql.org/docs/current/static/functions-admin.html for information on the peek functions.
If you want the binary format you can get that with
spock_slot_peek_binary_changes and the native protocol, but that’s
generally much less useful.
Manually discarding a change from a slot
Sometimes it’s desirable to manually purge one or more changes from a replication slot. This is usually an error recovery step when problems arise with the downstream code that’s replaying from the slot.
You can use the peek functions to determine the point in the stream you want to discard up to, as identified by LSN (log sequence number). See “non-destructively previewing pending data on a slot” above for details.
You can’t control the point you start discarding from, it’s always from the current stream position up to a point you specify. If the peek shows that there’s data you still want to retain you must make sure that the downstream replays up to the point you want to keep changes and sends replay confirmation. In other words there’s no way to cut a sequence of changes out of the middle of the pending change stream.
Once you’ve peeked the stream and know the LSN you want to discard up to, you
can use spock_slot_get_changes, specifying an upto_lsn, to consume
changes from the slot up to but not including that point. That will be the
point at which replay resumes.
For example, if you wanted to discard the first transaction in the example
from the section above, i.e. discard xact 5562 and start decoding at xact
5563 from its’ BEGIN lsn 0/4E8ABA8, you’d run:
SELECT location, xid, data
FROM spock_slot_get_changes('demo_slot', '0/4E8ABA8', NULL,
'min_proto_version', '1', 'max_proto_version', '1',
'startup_params_format', '1', 'proto_format', 'json');
Note that _get_changes is used instead of _peek_changes and that
the upto_lsn is '0/4E8ABA8' instead of NULL.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.16.5 - Spock Protocol
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_output defines a libpq subprotocol for streaming tuples, metadata, etc., from the decoding plugin to receivers.
This protocol is an inner layer in a stack:
- TCP or unix sockets
- libpq protocol
- libpq replication subprotocol (COPY BOTH etc.)
- spock output plugin => consumer protocol
- libpq replication subprotocol (COPY BOTH etc.)
- libpq protocol
so clients can simply use libpq’s existing replication protocol support, directly or via their libpq-wrapper driver.
This is a binary protocol intended for compact representation.
spock_output also supports a json-based text protocol with json
representations of the same changesets, supporting all the same hooks etc.,
intended mainly for tracing/debugging/diagnostics. That protocol is not
discussed here.
Table of Contents
- Protocol Flow
- Protocol Messages
- Startup Message
- Startup Errors
- Arguments Client Supplies to Output Plugin
- Extensibility
- JSON Protocol
Protocol Flow
The protocol flow is primarily from upstream walsender/decoding plugin to the downstream receiver.
The only information that flows downstream-to-upstream is:
- The initial parameter list sent to
START_REPLICATION; and - replay progress messages
We can accept an arbitrary list of params to START_REPLICATION. After
that we have no general-purpose channel for information to flow upstream. That
means we can’t do a multi-step negotiation or handshake for determining the
replication options to use, binary protocol, etc.
The main form of negotiation is the client getting a “take it or leave it” set of settings from the server in an initial startup message sent before any replication data (see below) and, if it doesn’t like them, reconnecting with different startup options.
Except for the negotiation via initial parameter list and then startup message the protocol flow is the same as any other walsender-based logical replication plugin. The data stream is sent in COPY BOTH mode as a series of CopyData messages encapsulating replication data, and ends when the client disconnects. There’s no facility for ending the COPY BOTH mode and returning to the walsender command parser to issue new commands. This is a limitation of the walsender interface, not spock_output.
Protocol Messages
The individual protocol messages are discussed in the following sub-sections. Protocol flow and logic comes in the next major section.
Absolutely all top-level protocol messages begin with a message type byte. While represented in code as a character, this is a signed byte with no associated encoding.
Since the PostgreSQL libpq COPY protocol supplies a message length there’s no need for top-level protocol messages to embed a length in their header.
BEGIN Message
A stream of rows starts with a BEGIN message. Rows may only be sent after a
BEGIN and before a COMMIT.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal B (0x42) |
| flags | uint8 | 0-3: Reserved, client must ERROR if set and not recognised. |
| lsn | uint64 | “final_lsn” in decoding context - currently it means lsn of commit |
| commit time | uint64 | “commit_time” in decoding context |
| remote XID | uint32 | “xid” in decoding context |
Forwarded Transaction Origin Message
The message after the BEGIN may be a forwarded transaction origin message
indicating what upstream node the transaction came from.
Sent if the immediately prior message was a BEGIN message, the upstream
transaction was forwarded from another node, and replication origin forwarding
is enabled, i.e. forward_changeset_origins is t in the startup reply
message.
A “node” could be another host, another DB on the same host, or pretty much
anything. Whatever origin name is found gets forwarded. The origin identifier
is of arbitrary and application-defined format. Applications should prefix
their origin identifier with a fixed application name part, like bdr_,
myapp_, etc. It is application-defined what an application does with
forwarded transactions from other applications.
An origin message with a zero-length origin name indicates that the origin could not be identified but was (probably) not the local node. It is client-defined what action is taken in this case.
It is a protocol error to send/receive a forwarded transaction origin message
at any time other than immediately after a BEGIN message.
The origin identifier is typically closely related to replication slot names and replication origins’ names in an application system.
For more detail see Changeset Forwarding in the README.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal O (0x4f) |
| flags | uint8 | 0-3: Reserved, application must ERROR if set and not recognised |
| origin_lsn | uint64 | LSN (XLogRecPtr) of the transaction’s commit record on its origin node (as opposed to the forwarding node’s commit LSN, which is ’lsn’ in the BEGIN message) |
| origin_identifier_length | uint8 | Length in bytes of origin_identifier |
| origin_identifier | signed char[origin_identifier_length] | An origin identifier of arbitrary, upstream-application-defined structure. Should be text in the same encoding as the upstream database. NULL-terminated. Should be 7-bit ASCII. |
COMMIT Message
A stream of rows ends with a COMMIT message.
There is no ROLLBACK message because aborted transactions are not sent by the
upstream.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal C (0x43) |
| Flags | uint8 | 0-3: Reserved, client must ERROR if set and not recognised |
| Commit LSN | uint64 | commit_lsn in decoding commit decode callback. This is the same value as in the BEGIN message, and marks the end of the transaction. |
| End LSN | uint64 | end_lsn in decoding transaction context |
| Commit time | uint64 | commit_time in decoding transaction context |
INSERT, UPDATE or DELETE Message
After a BEGIN or metadata message, the downstream should expect to receive
zero or more row change messages, composed of an insert/update/delete message
with zero or more tuple fields, each of which has one or more tuple field
values.
The row’s relidentifier must match that of the most recently preceding metadata message. All consecutive row messages must currently have the same relidentifier. (Later extensions to add metadata caching will relax these requirements for clients that advertise caching support; see the documentation on metadata messages for more detail).
It is an error to decode rows using metadata received after the row was received, or using metadata that is not the most recently received metadata revision that still predates the row. I.e. in the sequence M1, R1, R2, M2, R3, M4: R1 and R2 must be decoded using M1, and R3 must be decoded using M2. It is an error to use M4 to decode any of the rows, to use M1 to decode R3, or to use M2 to decode R1 and R2.
Row messages may not arrive except during a transaction as delimited by BEGIN
and COMMIT messages. It is an error to receive a row message outside a
transaction.
Any unrecognised tuple type or tuple part type is an error on the downstream that must result in a client disconnect and error message. Downstreams are expected to negotiate compatibility, and upstreams must not add new tuple types or tuple field types without negotiation.
The downstream reads rows until the next non-row message is received. There is no other end marker or any indication of how many rows to expect in a sequence.
Row Message Header
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal Insert (0x49), Update (0x55) or Delete (0x44) |
| flags | uint8 | Row flags (reserved) |
| relidentifier | uint32 | relidentifier that matches the table metadata message sent for this row. (Not present in BDR, which sends nspname and relname instead) |
| [tuple parts] | [composite] |
One or more tuple-parts fields follow.
Tuple Fields
| Message | Type/Size | Notes |
|---|---|---|
| Tuple type | signed char | Identifies the kind of tuple being sent. |
| tupleformat | signed char | T (0x54) |
| natts | uint16 | Number of fields sent in this tuple part. (Present in BDR, but meaning significantly different here) |
| [tuple field values] | [composite] |
Tuple tupleformat compatibility
Unrecognised tupleformat kinds are a protocol error for the downstream.
Tuple Field Value Fields
These message parts describe individual fields within a tuple.
There are two kinds of tuple value fields, abbreviated and full. Which is being read is determined based on the first field, kind.
Abbreviated tuple value fields are nothing but the message kind:
| Message | Type/Size | Notes |
|---|---|---|
| kind | signed char | null (0x6e) field |
Full tuple value fields have a length and datum:
| Message | Type/Size | Notes |
|---|---|---|
| kind | signed char | internal binary (0x62) field |
| length | int4 | Only defined for kind = i|b|t |
| data | [length] | Data in a format defined by the table metadata and column kind. |
Tuple Field Values Kind Compatibility
Unrecognised field kind values are a protocol error for the downstream. The downstream may not continue processing the protocol stream after this point.
The upstream may not send internal or binary format values to the downstream without the downstream negotiating acceptance of such values. The downstream will also generally negotiate to receive type information to use to decode the values. See the section on startup parameters and the startup message for details.
Table/Row Metadata Messages
Before sending changed rows for a relation, a metadata message for the relation must be sent so the downstream knows the namespace, table name, column names, optional column types, etc. A relidentifier field, an arbitrary numeric value unique for that relation on that upstream connection, maps the metadata to following rows.
A client should not assume that relation metadata will be followed immediately (or at all) by rows, since future changes may lead to metadata messages being delivered at other times. Metadata messages may arrive during or between transactions.
The upstream may not assume that the downstream retains more metadata than the one most recent table metadata message. This applies across all tables, so a client is permitted to discard metadata for table x when getting metadata for table y. The upstream must send a new metadata message before sending rows for a different table, even if that metadata was already sent in the same session or even same transaction. This requirement will later be weakened by the addition of client metadata caching, which will be advertised to the upstream with an output plugin parameter.
Columns in metadata messages are numbered from 0 to natts-1, reading consecutively from start to finish. The column numbers do not have to be a complete description of the columns in the upstream relation, so long as all columns that will later have row values sent are described. The upstream may choose to omit columns it doesn’t expect to send changes for in any given series of rows. Column numbers are not necessarily stable across different sets of metadata for the same table, even if the table hasn’t changed structurally.
A metadata message may not be used to decode rows received before that metadata message.
Table Metadata Header
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal R (0x52) |
| flags | uint8 | 0-6: Reserved, client must ERROR if set and not recognised. |
| relidentifier | uint32 | Arbitrary relation id, unique for this upstream. In practice this will probably be the upstream table’s oid, but the downstream can’t assume anything. |
| nspnamelength | uint8 | Length of namespace name (incl. terminating \0) |
| nspname | signed char[nspnamelength] | Relation namespace (null terminated) |
| relnamelength | uint8 | Length of relation name (incl. terminating \0) |
| relname | char[relname] | Relation name (null terminated) |
| attrs block | signed char | Literal: A (0x41) |
| natts | uint16 | Number of attributes |
| [fields] | [composite] | Sequence of ’natts’ column metadata blocks, each of which begins with a column delimiter followed by zero or more column metadata blocks, each with the same column metadata block header. This chunked format is used so that new metadata messages can be added without breaking existing clients. |
Column Delimiter
Each column’s metadata begins with a column metadata header. This comes immediately after the natts field in the table metadata header or after the last metadata block in the prior column.
It has the same char header as all the others, and the flags field is the same size as the length field in other blocks, so it’s safe to read this as a column metadata block header.
Currently, the only defined flag is 0x1 indicating that the column is part of the relation’s identity key.
| Message | Type/Size | Notes |
|---|---|---|
| blocktype | signed char | C (0x43) - column |
| flags | uint8 | Column info flags |
Column Metadata Block Header
All column metadata blocks share the same header, which is the same length as a column delimiter:
| Message | Type/Size | Notes |
|---|---|---|
| blocktype | signed char | Identifies the kind of metadata block that follows. |
| blockbodylength | uint16 | Length of block in bytes, excluding blocktype char and length field. |
Column Name Block
This block just carries the name of the column, nothing more. It begins with a column metadata block, and the rest of the message is the column name.
| Message | Type/Size | Notes |
|---|---|---|
| [column metadata block header] | [composite] | blocktype = N (0x4e) |
| colname | char[blockbodylength] | Column name. |
Column Type Block
T.B.D.
Not defined in first protocol revision.
Likely to send a type identifier (probably the upstream oid) as a reference to a “type info” protocol message to be delivered before. Then we can cache the type descriptions and avoid repeating long schemas and names, just using the oids.
Needs to have room to handle:
- built-in core types
- extension types (ext version may vary)
- enum types (CREATE TYPE … AS ENUM)
- range types (CREATE TYPE … AS RANGE)
- composite types (CREATE TYPE … AS (…))
- custom types (CREATE TYPE ( input = x_in, output = x_out ))
… some of which can be nested
Startup Message
After processing output plugin arguments, the upstream output plugin must send a startup message as its first message on the wire. It is a trivial header followed by alternating key and value strings represented as null-terminated unsigned char strings.
This message specifies the capabilities the output plugin enabled and describes the upstream server and plugin. This may change how the client decodes the data stream, and/or permit the client to disconnect and report an error to the user if the result isn’t acceptable.
If replication is rejected because the client is incompatible or the server is unable to satisfy required options, the startup message may be followed by a libpq protocol FATAL message that terminates the session. See Startup Errors below.
The parameter names and values are sent as alternating key/value pairs as null-terminated strings, e.g.
key1\0parameter1\0key2\0value2\0
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | S (0x53) - startup |
| Startup message version | uint8 | Value is always “1”. |
| (parameters) | null-terminated key/value pairs | See table below for parameter definitions. |
Startup Message Parameters
Since all parameter values are sent as strings, the value types given below specify what the value must be reasonably interpretable as.
| Key name | Value type | Description |
|---|---|---|
| max_proto_version | integer | Newest version of the protocol supported by output plugin. Currently 5. |
| min_proto_version | integer | Oldest protocol version supported by server. Currently 4. |
| proto_version | integer | The negotiated protocol version selected by the server based on the overlap between client and server ranges. |
| coltypes | boolean | Column types will be sent in table metadata. Currently always false. |
| pg_version_num | integer | PostgreSQL server_version_num of server, if it’s PostgreSQL. e.g. 180000 |
| pg_version | string | PostgreSQL server_version of server, if it’s PostgreSQL. e.g. “18.0” |
| pg_catversion | uint32 | Version of the PostgreSQL system catalogs on the upstream server, if it’s PostgreSQL. |
| database_encoding | string | The native text encoding of the database the plugin is running in. |
| encoding | string | Field values for textual data will be in this encoding in native protocol text, binary or internal representation. For the native protocol this is currently always the same as database_encoding. For text-mode json protocol this is always the same as client_encoding. |
| forward_changeset_origins | bool | Tells the client that the server will send changeset origin information. See Changeset forwarding for details. |
| walsender_pid | integer | PID of the walsender process on the upstream server. |
| spock_version | string | Spock version string of the upstream server. e.g. “4.0.11” |
| spock_version_num | integer | Spock numeric version of the upstream server. e.g. 40011 |
| no_txinfo | bool | Echo of the client’s no_txinfo setting. When true, variable transaction info such as XIDs, LSNs, and timestamps are omitted from output. Mainly for tests. Currently ignored for protos other than json. |
Startup Message ‘binary’ Parameters
| Key name | Value type | Description |
|---|---|---|
| binary.internal_basetypes | boolean | If true, PostgreSQL internal binary representations for row field data may be used for some or all row fields, where the type is appropriate and the binary compatibility parameters of upstream and downstream match. See binary.want_internal_basetypes in the output plugin parameters for details. May only be true if binary.want_internal_basetypes was set to true by the client in the parameters and the client’s accepted binary format matches that of the server. |
| binary.binary_basetypes | boolean | If true, external binary format (send/recv format) may be used for some or all row field data where the field type is a built-in base type whose send/recv format is compatible with binary.binary_pg_version. May only be set if binary.want_binary_basetypes was set to true by the client in the parameters and the client’s accepted send/recv format matches that of the server. |
| binary.basetypes_major_version | uint16 | The PostgreSQL major version that internal binary format values are compatible with. Corresponds to PG_VERSION_NUM/100 on the upstream server. |
| binary.binary_pg_version | uint16 | The PostgreSQL major version that send/recv format values will be compatible with. This is not necessarily the actual upstream PostgreSQL version. |
| binary.sizeof_int | uint8 | sizeof(int) on the upstream. |
| binary.sizeof_long | uint8 | sizeof(long) on the upstream. |
| binary.sizeof_datum | uint8 | sizeof(Datum) on the upstream (the PostgreSQL Datum typedef). |
| binary.maxalign | uint8 | Upstream PostgreSQL server’s MAXIMUM_ALIGNOF value - platform dependent, determined at build time. |
| binary.bigendian | bool | True iff the upstream is big-endian. |
| binary.float4_byval | bool | Upstream PostgreSQL’s float4_byval compile option. |
| binary.float8_byval | bool | Upstream PostgreSQL’s float8_byval compile option. |
| binary.integer_datetimes | bool | Whether TIME, TIMESTAMP and TIMESTAMP WITH TIME ZONE will be sent using integer or floating point representation. Usually this is the value of the upstream PostgreSQL’s integer_datetimes compile option. |
Startup Errors
If the server rejects the client’s connection - due to non-overlapping protocol support, unrecognised parameter formats, unsupported required parameters like hooks, etc - then it will follow the startup reply message with a normal libpq protocol error message. (Current versions send this before the startup message).
Arguments Client Supplies to Output Plugin
The one opportunity for the downstream client to send information (other than replay feedback) to the upstream is at connect-time, as an array of arguments to the output plugin supplied to START LOGICAL REPLICATION.
There is no back-and-forth, no handshake.
As a result, the client mainly announces capabilities and makes requests of the output plugin. The output plugin will ERROR if required parameters are unset, or where incompatibilities that cannot be resolved are found. Otherwise the output plugin reports what it could and could not honour in the startup message it sends as the first message on the wire down to the client. The client chooses whether to continue replay or to disconnect and report an error to the user, then possibly reconnect with different options.
Output Plugin Arguments
The output plugin’s key/value arguments are specified in pairs, as key and value. They’re what’s passed to START_REPLICATION, etc.
All parameters are passed in text form. They should be limited to 7-bit ASCII, since the server’s text encoding is not known, but may be normalized precomposed UTF-8. The types specified for parameters indicate what the output plugin should attempt to convert the text into. Clients should not send text values that are outside the range for that type.
Capabilities
Many values are capabilities flags for the client, indicating that it understands optional features like metadata caching, binary format transfers, etc. In general the output plugin may disregard capabilities the client advertises as supported and act as if they are not supported. If a capability is advertised as unsupported or is not advertised the output plugin must not enable the corresponding features.
In other words, don’t send the client something it’s not expecting.
Protocol Versioning
Two parameters max_proto_version and min_proto_version, which clients must always send, allow negotiation of the protocol version. The output plugin must ERROR if the client protocol support does not overlap its own protocol support range.
The protocol version is only incremented when there are major breaking changes that all or most clients must be modified to accommodate. Most changes are done by adding new optional messages and/or by having clients advertise capabilities to opt in to features.
The current protocol version range is 4 (min) to 5 (max). Both nodes must be running Spock version >= 50000 to use protocol versions 4 and 5.
The startup_params_format parameter identifies the format of the startup parameter set itself (currently always “1”). Parameters are looked up by name and may appear in any order.
| Key | Type | Value(s) | Notes |
|---|---|---|---|
| startup_params_format | uint32 | 1 | The format version of this startup parameter set. Currently always 1. Required, ERROR if missing. |
| max_proto_version | uint32 | 4-5 | Newest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing. |
| min_proto_version | uint32 | 4-5 | Oldest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing. |
Client Requirements and Capabilities
| Key | Type | Default | Notes |
|---|---|---|---|
| expected_encoding | string | null | The text encoding the downstream expects field values to be in. Applies to text, binary and internal representations of field values in native format. Has no effect on other protocol content. If specified, the upstream must honour it. For json protocol, must be unset or match client_encoding. (Current plugin versions ERROR if this is set for the native protocol and not equal to the upstream database’s encoding). |
| proto_format | string | null | Protocol format requested. “native” (documented here) or “json”. Default is native (binary). |
| no_txinfo | boolean | false | When true, requests that variable transaction info such as XIDs, LSNs, and timestamps be omitted from output. Mainly for tests. Currently ignored for protos other than json. |
Spock-Specific Parameters
These parameters are specific to the Spock replication extension and control what data is replicated.
| Key | Type | Default | Notes |
|---|---|---|---|
| spock.forward_origins | string | null | Comma-separated list of replication origin names to forward. Currently only the special value “all” is accepted. |
| spock.replication_set_names | string | null | Comma-separated list of replication set names to subscribe to. If specified, only changes in the named replication sets are sent. |
| spock.replicate_only_table | string | null | Qualified table name (schema.table) to replicate. If specified, only changes to this single table are sent. Used during initial table synchronization. |
| hooks.setup_function | string | null | Legacy parameter for backwards compatibility with Spock 1.x. Currently ignored. |
General Client Information
These keys tell the output plugin about the client. They’re mainly for informational purposes. In particular, the versions must not be used to determine compatibility for binary or send/recv format, as non-PostgreSQL clients will simply not send them at all but may still understand binary or send/recv format fields.
| Key | Type | Default | Notes |
|---|---|---|---|
| pg_version | uint32 | null | PostgreSQL PG_VERSION_NUM of the downstream, if it’s PostgreSQL. e.g. 180000. Note: despite the name, this is the numeric version (equivalent to the startup message’s pg_version_num). |
| spock_version | string | null | Spock version string of the downstream. e.g. “4.0.11”. Logged on the upstream if it differs from the server’s version. |
| spock_version_num | uint32 | null | Spock numeric version of the downstream. e.g. 40011. Logged on the upstream if it differs from the server’s version. |
Parameters Relating to Exchange of Binary Values
The downstream may specify to the upstream that it is capable of understanding binary (PostgreSQL internal binary datum format), and/or send/recv (PostgreSQL binary interchange) format data by setting the binary.want_binary_basetypes and/or binary.want_internal_basetypes options, or other yet-to-be-defined options.
An upstream output plugin that does not support one or both formats may ignore the downstream’s binary support and send text format, in which case it may ignore all binary.* parameters. All downstreams must support text format. An upstream output plugin must not send binary or send/recv format unless the downstream has announced it can receive it. If both upstream and downstream support both formats an upstream should prefer binary format and fall back to send/recv, then to text, if compatibility requires.
Internal and binary format selection should be done on a type-by-type basis. It is quite normal to send ’text’ format for extension types while sending binary for built-in types.
The downstream must specify its compatibility requirements for internal and binary data if it requests either or both formats. The upstream must honour these by falling back from binary to send/recv, and from send/recv to text, where the upstream and downstream are not compatible.
An unspecified compatibility field must be presumed to be unsupported by the downstream so that older clients that don’t know about a change in a newer version don’t receive unexpected data. For example, in the unlikely event that PostgreSQL 99.8 switched to 128-bit DPD (Densely Packed Decimal) representations of NUMERIC instead of the current arbitrary-length BCD (Binary Coded Decimal) format, a new binary.dpd_numerics parameter would be added. Clients that didn’t know about the change wouldn’t know to set it, so the upstream would presume it unsupported and send text format NUMERIC to those clients. This also means that clients that support the new format wouldn’t be able to receive the old format in binary from older servers since they’d specify dpd_numerics = true in their compatibility parameters.
At this time a downstream may specify compatibility with only one value for a given option; i.e. a downstream cannot say it supports both 4-byte and 8-byte sizeof(int). Leaving it unspecified means the upstream must assume the downstream supports neither. (A future protocol extension may allow clients to specify alternative sets of supported formats).
The pg_version option must not be used to decide compatibility. Use binary.basetypes_major_version instead.
| Key name | Value type | Default | Description |
|---|---|---|---|
| binary.want_binary_basetypes | boolean | false | True if the client accepts binary interchange (send/recv) format rows for PostgreSQL built-in base types. |
| binary.want_internal_basetypes | boolean | false | True if the client accepts PostgreSQL internal-format binary output for base PostgreSQL types not otherwise specified elsewhere. |
| binary.basetypes_major_version | uint32 | null | The PostgreSQL major version the downstream expects binary and send/recv format values to be in. Corresponds to PG_VERSION_NUM/100 in PostgreSQL. e.g. 180 for PostgreSQL 18.0. |
| binary.sizeof_int | uint32 | null | sizeof(int) on the downstream. |
| binary.sizeof_long | uint32 | null | sizeof(long) on the downstream. |
| binary.sizeof_datum | uint32 | null | sizeof(Datum) on the downstream (the PostgreSQL Datum typedef). |
| binary.bigendian | bool | null | True iff the downstream is big-endian. |
| binary.float4_byval | bool | null | Downstream PostgreSQL’s float4_byval compile option. |
| binary.float8_byval | bool | null | Downstream PostgreSQL’s float8_byval compile option. |
| binary.integer_datetimes | bool | null | Downstream PostgreSQL’s integer_datetimes compile option. |
Note:
binary.maxalignis not sent by the downstream client. It is only present in the upstream’s startup message. The upstream uses its own MAXIMUM_ALIGNOF for binary compatibility decisions.
Extensibility
Because of the use of optional parameters in output plugin arguments, and the confirmation/response sent in the startup packet, a basic handshake is possible between upstream and downstream, allowing negotiation of capabilities.
The output plugin must never send non-optional data or change its wire format without confirmation from the client that it can understand the new data. It may send optional data without negotiation.
When extending the output plugin arguments, add-ons are expected to prefix all keys with the extension name, and should preferably use a single top level key with a json object value to carry their extension information. Additions to the startup message should follow the same pattern.
Hooks and plugins can be used to add functionality specific to a client.
JSON Protocol
If proto_format is set to json then the output plugin will emit JSON
instead of the custom binary protocol. JSON support is intended mainly for
debugging and diagnostics.
The JSON format supports all the same hooks.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.17 - Troubleshooting Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This document provides solutions to common issues encountered when using Spock for PostgreSQL logical replication.
Start with the Status Views
Before reading the server log, query the status views. They hold the last error of every apply worker and a history of recent events on the node:
Common Replication Issues
This section describes common problems that prevent replication from working correctly and provides solutions for each issue.
Replication Not Starting
If replication fails to start, check the following items:
Verify
pg_hba.confentries allow secure connections between nodes.Test network connectivity between nodes with the following command:
You can check the PostgreSQL logs for detailed error messages with this command:
You can verify that the Spock extension is created on both nodes with this query:
Subscription Stuck in Initializing State
If a subscription remains in the initializing state, verify the following configuration parameters.
Check that
max_replication_slotsis set to a sufficient value:A subscription that is initializing needs two slots on the provider: the one held by its apply stream, plus one created for the sync worker that copies the table data. Subscriptions are per database, so size for
2 x subscribers x replicated databasesper node, plus any physical or failover slots. On PostgreSQL 15-17 this parameter also caps replication origins.Verify that
max_wal_sendersis set to a sufficient value:Set this equal to
max_replication_slots: every slot has a walsender behind it while it streams, so the accounting above applies unchanged. A shortfall here is the most common reason a cluster that replicates fine in steady state cannot add or resync a table.For PostgreSQL 18+, check the
max_active_replication_originssetting:Ensure that the value is at least the number of subscriptions this node applies -
(nodes - 1) x replicated databasesin a full mesh - plus headroom.If parameters were modified, restart PostgreSQL with this command:
Check the subscription status with this query:
DDL Not Replicating
If DDL statements are not replicating across nodes, check the following settings.
Verify that automatic DDL replication is enabled with this query:
The value should be
on.Check that the
include_ddl_repsetparameter is enabled:Ensure that schema structures match on both nodes before enabling auto-DDL.
To confirm that DDL is replicated from functions, verify this setting is enabled:
Some DDL statements are intentionally not replicated, such as CREATE DATABASE. The CREATE TABLE...AS... statement generates a warning:
“DDL statement replicated, but could be unsafe.”
UPDATE or DELETE Operations Fail
If UPDATE or DELETE operations fail with unable to find tuple errors,
the table may be missing a primary key or replica identity.
To resolve this issue, choose one of the following solutions:
Add a primary key to the table with the following command:
Alternatively, set a replica identity using a unique index:
The unique index must be non-partial, non-deferrable, and use NOT NULL
columns.
REPLICA IDENTITY FULL is only supported with Delta-Apply columns on
primary key tables.
Unique Constraint Conflicts
If you encounter unique constraint violations during replication, ensure
only one UNIQUE index or constraint exists on downstream tables.
The error message for deferrable index constraints appears as follows:
To resolve this issue, convert deferrable constraints to non-deferrable:
Delta-Apply Column Errors
If you receive a delta apply column can’t operate NULL values error, ensure all Delta-Apply columns have NOT NULL constraints.
Then configure the Delta-Apply column with the following command:
Configuration Issues
This section covers problems related to PostgreSQL and Spock configuration parameters that can cause replication issues.
Missing Required Parameters
The following parameters are required in postgresql.conf for Spock to
function properly:
The three numeric values shown are a small-cluster starting point. If you are
troubleshooting worker registration failures, stuck subscriptions, or apply
workers that will not start, size them from your actual topology using
Sizing Postgres Resources for Spock - the defaults in the
tutorials do not account for parallel query workers sharing the
max_worker_processes pool, nor for the per-database managers, the
supervisor, and the slot sync worker that every node runs.
After modifying postgresql.conf, restart PostgreSQL with this command:
Decoding Fails on spock_output
Replication stops — either a new subscription never leaves the initializing state, or an established subscription stops applying after a minor-version upgrade — and the provider’s log records:
A 2026 PostgreSQL security fix (CVE-2026-6471, back-patched to every supported
major) added the output_plugin_libraries parameter, and a library may no
longer be used as an output plugin unless it is listed there. The default,
'pgoutput, test_decoding', excludes spock_output.
The check runs whenever logical decoding starts, not only when the slot is created, so this is not limited to new subscriptions: a cluster that has been replicating for months will stop the first time a walsender starts decoding after the upgrade. Add the library on every node a subscription may connect to — which, in a mesh, is all of them — keeping the core defaults:
Include physical standbys and Patroni replicas that hold synchronized failover
slots: a copied slot keeps spock_output as its plugin, so a standby missing
this setting serves replication only until it is promoted, and then fails.
The parameter is PGC_SUSET, so SELECT pg_reload_conf(); is enough — no
restart needed. The apply worker on the subscriber treats the failure as a
lost connection and reconnects by itself once the provider has been
reloaded; the subscription is not disabled.
Only set the parameter if your server has it; on a release predating the fix,
an unrecognised parameter in postgresql.conf stops the server from starting.
Check with:
A NULL result means the parameter does not exist and must not be set.
Conflict Resolution Issues
If conflicts are causing replication to stop, check the conflict resolution setting with this query:
The only supported value is:
last_update_wins- Keep the version with the newest commit timestamp.
To change the setting, use the following command:
The last_update_wins setting requires track_commit_timestamp = on.
Exception Handling Behavior
If replication is stopping due to errors, check the exception behavior setting with this query:
The following values are available:
transdiscard- Discard the entire transaction on ERROR.discard- Continue processing without the ERROR statement.sub_disable- Disable the subscription and queue transactions.
To change the setting, use the following command:
You can check the exception log table for details with this query:
Performance Issues
This section addresses performance-related problems that can affect replication speed and efficiency.
High Replication Lag
If replication lag is increasing, check the lag status with this query:
The query displays replication_lag_bytes and replication_lag for each
subscription. spock.lag_tracker shows the same figures per node pair. On
the provider, spock.slot_status shows how much WAL each subscriber still
has to fetch in pending_wal_bytes.
Possible causes and solutions include:
- Insufficient
max_worker_processes- increase the value; see Sizing Postgres Resources for Spock. Remember that parallel query workers draw from the same pool, so a parallel-heavy workload can starve apply workers even when the value looks generous, and that the supervisor, the per-database managers, and the slot sync worker each consume a slot before any apply worker starts. - Network bandwidth limitations - check network throughput.
- Large transactions - break into smaller transactions if possible.
- Slow subscriber hardware - upgrade hardware or reduce workload.
Node Failure and Recovery
This section explains how to recover from node failures and restore replication after a node becomes unavailable.
Catastrophic Node Failure
If a node fails catastrophically, use ACE (Active Consistency Engine) to recover missing data.
The recovery workflow involves five phases:
Assess damage by checking subscription status on surviving nodes.
Clean up Spock metadata by dropping subscriptions to the failed node:
Identify missing data using ACE table-diff with these flags:
Repair affected tables using ACE table-repair:
Validate by re-running table-diff without flags to confirm tables match.
Always use the --preserve-origin flag during recovery to maintain
replication metadata. Without this flag, repaired rows get wrong
origin IDs and timestamps, causing conflicts.
Subscription Down Status
If a subscription shows down status, check the following items:
Read the last error of the apply worker and the recent events of the subscription:
A
worker_statusofrestart pendingmeans the worker failed and the manager will retry afterworker_restart_delaymilliseconds.Verify the provider node is running and accessible.
Check replication slots on the provider with this query:
Review PostgreSQL logs on both provider and subscriber nodes if the views do not explain the failure.
Restart the subscription with these commands:
Upgrade Issues
This section provides guidance on verifying and troubleshooting Spock installations after upgrading to a new version.
Post-Upgrade Verification
After upgrading Spock, verify the installation with the following checks.
Check that the extension matches the installed library and that the upgrade was recorded:
Verify subscription status with this query:
Check replication slots on each provider with this query:
Monitor replication lag with this query:
DDL Replication After Upgrade
If DDL replication was disabled for the upgrade, re-enable it on all nodes with the following commands:
Special Feature Issues
This section covers troubleshooting for advanced Spock features including row filters, column filters, and partitioned tables.
Row Filter Errors
If row filters are causing replication to stop, check for volatile functions in the filter expression.
random() is VOLATILE and can return different values on successive calls. now() is STABLE within a transaction and can differ across transactions. Review when the filter is evaluated.
Replace volatile functions with stable or immutable alternatives, or remove them from the filter.
Column Filter Issues
If columns are missing after filtering, note the following behaviors:
- System columns (
oid,xmin) cannot be filtered. - Dropping a filtered column automatically removes it from the filter.
- New columns are not automatically included in existing filters.
Update the filter to include new columns with this command:
Partitioned Table Replication
If new partitions are not replicating, add them manually with the following command:
The parent table is synced during initial sync, but new partitions
created after sync must be added explicitly. Pass partition := NULL
(or omit it) to add every existing partition of the parent at once.
You can also pass an optional row_filter argument to restrict which
rows from the partition are replicated.
Checking Logs
Most replication errors are visible without the log: the last error of each
apply worker is in spock.subscription_status.last_error_message, and errors
raised in a spock worker are recorded as worker_error rows in
spock.events.
Not every one of them reaches that view. Connection failures and PANIC are left out, and an event is dropped rather than waited for when the ring is briefly locked. The log remains the place for the full context of an error, such as the statement and the detail lines, and the place to look when a worker failed and the views do not say why.
PostgreSQL logs provide detailed information about replication errors and issues.
Locate log files with this query:
On RHEL/Rocky Linux, logs are typically located at:
Monitor logs in real-time with this command:
Filter for Spock-related messages with this command:
Getting Help
If you cannot resolve your issue using this troubleshooting guide, gather the following information before requesting support:
- Spock version from
SELECT extversion FROM pg_extension WHERE extname = 'spock'; - PostgreSQL version from
SELECT version(); - Operating system and version
- Configuration settings from
postgresql.conf - Relevant error messages from PostgreSQL logs
- Subscription status from
SELECT * FROM spock.sub_show_status(); - Node status from
SELECT * FROM spock.node; - Replication lag from
SELECT * FROM spock.lag_tracker;
For more information, see the following resources:
- The Spock Functions Reference document provides detailed function documentation.
- The Configuring Spock document describes configuration parameters and settings.
- The Limitations and Restrictions document explains known limitations and constraints that may affect your replication setup.
- The FAQ document answers frequently asked questions.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.18 - Frequently Asked Questions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Using a Column Filter
What happens if I set up a column filter on a table with OIDS? Can I filter on xmin?
Column filters work fine on tables with OIDs, but spock cannot filter on system columns like
oidorxmin.What happens if a column being filtered on is dropped?
Currently in spock replication, you can drop even a primary key on the provider. If a column being filtered on is dropped on the provider, it is removed from the column filter too. Use
spock.repset_show_table()to confirm this behavior.Columns on each subscriber remain as defined, which is correct and expected. In this state, the subscriber replicates INSERTs, but does not replicate UPDATEs and DELETEs.
If I add a column, does it automatically get included?
If you add a column to a table on the provider, it is not automatically added to the column filter.
Using a Row Filter
Can I create a
row_filteron a table with OIDS? Can I filter on xmin?Yes,
row_filterbehavior works fine for table with OIDs, but spock cannot filter on system columns (likexmin).What types of functions can we execute in a
row_filter? Can we use a volatile sampling function, for example?We can execute immutable, stable and volatile functions in a
row_filter. Exercise caution with regard to writes as any expression which will do writes can potentially throw an error and stop replication.Volatile sampling function in
row_filter: This would not work in practice as it would not get correct snapshot of the data in live system. Theoretically with static data, it works.Can we test a JSONB datatype that includes some form of attribute filtering?
Yes, a
row_filteron attributes of JSONB datatype works fine.
Using apply_delay with Time Changes
Does
apply_delayaccommodate time zone changes, for example Daylight Savings Time?Note: the physical replication parameter
recovery_min_apply_delaybehaves differently — if set during daylight savings time, you may get that interval plus the time change (e.g., 1h delay instead of 2h), which could require stopping and starting the database service twice per year.Spock’s
apply_delayis interval-based and accommodates time changes like Daylight Savings Time. The configured interval stays constant and is not affected by DST or other time zone shifts. However, we do not recommend running heavy workloads during a time change as spock replication needs some time (~5 minutes) to recover.
Node failure and recovery
What should I do if a node crashes and another node is left behind (for example, missing some transactions)?
If one node fails and a subscriber did not receive all of that node’s transactions before the failure, you can recover the lagging node using the Active Consistency Engine (ACE). ACE compares table data across the surviving nodes, identifies what is missing on the lagging node, and repairs it using a fully synchronized node as the source of truth. You can preserve original timestamps and origin IDs so that replication metadata stays correct. For a step-by-step procedure, see Recovering from Catastrophic Node Failure.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.19 - Spock Release Notes
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock 6.0.0-beta.2
This section lists what changed since 6.0.0-beta.1, for those testing the beta. Most items are covered in full in the 6.0.0 notes below. This section will be removed at general availability.
Upgrading from beta 1
Beta 1 and beta 2 both install extension version
6.0.0, but the catalog differs between them, so a plainALTER EXTENSION spock UPDATEdoes nothing on a beta 1 node. Update a beta 1 node this way instead:Pause DDL on the cluster.
Install the beta 2 binaries and restart the node.
In every database where Spock is installed, run:
Repeat for each node, then resume DDL.
On each primary, check that every Spock slot has the
failoverflag:For any slot still showing
false, pause the subscriber that holds it and runSELECT spock.slot_enable_failover();on the primary.
The first command adds the objects beta 2 needs (the
spock.reserved_objectcatalog and its functions, the node metadata functions and the trigger onspock.node, and the monitoring views and functions with theirpg_monitorgrants), removesspock.wait_for_apply_worker(), reimplementsspock.get_apply_worker_status()overspock.get_worker_status(), marksspock.md5_aggparallel safe on a node upgraded from 5.x, and sets thefailoverflag on existing slots. The second only sets the version name back to6.0.0.The
failoverflag matters on PostgreSQL 17 and 18, where native slot sync copies only flagged slots to a standby. Beta 1’s upgrade from 5.x did not flag the slots that already existed, so a beta 1 node upgraded from 5.x may have slots that would be missing on the standby after a failover. Slots created by 6.0.0 already have the flag. The first command flags the rest, but skips any slot in use at that moment and prints a NOTICE naming it. On PostgreSQL 16 and older, or with Spock’s own slot sync worker on 17, the flag is not used and step 5 can be skipped.Until a database has been updated, AutoDDL, adding tables to a replication set and structure sync fail there with
catalog "spock.reserved_object" does not exist, and its apply workers fail when a peer changes its location, country or info, becausespock.node_info_apply()is missing. Running the commands on a node that already has beta 2’s catalog changes nothing. These two update steps will be removed at general availability.The upgrade from 5.0.x now starts at 5.0.14. A 5.0.11, 5.0.12 or 5.0.13 node still upgrades in one
ALTER EXTENSION spock UPDATE, through 5.0.14.On a server with PostgreSQL’s fix for CVE-2026-6471,
spock_outputmust be listed inoutput_plugin_libraries. See Upgrading below.On PostgreSQL 18,
spock.pg_standby_slot_namesdid nothing on beta 1, so a value set there, or one inherited by a promoted standby, had no effect. Beta 2 honours it: with the defaultspock.standby_slots_min_confirmedof-1a logical walsender waits for every named slot untilwal_sender_timeoutand then starts over, so replication stalls while a named slot is missing. Check the value on each PostgreSQL 18 node before installing beta 2, and either create the slots it names or clear the setting.
Node monitoring
The largest change since beta 1. See Node monitoring views in the 6.0.0
notes for what each view shows. SELECT on the views, and EXECUTE on the
functions they read, is granted to pg_monitor. USAGE on the spock
schema is not, so a monitoring role needs that granted as well.
GUC
spock.event_history_size(integer, default1024, range 16 to 1048576,POSTMASTER): how many recent events thespock.eventsview keeps in shared memory.
Views
spock.node_status: the whole node on one row: versions, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.peer_status: the known nodes.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: per-subscription worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.table_sync_status: table synchronization state.spock.replication_set_status: the replication sets.spock.system_status: disk space, load, connections, long and idle transactions, wraparound age, archiving.spock.settings: the parameters replication depends on.spock.events: the history of recent events.
Functions
spock.node_report(recent integer DEFAULT 50) RETURNS SETOF text: the whole node as one text report for support cases: host and versions, installed extensions, settings, every monitoring view, and the most recent exceptions, conflict resolutions and events.spock.replication_origin_status(): the replication origins and their progress, readable bypg_monitor, sincepg_replication_origin_statusis for superusers only.- Internal functions behind the views and
node_report():spock.get_worker_status(),spock.get_events(),spock.reset_events(),spock.get_apply_stats(),spock.get_slot_groups(),spock.get_monitor_summary(),spock.get_system_info(),spock.get_pending_exceptions(),spock.redact_dsn(),spock.wal_size_bytes()andspock.report_section().get_system_info(),get_events(),get_apply_stats()andget_pending_exceptions()are executable bypg_monitoronly, andreset_events()by superusers only.
Changed
spock.get_apply_worker_status()is now a SQL function overspock.get_worker_status(), with the same columns and rows as before.spock.get_worker_status()and thespock.worker_statusview cover every worker type and give more detail.spock.reset_subscription_stats()also resets the new activity counters, on every supported PostgreSQL version, and EXECUTE on it is revoked from PUBLIC.
Other GUC changes
New
spock.sync_timeout(seconds, default0,USERSET): the time limit for a single wait in the node management routines.0keeps each routine’s built-in limit.spock.non_conflicting_inserts(boolean, defaultoff,POSTMASTER): asserts that a replicatedINSERTcan never collide with a local row, so the apply worker skips the conflict lookup and the speculative insertion.spock.failover_slots_naptime(milliseconds, default1000,SIGHUP) andspock.failover_slots_feedback_naptime(milliseconds, default10000,SIGHUP): how often Spock’s failover-slots worker syncs slots. It used to wait a fixed 60 seconds.spock.failover_slots_recreate_invalidated(boolean, defaulton,SIGHUP): whether the failover-slots worker drops and recreates a synchronized slot whose copy was invalidated on the standby. Off leaves the copy as it is and reports it once.spock.failover_slots_database(string, default empty,POSTMASTER): on PostgreSQL 16 and 17, the database the failover-slots worker connects to so it can decode each slot copy on the standby. Without it a copy has no snapshot of its own, and after a promotion transactions committed shortly before the failover can be skipped. On PostgreSQL 16 it must be the database the slots belong to.
Changed
spock.pause_timeout: the 300-second maximum is removed.spock.restart_delay_default,spock.restart_delay_on_exceptionandspock.output_delayare now declared in milliseconds, so they accept values with units such as'5s'.spock.restart_delay_defaultnow applies to every apply-worker restart, including after a lost connection or a temporary error.
Other SQL function and catalog changes
The monitoring views and functions are listed under Node monitoring above.
New
- Table
spock.reserved_object, listing the schemas and extensions Spock keeps out of the structure-sync dump, out of replication sets, or out of DDL replication. spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump boolean DEFAULT true, p_block_in_repset boolean DEFAULT true, p_replicate_ddl boolean DEFAULT true).spock.reserved_object_remove(p_name name, p_kind text).spock.node_alter(p_location text, p_country text, p_info_patch jsonb), which changes the local node’s metadata and validates atiebreakervalue.spock.node_refresh_info(p_node_name name DEFAULT NULL), which fetches the metadata of one peer, or of every peer, again.spock.slot_enable_failover() RETURNS integer, called by the 5.x upgrade.- Internal functions
spock.node_info_emit(),spock.node_info_apply(),spock.node_info_broadcast()andspock.node_refresh_info_one(), and thenode_info_broadcast_triggertrigger onspock.node. EXECUTE on the first two and onnode_refresh_info_one()is revoked from PUBLIC.
Removed
spock.wait_for_apply_worker(p_subbid bigint, timeout int).
Changed
spock.repset_add_all_tables()now skips a table it cannot add, with a warning, instead of failing the whole call.
Other changes
- The failover-slots worker no longer stops synchronizing every slot while it waits for the primary’s copy of a new slot to catch up. The new copy stays a temporary slot until then and is dropped, not kept, if the standby is promoted first.
- The walsender hold-back on
spock.pg_standby_slot_nameswithspock.standby_slots_min_confirmedis installed on PostgreSQL 18 and later again. It had been dropped there together with the failover slot worker, but native slot sync only replaces the worker: PostgreSQL’ssynchronized_standby_slotswaits for every slot it names, so with two standbys one that is down stopped replication to every subscriber. - The failover-slots worker recreates a slot copy that was invalidated on
the standby, instead of advancing a copy that could never be used and
breaking the subscription only after a promotion. See
spock.failover_slots_recreate_invalidatedabove. - On PostgreSQL 16 and 17, with
spock.failover_slots_databaseset andwal_level = logicalon the standby, the failover-slots worker decodes each slot copy on the standby so it has a consistent snapshot. Without it, transactions committed shortly before a failover could be missed after the promotion. A copy that cannot be decoded is reported once with a WARNING. - On PostgreSQL 17, once the failover-slots worker has taken over from native slot sync, a copy made by native slot sync whose slot the primary drops no longer makes the worker fail and restart every minute.
- A change already being applied when
spock.sub_resync_table()empties the table is skipped, instead of failing and, withspock.exception_behaviour = sub_disable, disabling the subscription. The same holds for a partition whose partitioned table is being resynchronized. A table sync requested in the middle of a remote transaction now starts its sync worker. - Under
last_update_wins, an incomingUPDATEalways won against a local row thatVACUUMhad frozen, even when the local change was newer, so nodes could end up with different values. The commit timestamp of a frozen row is now found. - A procedure that runs
COMMITorROLLBACK, called over the extended query protocol with a bound parameter, could crash the server.spock.wait_for_sync_event()does this, so a client such as psycopg or JDBC waiting for a sync event could crash a node. - With
spock.apply_change_loggingon, a table whose columns are laid out differently on the provider and the subscriber was logged with values under the wrong columns, and could crash the apply worker on every restart. - Two table syncs finishing at the same time could both write
resource.dat, ending the apply worker and leaving its subscription disabled after the restart. - On PostgreSQL 19, AutoDDL runs
REPACK (ANALYZE)andREPACK (CONCURRENTLY)locally and does not replicate them, since neither can run inside the apply worker’s transaction. spock.sub_wait_for_sync()andspock.table_wait_for_sync()raise an error instead of waiting forever when a subscription has no sync status row, and the apply worker rejects a Spock message too short to hold its type.- Direct DDL against the
spockandsnowflakeschemas is refused while DDL replication is on. - Large objects stored by lolor can be replicated, and Zodan
add_nodecopies them to the new node. - Zodan
add_nodecan add a 6.0.0 node to a cluster of 5.0.9 or later nodes, and copies the source node’s replication sets to the new node. forward_originscannot be active on a subscription while another subscription on the node is enabled.- The apply worker restarts and tries again after a temporary error, such as a deadlock or lock timeout, instead of treating it as a data exception.
pg_upgradeof a Spock node on PostgreSQL 17 and later no longer fails withresource manager with ID 144 not registered.- A node’s location, country and info, including its
tiebreaker, are sent to its direct subscribers when they change.spock.sub_resync_table()warns when the provider’s row differs from the local copy. - A replicated
INSERTthat collides with a row committed locally at the same moment goes to conflict resolution instead of failing with a duplicate key error. EachINSERTinto a table with a unique index now takes a speculative insertion; seespock.non_conflicting_insertsabove. - With three or more nodes, a conflict between two changes with the same
commit timestamp is decided by the existing row’s real origin, so nodes
that agree on every node’s
tiebreakerpick the same winner. When the row’s origin is unknown, the applying node is used, as before. A row copied by the initial table sync records a local origin ID, which can still be taken for a different node. TheCONFLICT: ... wins over ... by tiebreakerlog messages now name the existing row’s origin and the incoming change’s origin instead of the current and remote node. - Table sync no longer fails with
SET TRANSACTION SNAPSHOT must be called before any querywhen an extension such as pg_duckdb runs a query onSET. - Documentation on running logical slot failover under Patroni, with the
sample
samples/set_synchronized_standby_slots.sh. - Bug fixes from 5.0.11 to 5.0.14. From 5.0.13: a promoted
physical standby of a subscriber no longer asks the provider to resend
transactions the subscriber had already applied, which showed up as
conflicts or as duplicate rows in tables without a primary key;
spock.sub_wait_for_sync()andspock.table_wait_for_sync()no longer crash the server when the subscription is dropped while they wait; a pg_dump or pg_restore failure during structure sync reports how the child exited instead of an unrelated error such asInvalid argument; and table sync no longer fails against an origin older than 5.0.7, which lacksspock.pause_apply_workers(). From 5.0.14, besides the failover-slots, frozen-row andCALLfixes listed above: a slot named inspock.pg_standby_slot_namesthat does not exist is reported even when the other slots meetspock.standby_slots_min_confirmed, a slot named twice is counted once, AutoDDL no longer replicatesCLUSTERwithout a table orCLUSTERon a partitioned table, and an apply worker no longer reports the exception log full while it has free entries, or leaves a Spock lock held when it really is full. - An error from the provider’s startup message, or a malformed
BEGIN, no longer makes the apply worker write outside its exception log entry in shared memory. The worker restarts afterspock.restart_delay_defaultinstead. - AutoDDL failed
CREATE SCHEMA ... CREATE TABLE ...withrelation "..." does not exist, which aborted the statement. This happened on PostgreSQL 19 RC2, and on earlier versions when the statement ran from a function or over the extended query protocol. - Builds against PostgreSQL 19 beta 3, beta 4, RC1 and RC2, and against
PostgreSQL 15.20, 16.16, 17.11, 17.12 and 18.7. The
attoptionsserver patches were refreshed for changes in these releases; only context lines changed.
Spock 6.0.0
The on-disk catalog format and the GUC surface both change in this release;
see Upgrading below before running ALTER EXTENSION spock UPDATE.
Highlights
- Catastrophic node failure recovery — new ACE-based workflow with origin-preserving repair prevents silent data divergence after node loss.
- Progress tracking moved to WAL + shared memory — eliminates
heavyweight catalog writes in the apply hot path;
spock.progressis now a view backed byspock.apply_group_progress(). - More granular conflict classification — seven conflict types (up from four), with origin-aware suppression and DELETE conflicts now resolved through timestamp-based resolution.
- Automatic node metadata propagation — a node’s
location,country, andinfo(including its conflict-resolutiontiebreaker) now propagate automatically to every direct subscriber on change, via the newspock.node_alter()function or a plainUPDATE; no more silently disagreeing tiebreakers from a forgottenspock.node_refresh_info(). - Per-subscription conflict statistics on PostgreSQL 18+ via a custom pgstat kind.
- Node monitoring views:
spock.node_status,spock.subscription_status,spock.subscription_stats,spock.worker_status,spock.slot_statusandspock.eventsgive the complete picture of a node without reading the server log. - Liveness and feedback refactor — TCP keepalive replaces the fragile
wal_sender_timeoutworkaround; newspock.apply_idle_timeoutGUC. - Logical slot failover uses native PostgreSQL slotsync on PG17+ / PG18+.
- Rolling upgrade support — protocol negotiation (v4 for 5.0.x, v5 for 6.0+) enables zero-downtime rolling upgrades.
- Exception handling refactor — stable behaviour under TRANSDISCARD /
SUB_DISABLE; original error messages preserved in
spock.exception_log. - Replay queue spills to disk instead of refetching from the publisher.
- Reserved schemas and extensions are configurable — a new
spock.reserved_objectcatalog controls which schemas and extensions are left out of structure sync, replication sets and DDL replication. - Mixed-version node addition — Zodan
add_nodecan add a 6.0.0 node to a cluster of 5.0.9 or later nodes. - Large object replication — tables of the lolor extension can join a
replication set, and Zodan
add_nodecopies large objects to the new node. - PostgreSQL 19 support — compatibility work across core patches and
version-specific API changes (replication-origin session state folded into
replorigin_xact_state,CLUSTERfolded intoREPACK, thepgstatand recovery-conflict signalling changes, and theRepOriginIdrename). Spock builds against PostgreSQL 19 beta 3, beta 4 and RC1. This support is preliminary: PostgreSQL 19 has not been released, and Spock on 19 is not supported for production use.
Catastrophic node failure recovery
Spock 6.0 documents and supports a structured recovery workflow for the scenario where a node fails permanently and one or more surviving nodes are lagging behind. Using the Active Consistency Engine (ACE), operators can:
- Identify which rows are missing on lagging survivors using
table-diff --preserve-origin. - Repair the lagging node from a fully-synchronized survivor using
table-repair --recovery-mode --source-of-truth --preserve-origin.
The --preserve-origin flag is important: it ensures that repaired rows
retain their original origin ID and commit timestamp, so replication
metadata stays correct and the cluster remains conflict-free. Without it,
repaired rows would appear as local changes and could trigger false
conflicts.
Both single-node and multi-node failure scenarios are covered. See Catastrophic Node Failure Recovery for the full guide.
Replication progress tracking
Replication progress is no longer tracked in the spock.progress catalog
table. Spock now tracks it live in shared memory and persists a snapshot
to $PGDATA/spock/resource.dat. On apply-worker startup, Spock
reconciles the snapshot against the durable replication-origin LSN: if
resource.dat is stale, remote_commit_lsn is advanced from the origin
and stale timestamp fields are cleared (to be refreshed by subsequent
apply).
A custom resource manager (id 144) emits one WAL record per
SpockGroupHash entry at each resource.dat dump event, visible via
pg_waldump for debugging, not used for state recovery.
The catalog surface has been restructured accordingly:
spock.progressis now a view over the newspock.apply_group_progress()set-returning function, filtered to the current database. Code that read the previous table of the same name continues to work, but writes are no longer possible. Useapply_group_progress()directly (or the view) for live data, and use the newspock.read_peer_progress(slot, provider_node_id, subscriber_node_id)function during slot snapshot import.spock.lag_trackerview redefined. The oldlast_received_lsncolumn has been renamed tocommit_lsnto reflect what it actually is, and a newreceived_lsncolumn reports the last LSN sent by the publisher (matching thepgoutputprotocol convention).remote_insert_lsnis now updated on every incoming WAL record rather than only on COMMIT, so lag readings are more responsive.
Exception handling improvements
- Fixed TRANSDISCARD / SUB_DISABLE handling during the commit phase in retry mode, preventing apply-worker death loops.
- Eliminated “(unknown action)” in error-context strings and NULL error
messages in
exception_log. The originally-failing row now carries the real error message; bystander rows in the same transaction refer to the entry containing the root cause message. - Added
initial_operationfield to track which DML operation caused a transaction discard. - Subscriptions stuck in an unrecoverable synchronization stage are now disabled rather than restarted indefinitely.
Exception replay: spill to disk
spock.exception_replay_queue_size has changed semantics.
- Before: a single byte threshold (default 4 MiB ≈ 4194304). When the in-memory queue exceeded the threshold, Spock could not replay the transaction and would refetch it from the publisher.
- Now: a soft cap (default
4MB, unitMB). When the queue exceeds the cap, subsequent entries spill to a temporary file on disk. Set to0to disable spilling and allow unbounded memory use (improves throughput for very large transactions; allocation failure falls back tospock.exception_behaviour).
spock.exception_behaviour continues to control the action on
unrecoverable errors:
| Value | Action |
|---|---|
discard | Skip the failed transaction and continue replication. |
transdiscard | Roll back the failed transaction and continue. |
sub_disable | Disable the subscription and exit cleanly. |
Logical Slot Failover
- On PostgreSQL 17+, Spock creates all logical replication slots with
the
FAILOVERflag, allowing PostgreSQL’s built-in slotsync worker (sync_replication_slots = on) to automatically synchronize them to physical standbys. - On PostgreSQL 18+, Spock’s own
spock_failover_slotsbackground worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section of the configuration guide for requiredpostgresql.confsettings. - On PostgreSQL 17, Spock’s worker remains active but automatically
yields to the native slotsync worker if
sync_replication_slots = onis set, preventing conflicts. - Where Spock’s own worker runs (PostgreSQL 15 to 17):
- It syncs slots every
spock.failover_slots_naptime(1 second by default) instead of every 60 seconds. - It recreates a slot copy that was invalidated on the standby, instead
of advancing a copy that could never be used.
spock.failover_slots_recreate_invalidated = offleaves such a copy in place for inspection and reports it once. - It no longer stops syncing every slot while the primary’s slot catches up with a new copy. The new copy stays a temporary slot until then and is dropped, not kept, if the standby is promoted first.
- On PostgreSQL 16 and 17, with
spock.failover_slots_databaseset andwal_level = logicalon the standby, it decodes each copy on the standby so the copy has a consistent snapshot, as PostgreSQL 17’s own slot sync does. Without it, transactions committed shortly before a failover could be missed after the promotion. A copy that cannot be decoded is reported once with a WARNING. The worker stays connected to that database, so commands such asDROP DATABASEon it fail.
- It syncs slots every
More granular conflict classification
v5.0 classified conflicts into four types. v6.0 expands this to seven, adopting PostgreSQL-native conflict-type naming:
| v5.0 type | v6.0 type(s) | What changed |
|---|---|---|
insert_exists | insert_exists | No change. |
update_update | update_exists / update_origin_differs | Spock now distinguishes between an update whose local origin matches the incoming origin (suppressed silently) and one whose local origin differs (evaluated through resolution). update_exists is used for update constraint violations. |
update_delete | update_missing | Renamed for clarity. |
delete_delete | delete_missing / delete_origin_differs | Spock now logs whether the missing row was last modified by a different origin. |
| (new) | delete_exists | A remote DELETE arrives, but the local row has been updated more recently than the delete’s timestamp. The newer local version is preserved. |
Existing spock.resolutions data is migrated automatically during
ALTER EXTENSION spock UPDATE (see Catalog changes below).
DELETE operations now use conflict resolution
In v5.0, when a DELETE found a matching local row, it was applied
immediately without consulting conflict resolution. In v6.0, DELETE
operations go through timestamp-based resolution, just like updates. This
enables the new delete_exists classification — Spock can determine
whether a delete should be applied or whether a newer local version should
be preserved.
Automatic node metadata propagation
A node’s location, country, and info (including a tiebreaker key
used to break same-timestamp conflicts – see Tiebreaker in
conflict_types.md) previously had to be manually
re-fetched onto every other node with spock.node_refresh_info() after
any change; a node left unrefreshed would silently keep disagreeing with
the rest of the cluster about that peer’s tiebreaker.
v6.0 propagates such a change automatically to every node that
subscribes to it directly, via a new AFTER UPDATE trigger on
spock.node and a custom logical-replication message – deliberately
direct-subscribers-only, not forwarded through a cascade topology, so it
introduces no message-ordering dependency on the existing replication
stream. The new spock.node_alter() function is the recommended way to
make the change: it validates a tiebreaker value (must be a whole JSON
number that fits a 32-bit integer) and merges an info patch rather than
replacing it wholesale; a raw UPDATE spock.node on the node’s own row
continues to work and propagates the same way. spock.node_refresh_info()
updates a node whose cached row missed a change, for example because the
transaction carrying it was skipped or discarded, and spock.sub_resync_table()
warns when the provider’s row differs from the cached one. See
Automatic Node Metadata Propagation
and spock.node_alter for
details.
Cascade replication origin tracking
v6.0 adds support for tracking and forwarding replication origins in cascade topologies (Node A → Node B → Node C). The origin name is now included in ORIGIN messages when the protocol version is 5 or higher. This ensures that conflict evaluation on Node C has accurate origin information even when changes pass through intermediate Node B.
If Node C also has a disabled subscription directly to Node A, Spock now advances that subscription’s replication origin as forwarded changes from Node A arrive through Node B. When the direct subscription is later enabled, it starts from where the forwarded changes left off, so rows already received through Node B are not sent again.
A subscription cannot activate forward_origins while another subscription
is already enabled on the same node, and a subscription cannot be enabled
while another has forwarding active; clear forward_origins
(spock.sub_alter_options) or disable the other subscription first. See
Origin Forwarding for
details.
Per-subscription conflict statistics
On PostgreSQL 18+, Spock registers a custom pgstat kind
(SPOCK_PGSTAT_KIND_LRCONFLICTS) to count replication conflicts per
subscription. New SQL functions spock.get_subscription_stats(subid)
and spock.reset_subscription_stats(subid) read and reset them. On
PostgreSQL versions before 18, get_subscription_stats() raises a
feature-not-supported error; reset_subscription_stats() works on every
version, since it also resets the activity counters behind
spock.subscription_stats.
Node monitoring views
Spock now keeps a history of recent events and per-subscription activity
counters in shared memory, and exposes them together with worker, slot and
replication state through a set of views in the spock schema:
spock.node_status: the whole node on one row: library and extension version, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: apply and sync worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.events: subscription enable and disable, worker start, stop and failure, provider connects and disconnects, skipped and discarded transactions, table synchronization, extension upgrades.spock.peer_status,spock.replication_set_statusandspock.settingsfor the known nodes, the replication sets and the parameters replication depends on.spock.system_statusfor the health of the host and the instance: disk space of the data and WAL volumes, load, connections, long and idle transactions, wraparound age, archiving.spock.node_report()returns the whole node as one text report: host and versions, installed extensions, settings and every view in turn.- Errors are kept with SQLSTATE, DETAIL, CONTEXT, time and pid, classified
into deadlocks, lock timeouts, constraint violations and resource errors,
and errors of the walsender running the output plugin are recorded as
stream_errorevents. Workers waiting for a lock show the blocking session.
The event history size is set by the new spock.event_history_size GUC.
spock.reset_subscription_stats() now resets both the activity and the
conflict counters. spock.get_apply_worker_status() is kept, now as a SQL
function over the new spock.get_worker_status(), which with the
spock.worker_status view covers every worker type. The GUC, views and
functions are listed under Node monitoring GUCs, views and functions
below.
Liveness and feedback refactoring
The wal_sender_timeout-based liveness mechanism has been replaced with a
cleaner two-layer model:
- TCP keepalive as the primary liveness detector (detects dead network or host in ~25 seconds).
wal_sender_timeout=0on replication connections so the walsender never disconnects due to missing feedback.spock.apply_idle_timeout(default 300s) as a subscriber-side safety net for hung-but-connected walsenders.
This replaces the maybe_send_feedback() workaround that coupled
subscriber behaviour to a server GUC it cannot control.
Read-only mode refactoring
Read-only mode has been refactored to use PostgreSQL’s native
DefaultXactReadOnly mechanism instead of manual command-type filtering:
READONLY_USERrenamed toREADONLY_LOCAL(the old name is retained as a backward-compatible alias) to clarify that it restricts local (non-replication) connections.- In
READONLY_ALLmode, the apply worker sends keepalive feedback but skips applying new transactions. - Read-only mode changes are detected before applying the next
transaction (
CHECK_FOR_INTERRUPTSmoved to top of the replay loop).
Rolling upgrade via protocol negotiation
Spock now negotiates an output-plugin protocol version between publisher and subscriber (Protocol 4 for v5.0.x, Protocol 5 for v6.0+). This enables zero-downtime rolling upgrades: a v6.0 subscriber can apply from a v5 publisher and vice versa, with protocol-5-only features (such as cascade origin forwarding) activated only when both sides support them.
An incompatible upstream is now rejected early: create_subscription()
runs the version check at DDL time when synchronize_structure is
requested, and a structure sync from a newer-major upstream is refused
(pg_dump cannot read a newer server) instead of failing opaquely after a
slot and snapshot were created.
Zodan: data-loss fix when adding a node under write load
When adding a node while existing nodes were handling writes, the new node could permanently miss rows or accumulate stale updates. The root cause was that apply workers were not paused during slot creation (sub-second operation), so the captured resume LSN could fall before the COPY boundary. The fix pauses apply workers during slot creation and captures the resume LSN deterministically.
Additional Zodan fixes in 6.0:
- Slots and subscriptions are now named consistently as
sub_{provider}_{subscriber}via the newspock.gen_sub_name()helper. remove_nodedrops subscriptions from thespock.subscriptioncatalog instead of guessing names.- Phase 3 catch-up wait aligned and
spock.sync_event()parameterised to avoid the Phase 9 handshake deadlock. - Mixed versions —
add_nodecan add a 6.0.0 node to a cluster whose nodes run 5.0.9 or later, instead of requiring every node to be upgraded first. Existing nodes may already be mixed. The new node must run the same or a newer version than every existing node. - Replication sets are copied — the new node gets the source node’s replication sets, including user-created sets, column lists, row filters, and tables removed from a set. Before, the subscriptions named only the three built-in sets, so tables in a user-created set were neither sent nor received.
- Large objects — the new node may have lolor installed as long as its tables are empty, and must have it when the source replicates lolor tables. The initial data sync copies the large objects.
- Longer waits — the new
spock.sync_timeoutGUC raises the time limit on each wait in the node management routines, which was fixed at about three minutes and too short for large databases.spock.pause_timeoutno longer has a 300-second maximum. - The old Python versions,
zodan.pyandzodremove.py, are removed. Use the SQL procedures.
AutoDDL improvements
AutoDDL has been refactored and hardened:
Centralized in
spock_autoddl.c— all AutoDDL plumbing moved into a single module for maintainability.Simplified control flow — dropped the recursive tag-matching heuristic in favour of clearer early-exit filters.
Extension script guard — internal subcommands during
CREATE EXTENSION/ALTER EXTENSION UPDATEare no longer replicated.Transaction guards — AutoDDL hook no longer fails when utility commands (e.g.,
CLUSTERwithout a table name) execute outside a transaction context.Filtered non-transactional DDL — commands that cannot execute inside transaction blocks on subscribers (e.g.,
CLUSTERon partitioned tables,VACUUM) are filtered on the publisher side before being queued.Temporary-relation DDL not replicated —
CREATE TABLE … (LIKE temp)andCREATE TABLE … AS SELECT … FROM tempare skipped, since the temporary relation does not exist on the subscriber.Replication-set stickiness on
ALTER TABLE— withspock.include_ddl_repsetenabled,ALTER TABLEno longer evicts a table from a user-defined replication set unless it adds or drops a primary key / replica identity. InlineADD COLUMN … PRIMARY KEYandREPLICA IDENTITY FULLtables are now classified correctly.Safe
search_pathinterpolation — replicated DDL ships a validSET search_patheven when the session path is empty.Direct DDL against
spockandsnowflakeis refused (behaviour change) — whilespock.enable_ddl_replicationis on, a statement whose target schema is one of the built-in extension-owned schemas now fails outright:These schemas are populated by extension scripts, where AutoDDL is already suppressed, so a runtime statement against them is almost always a mistake. Previously such a statement half-applied: the command text replicated to peers while the relation was silently kept out of every replication set. See Upgrading for what this affects.
An extension’s own DDL during
DROP EXTENSIONstays node-local — withspock.allow_ddl_from_functionson, DDL an extension ran while being dropped was queued for replication, even though every peer runs the same cleanup when it applies theDROP EXTENSION. For lolor this left peers unable to drop the extension and stalled apply. TheDROP EXTENSIONitself still replicates, except for a node-local extension (below).CREATE,ALTERandDROP EXTENSION lolorare no longer replicated. lolor refuses to be created or dropped by an apply worker, so every peer logged the replicated statement inspock.exception_logand discarded it, while the node that ran it reported it as replicated. Thelolorextension row inspock.reserved_objecthasreplicate_ddl = false, and AutoDDL runs these statements only where they are issued, with a WARNING saying so. Run them on each node.COMMENT ON EXTENSION lolorandSECURITY LABEL ON EXTENSION lolorstay local too. ADROP EXTENSIONnaming lolor together with another extension is refused while DDL replication is on, and so isCREATE EXTENSION ... CASCADEof an extension that requires lolor.spock.replicate_ddl()refuses these statements for lolor.
Reserved schemas and extensions
Spock keeps some schemas and extensions out of the structure-sync dump and
out of replication sets. That list used to be fixed in the code. It is now
the spock.reserved_object catalog, with three settings per row:
exclude_from_dump: left out of the structure-sync dump.block_in_repset: its tables may not be added to a replication set.replicate_ddl: whenfalse,CREATE,ALTERandDROP EXTENSIONfor the extension run only on the node where they are issued. For a schema, the same holds for the DDL statements AutoDDL can trace to the schema; others, such asGRANT, still replicate. See the list in Replication Set Management. The default istrue.
The built-in rows cannot be changed or removed:
| Object | exclude_from_dump | block_in_repset | replicate_ddl |
|---|---|---|---|
spock | yes | yes | yes |
snowflake | yes | yes | yes |
lolor | yes | no | schema yes, extension no |
coldfront | yes | no | yes |
pgedge_ace | yes | yes | no |
Add your own with spock.reserved_object_add() and remove them with
spock.reserved_object_remove(). Your rows are kept across dump and
restore. See
Reserved Schemas and Extensions
for details.
Exclusion from the dump now applies whether or not the object exists on the subscriber. Before, an object present only on the provider was never excluded.
repset_add_all_tables() skips tables it cannot add
spock.repset_add_all_tables() used to fail, and add nothing, when any one
table had no replica identity index. It now adds the tables it can and
prints a warning naming each table it skipped. Tables in a reserved schema
or owned by a reserved extension are skipped the same way. Naming a
reserved schema in the call is still an error, and
spock.repset_add_table() still fails for a table it cannot add.
The message now says “replica identity index” instead of blaming a missing
primary key, since a table with a primary key and REPLICA IDENTITY FULL
or NOTHING is also rejected.
Memory and stability
- Replay queue spills to disk (see Exception replay above) instead of triggering a worker restart, eliminating the unpredictable restarts and replication lag spikes seen with large transactions.
- Resource leak fixes:
- Row filter processing no longer leaks resource-owner entries when many rows are filtered out.
remotetupleis now freed after use in the conflict reporting path.
- Shared memory initialization centralized in
spock_shmem.cwith proper handling of startup, checkpointer, and background-worker processes.
Bug fixes specific to 6.0
- WAL recovery crash after apply-worker failure — when an apply worker crashed and triggered a server restart, WAL recovery could fail due to improperly initialized shared memory structures. Shared memory init has been refactored to handle startup, checkpointer, and background-worker processes correctly.
remote_insert_lsnlost after crash recovery — the value was not included in WAL records and defaulted to 0 after crash recovery, breaking lag tracking inspock.lag_tracker.- Generated columns — tables containing
GENERATED ALWAYS AS … STOREDcolumns caused replication errors because generated columns were treated as regular columns during COPY, protocol messages, default-value filling, and conflict resolution. Now properly excluded. - Replica index lookup with
REPLICA IDENTITY FULL— cached index information was not invalidated before callingRelationGetReplicaIndex(), causing incorrect index usage when switching between replica identity modes. - Hash table iteration safety — fixed removal-during-iteration
corruption, missing NULL checks for
HASH_FIXED_SIZEtables, and torn reads of 64-bit counters without spinlock protection. - Skip LSN mechanism — a successfully skipped transaction in
SUB_DISABLEmode would incorrectly disable the subscription again due to LSN mismatch between the skip point (BEGIN LSN) and the clear point (COMMIT LSN). Exception-handling state is now cleared after a successful skip. - Table sync failure detection — COPY failures during table sync were
silently swallowed and the sync worker retried indefinitely.
PQgetResult()is now called afterPQputCopyEnd()to detect failures, and a newSYNC_STATUS_FAILEDstate stops retry loops and surfaces clear error messages. - Un-appliable TRUNCATE loop — in
discardmode a TRUNCATE that failed on the subscriber (e.g. the relation does not exist) crash-looped the apply worker. It is now wrapped in a subtransaction, logged, and discarded like other DML. pg_upgradefailed on PostgreSQL 17 and later —pg_upgradedecodes each logical slot’s remaining WAL to check it is drained, and Spock’s resource manager was not registered in the serverspg_upgradestarts. The check failed withresource manager with ID 144 not registered.- Apply idle timeout treated as a data exception — when
spock.apply_idle_timeoutfired in the middle of a transaction, the error went down the data-exception path, so the subscription could be disabled or a good transaction discarded. It is now handled like a lost connection. - Clock skew in progress tracking — an origin commit timestamp ahead of
the subscriber’s clock, or forwarded transactions whose timestamps do not
rise with the provider’s WAL position, tripped an assertion in
assert-enabled builds.
remote_commit_lsnnow advances independently of the timestamp fields. - Replay entries restored from the spill file were not terminated — a truncated or malformed record read back from disk could be scanned past the end of its buffer instead of being rejected.
- Peer sessions use a fixed time format — Spock reads commit timestamps
from other nodes as text, and their meaning depended on each side’s
DateStyleandTimeZone. Where the two differed, the same text could mean a different moment, which matters when a timestamp picks the LSN to advance a slot to duringadd_node. Peer connections now requestdatestyle=ISO, and a peer timestamp without an explicit UTC offset is rejected. - Initial sync with a row filter on a table with a dropped column — rows were read at the wrong offsets after a dropped column, giving corrupt rows or a crash.
- Sync worker lost the original error — a failure while creating the
slot during table sync was reported as
errstart was not calledinstead of the real error. - Replicated
INSERTracing a local insert — the apply worker looked for a conflicting row and, finding none, inserted. A row committed locally in between was missed, and the insert failed with a duplicate key error instead of going to conflict resolution. The row is now inserted speculatively with every immediate unique index as an arbiter, and a reported duplicate is looked up and resolved. This adds a speculative insertion to eachINSERTinto a table with a unique index;spock.non_conflicting_insertsturns it off where collisions cannot happen. A collision on a unique index other than the one used to find the row still raises a duplicate key error unlessspock.check_all_uc_indexesis on. - Equal-timestamp ties in a mesh of three or more nodes — the tiebreaker compared the applying node with the origin of the incoming change. When a node resolved a conflict between writes from two other nodes, it could pick a different winner than they did. The tie is now decided between the existing row’s recorded origin and the incoming change’s origin, falling back to the applying node when the row’s origin is unknown.
- Table sync with pg_duckdb — the session
SETs were sent inside the COPY transaction, so an extension that runs a query onSETmade the snapshot import fail withSET TRANSACTION SNAPSHOT must be called before any query. They are now sent before the transaction starts. - Change in flight during a resync —
spock.sub_resync_table()marks the table as being synchronized and empties it, but the apply worker reread its list of tables under synchronization only between remote transactions. A change already being applied met the emptied table, and anUPDATEthat found no row disabled the subscription undersub_disable. Such changes are now skipped, including changes to a partition whose partitioned table is being resynchronized; the sync worker’s copy contains them. A table sync requested in the middle of a remote transaction also failed to start its sync worker. last_update_winsagainst a frozen row — the commit timestamp of a local row was looked up through its xmin, which reads as frozen onceVACUUMfreezes the row, and the row then counted as older than any change. An older incomingUPDATEoverwrote the newer local value, so nodes could diverge. This affects every supported PostgreSQL version:VACUUM (FREEZE)and aggressive vacuums freeze recently written rows, and since PostgreSQL 16 a normalVACUUMcan too. The original xid is now used.- Crash after a procedure that ends its transaction — after a
CALLthat runsCOMMITorROLLBACKover the extended query protocol with a bound parameter, AutoDDL read the statement from freed memory and the server crashed.spock.wait_for_sync_event()runsROLLBACK, so a psycopg or JDBC client waiting for a sync event could crash a node. spock.apply_change_loggingwith different column layouts — values were read at the provider’s column positions, so they were logged under the wrong columns when the provider and the subscriber order or drop columns differently, and a value of one type printed as another could crash the apply worker on every restart.- Concurrent
resource.datwrites — two table syncs finishing at the same time wrote the same temporary file, and the second rename failed, ending the apply worker and leaving its subscription disabled after the restart. REPACKon PostgreSQL 19 — AutoDDL queuedREPACK (ANALYZE)andREPACK (CONCURRENTLY), which cannot run inside the apply worker’s transaction. They now run locally only, as table-less and partitionedCLUSTERalready did.- Failover-slots worker — on PostgreSQL 15 to 17 it advanced a slot copy that had been invalidated on the standby, so the copy looked current but the subscription broke after promotion; it waited for a lagging primary slot without a time limit, syncing no other slot meanwhile, and if promotion came during the wait it kept a copy that skipped commits; on PostgreSQL 16 and 17 a copy had no snapshot of its own, so transactions committed shortly before a failover could be missed; and on PostgreSQL 17 a copy made by native slot sync whose slot the primary dropped made the worker restart every minute. See Logical Slot Failover above.
spock.sub_wait_for_sync()andspock.table_wait_for_sync()waited forever for a subscription that had no sync status row. They now raise an error.
Security
- DSN password obfuscation — passwords in DSN connection strings are no longer visible in error messages or log output. A message-filter hook wipes password characters from error messages before they are written.
Other notable changes
- Protocol cleanup — removed unused SPI API support from the Spock protocol; fixed multiple protocol parameter validation issues.
- Prevented adding tables from ignored schemas to replication sets.
- Snowflake removal — removed snowflake-related functions and documentation since it is now in its own repository.
- SpockCtrl removal — removed the SpockCtrl utility code.
- Windows support removal — dropped Win32-specific code paths; Spock targets POSIX-only environments.
--exclude-extension— extended use of the pg_dump option (PostgreSQL 17+).- PostgreSQL 18 support — compatibility work across core patches, initdb, row filters, and compiler warnings.
- Source tree restructured under
src/andinclude/directories. - Packaging — the repository now builds the
spock60RPM and DEB packages itself. Debian bullseye, which has reached end of life, is no longer built. - Documentation — a new guide on sizing PostgreSQL resources for Spock
by node and database count (see Sizing), a
SECURITY.mdexplaining how to report vulnerabilities, and theoutput_plugin_librariesrequirement in the README and the configuration, installation and troubleshooting guides. The guide to running logical slot failover under Patroni, with the samplesamples/set_synchronized_standby_slots.sh, is carried over from 5.0.12 (see Logical Slot Failover).
GUC changes
New
spock.apply_idle_timeout(int seconds, default300,SIGHUP) — safety net for detecting a hung walsender that keeps the TCP connection alive but stops sending data. The timer resets on any received message. Set to0to disable and rely solely on TCP keepalive for liveness detection.spock.output_delay(int milliseconds, default0, range 0–60000,SIGHUP) — artificial delay in the publisher-side output plugin. Used to reproduce conflict and lag scenarios in tests.spock.resolutions_retention_days(int days, default100,SIGHUP) — TTL for rows inspock.resolutions. Rows older than this are deleted periodically by the apply worker. Set to0to disable automatic cleanup. Complementsspock.cleanup_resolutions(days)and the new index onresolutions(log_time).spock.enable_quiet_mode(bool, defaultoff,SIGHUP) — when enabled, downgrades DDL replication INFO/WARNING messages to LOG level and suppresses dependent-object reporting inDROP CASCADEoperations. Intended for regression tests and production environments where less verbose output is desired.spock.log_verbosity(enumnormal/debug1/debug2, defaultnormal,SUSET) — promotes Spock’s ownDEBUG1/DEBUG2messages toLOGso they survive a normallog_min_messages.spock.apply_change_logging(enumnone/key_only/verbose, defaultnone,SUSET) — emits per-change JSON from the apply worker (action, table, key, origin, commit timestamp; plus row data inverbose).spock.read_retry_countallows for configuring the number of retries when an expected row is not found. The default matches the previously hard-coded value of 5 (there is 1ms of sleep between each retry). Setting it to 0 disables retries. This helps when a node has a large lag and we do not want to slow down processing.spock.sync_timeout(int seconds, default0,USERSET) — the time limit for one wait in the node management routines: for a sync event to arrive, for a peer to catch up, or for a subscription to start replicating. Raise it on large databases, where catching up takes longer than the built-in limits allow.0keeps each routine’s built-in limit. It can be set for one operation, for exampleSET spock.sync_timeout = '2h'.spock.failover_slots_naptime(int milliseconds, default1000, range 1–3600000,SIGHUP) — how long Spock’s failover-slots worker sleeps between slot sync passes. It used to be a fixed 60 seconds, which let a standby’s slots fall up to a minute behind.spock.failover_slots_feedback_naptime(int milliseconds, default10000, range 1–3600000,SIGHUP) — the shorter retry interval the failover-slots worker uses while waiting for the standby to receive the WAL a slot needs. Both failover-slots settings matter only where Spock’s own worker runs: PostgreSQL 15 and 16, and 17 whensync_replication_slotsis off.spock.non_conflicting_inserts(bool, defaultoff,POSTMASTER) — asserts that a replicatedINSERTcan never collide with a local row, for example because each node generates keys from its own range. The apply worker then skips the conflict lookup and the speculative insertion and inserts the row directly. Nothing checks the assertion: a collision raises a duplicate key error, handled byspock.exception_behaviourrather than by conflict resolution.spock.failover_slots_recreate_invalidated(bool, defaulton,SIGHUP) — whether Spock’s failover-slots worker drops and recreates a slot copy that was invalidated on the standby.offleaves the copy as it is, so the cause can be looked into, and reports it once; the copy is recreated on the first pass after the setting is turned back on.spock.failover_slots_database(string, default empty,POSTMASTER) — on PostgreSQL 16 and 17, the database Spock’s failover-slots worker connects to so it can decode each slot copy on the standby and give it a consistent snapshot. On PostgreSQL 16 it must be the database the slots belong to. Empty keeps the old behaviour, under which transactions committed shortly before a failover can be missed after the promotion.
Removed
spock.use_spi— no longer used; the legacy SPI apply path is gone.spock.feedback_frequency— replaced by internal pacing.spock.batch_inserts- unused.
Changed
spock.exception_replay_queue_size: default4194304→4, unit changed from bytes to MB, semantics changed from a hard threshold (with publisher refetch) to a soft cap (with disk spill). See above.spock.pause_timeout: the 300-second maximum is removed, for very large or long-running transactions. The default is still 10 seconds.spock.restart_delay_default,spock.restart_delay_on_exceptionandspock.output_delayare now declared in milliseconds, so they accept values with units ('5s') andSHOWreports the unit. Their values do not change.spock.restart_delay_defaultnow applies to every apply-worker restart, including after a lost connection or a temporary error, so a problem that does not clear cannot become a tight restart loop.
Catalog changes
- New:
spock.sub_id_generatorsequence (replaces inline oid-from-counter generation for subscription rows). - New:
spock.reserved_objecttable, the list of reserved schemas and extensions (see Reserved schemas and extensions above). Built-in rows are protected by a trigger, and only user-added rows are dumped. - New index
spock.resolutions(log_time)to supportspock.cleanup_resolutions(). spock.resolutions.conflict_typevalues renamed during upgrade:update_update→update_exists,update_delete→update_missing,delete_delete→delete_missing.insert_existsis unchanged.spock.subscription.sub_skip_schemais now correctly typed astext[](the column was added astextin 5.0.2 but the C code always treated the bytes astext[]; the 5.0.7 step migration relabels the catalog so no rewrite or downtime is required).- New monitoring views: see Node monitoring GUCs, views and functions below.
New functions
spock.apply_group_progress()— set-returning health view (backsspock.progress).spock.read_peer_progress(slot, provider_node_id, subscriber_node_id)— used by zodan when importing a slot snapshot.spock.get_subscription_stats(subid)/spock.reset_subscription_stats(subid)— per-subscription conflict statistics (reading them needs PostgreSQL 18 or later).spock.cleanup_resolutions(days int DEFAULT NULL)— TTL-based cleanup of the resolutions log. Default permissions revoke EXECUTE from PUBLIC.spock.sub_alter_options(subscription_name name, options text[])— bulk subscription option changes, with input validation and no-op restart skipping.spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump boolean DEFAULT true, p_block_in_repset boolean DEFAULT true, p_replicate_ddl boolean DEFAULT true)— reserve a schema or extension, or change an existing row.spock.reserved_object_remove(p_name name, p_kind text)— remove a reserved schema or extension you added.spock.slot_enable_failover() RETURNS integer— sets thefailoverflag on Spock’s logical slots on PostgreSQL 17 and later, and returns how many it changed. The upgrade from 5.x calls it. EXECUTE is revoked from PUBLIC.spock.node_alter(p_location text, p_country text, p_info_patch jsonb)— validated way to change the local node’s own location/country/info (merging info, validating atiebreakerpatch); see Automatic node metadata propagation above.spock.node_refresh_info(p_node_name name DEFAULT NULL) RETURNS boolean: fetches a peer’s location, country and info again from the peer itself, or every peer’s when called without a name, for a cached row that missed a change. Called with a name, it raises an error if that node cannot be refreshed. Called without one, it warns about each peer it cannot refresh and returnsfalseif any failed.spock.node_info_emit()/spock.node_info_apply()/spock.node_info_broadcast()(trigger function, backing the newnode_info_broadcast_triggeronspock.node) /spock.node_refresh_info_one()— internal plumbing behind node metadata propagation and refresh; not intended to be called directly (EXECUTErevoked fromPUBLIC, except on the trigger function).- The monitoring functions: see Node monitoring GUCs, views and functions below.
Removed functions
spock.convert_column_to_int8(regclass, smallint)— superseded.spock.convert_sequence_to_snowflake(regclass)— superseded.spock.wait_for_apply_worker(p_subbid bigint, timeout int)— had no callers since SpockCtrl was removed.
Node monitoring GUCs, views and functions
The monitoring added in 6.0, in one place. Node monitoring views above
describes what it shows. SELECT on the views, and EXECUTE on the functions
they read, is granted to pg_monitor. USAGE on the spock schema is not,
so a monitoring role needs that granted as well.
GUC
spock.event_history_size(int, default1024, range 16 to 1048576,POSTMASTER): how many recent events thespock.eventsview keeps in shared memory. Once the history is full, each new event drops the oldest, and the history is lost on restart.
Views
spock.node_status: the whole node on one row: versions, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.peer_status: the known nodes.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: per-subscription worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.table_sync_status: table synchronization state.spock.replication_set_status: the replication sets.spock.system_status: disk space, load, connections, long and idle transactions, wraparound age, archiving.spock.settings: the parameters replication depends on.spock.events: the history of recent events.
Functions
spock.node_report(recent integer DEFAULT 50) RETURNS SETOF text: the whole node as one text report for support cases: host and versions, installed extensions, settings, every monitoring view, and the most recent exceptions, conflict resolutions and events.spock.replication_origin_status(): the replication origins and their progress, readable bypg_monitor, sincepg_replication_origin_statusis for superusers only.- Internal functions behind the views and
node_report():spock.get_worker_status(),spock.get_events(),spock.reset_events(),spock.get_apply_stats(),spock.get_slot_groups(),spock.get_monitor_summary(),spock.get_system_info(),spock.get_pending_exceptions(),spock.redact_dsn(),spock.wal_size_bytes()andspock.report_section().get_system_info(),get_events(),get_apply_stats()andget_pending_exceptions()are executable bypg_monitoronly, andreset_events()by superusers only. spock.reset_subscription_stats(subid)also resets the activity counters behindspock.subscription_stats, on every supported PostgreSQL version, and only superusers can run it.spock.get_apply_worker_status()is now a SQL function overspock.get_worker_status(), with the same columns and rows as before.
Bug fixes carried forward from the 5.0.x line
These shipped in 5.0.6 – 5.0.14 and are included in 6.0.0. The 5.0.14 fixes are listed under Other changes in the 6.0.0-beta.2 notes above.
- A promoted physical standby of a subscriber could replay transactions the subscriber had already applied. The apply worker’s commits record the origin node’s progress, not the subscription’s, so crash recovery and a physical standby left the subscription’s replication origin where the last checkpoint or base backup put it, and a promoted standby asked the provider to resend everything after that point. The apply and sync workers now write the subscription’s progress to WAL after each commit. (5.0.13)
spock.sub_wait_for_sync()andspock.table_wait_for_sync()crashed the server if the subscription was dropped while they waited. They now report that the subscription does not exist. (5.0.13)- pg_dump and pg_restore failures during structure sync were reported with
a stale
errnomessage such asInvalid argument. The error now gives the child’s exit code or signal. (5.0.13) - Table sync failed with
function does not existagainst an origin older than 5.0.7, which lacksspock.pause_apply_workers()andspock.resume_apply_workers(). Sync now skips pausing and resuming in that case. (5.0.13) - Handle upstream connection loss cleanly without replication-origin
advance leak. Previously a stale libpq socket fd produced an
epoll_ctl(EINVAL)cascade and the recovery path could silently advance the replication origin past an in-flight remote transaction, causing it to be missed on reconnect (and, withspock.exception_behaviour = transdiscard, its rows would land inspock.exception_logwitherror_message = unknown). The apply worker nowPG_RE_THROWs on connection-class errors and the manager respawns it from the last durably-committed remote LSN. - Preserve the original error message in
spock.exception_logwhen applying undertransdiscard/sub_disable. The originally-failing row now carries the real error message; bystander rows in the same transaction are recorded asunavailableinstead ofunknown. - zodan: name slots and subscriptions consistently
(
sub_{provider}_{subscriber}) via the newspock.gen_sub_name()helper;remove_nodedrops subscriptions from thespock.subscriptioncatalog instead of guessing names; pause apply workers during slot creation to prevent data loss when adding a new node; align Phase 3 catch-up wait and parameterisespock.sync_event()to avoid the Phase 9 handshake deadlock. - Prevent data loss on
resync_tablewhen the subscriber is read-only (SPOC-440). - Fix stale
local_tuplepointer in the INSERT exception path for a missing relation;SUB_DISABLEnow exits cleanly instead of dereferencing freed memory. - Suppress repeated
hot_standby_feedback offERROR spam when a standby is used for reporting (not failover). - Fix stack-use-after-scope in
spock_connect_base()(ASan finding). - Fix resource owner bug
apply_replay_bytesint→uint64overflow fix (b4ba9bdf)- A lost provider connection under
SUB_DISABLEcould disable the subscription: the resent transaction was mistaken for one that had failed to apply. - The apply worker retries after temporary errors — deadlocks,
lock_timeout, running out of a resource (SQLSTATE class 53), or a provider that is restarting or in recovery (57P02, 57P03) — instead of treating them as data exceptions that disable the subscription or discard the transaction. The worker exits without advancing the replication origin and the provider resends the transaction. - Restarting an apply worker in the middle of a transaction could disable
the subscription under
SUB_DISABLE. The failure marker is now cleared when the worker exits onSIGTERM. - An error between transactions left the apply worker in replay mode for
the next transaction, which had never failed, so under
TRANSDISCARDorSUB_DISABLEit could be discarded or disable the subscription. - Two subscriptions whose names share a prefix (such as
subandsub_parallel) shared one exception-log slot. The lookup now compares the whole name, and no longer reads past the end of the array. spock.get_lsn_from_commit_ts()could hang on an idle node. Its WAL scan now stops at the end of WAL as it was when the scan began.- The failover-slots worker died whenever the walreceiver reconnected to
the primary, when
spock.primary_dsnwas not set. It now waits for the next cycle. - Two retry messages lowered from LOG to DEBUG1 still reached the server log with default settings, because the level check was backwards.
- A column that exists on the provider but not on the subscriber put the apply worker in a restart loop. It is now handled like a missing table, and the error names every missing column.
- Tuple data from the provider is checked against the local column definition before use, so a tuple that does not fit is rejected instead of applied. Names and attribute counts in RELATION messages are checked too, and a subscriber built without lz4 rejects an lz4-compressed value.
Upgrading
The upgrade from 5.0.14 to 6.0.0 is a single ALTER EXTENSION spock UPDATE
once the binaries are swapped. Earlier 5.0.x releases upgrade in the same
single step, through 5.0.14. The upgrade:
- drops the legacy
spock.progresstable and recreates it as a view, - replaces the
spock.lag_trackerview definition, - migrates
spock.resolutions.conflict_typevalues, - adds the new functions, the
sub_id_generatorsequence and thespock.reserved_objectcatalog, - drops
spock.wait_for_apply_worker(), - replaces the C
spock.get_apply_worker_status()with a SQL function overspock.get_worker_status(), - adds the
node_info_broadcast_triggertrigger onspock.node, - adds the monitoring views and functions, and grants the read side to
pg_monitor, - refreshes the parallel-safety attributes on
spock.md5_agg_sfunc,spock.md5_aggandspock.spock_gen_slot_name, - turns on the
failoverflag for existing logical slots by callingspock.slot_enable_failover(), so PostgreSQL 17 and 18 slot synchronization picks them up. This is a no-op on PostgreSQL 16 and older and on a standby, and it skips slots that are in use at the time. See Logical Slot Failover for how to handle any skipped slots.
Check your runbooks and automation for direct DDL against the spock or
snowflake schemas before upgrading. Statements such as
DROP TABLE snowflake.x or CREATE INDEX on a spock table succeeded on
5.0.x and now raise an error (see AutoDDL improvements above). Any
procedure that needs to keep doing this must set
spock.enable_ddl_replication = off for the session first, which is also
what the error hint says. The restriction covers only the built-in
extension-owned schemas: schemas you reserve yourself with
spock.reserved_object_add() are unaffected, and pgedge_ace continues to
accept DDL and keep it node-local.
PostgreSQL’s 2026 security fix for CVE-2026-6471 added the
output_plugin_libraries parameter, and its default leaves out
spock_output, so logical decoding fails on a server with the fix. Set
output_plugin_libraries = 'pgoutput, test_decoding, spock_output' on every
node, physical standbys included, and only on servers that have the
parameter. See Configuring Spock.
The apply worker now restarts and tries again after a temporary error such
as a deadlock or lock timeout. If the problem never clears, expect the
worker to restart every spock.restart_delay_default (5 seconds by default)
instead of a disabled subscription or a discarded transaction.
Spock 5.0.15 release candidate (5.0 branch)
pgEdge published v5.0.15-rc.2 on November 23, 2026. The 5.0 branch still lists v5.0.14 as its latest stable tag. The candidate has no schema changes. Its release notes describe three fixes for the failover slot worker:
- When the primary is idle, a new slot copy on the standby can now become permanent in the same synchronization pass. The worker waits for the standby to receive the primary slot’s
restart_lsn, then creates the copy at that position. Previously promotion could discard a temporary copy and leave the subscriber without a slot. - When the standby cannot decode the WAL for an existing copy, the worker keeps the copy’s
restart_lsnin place until the standby has received the WAL up to the intended position. - If
spock.failover_slots_databaseis unavailable, slot synchronization continues without the consistent snapshot check. On a standby the worker retries when the database accepts connections. For other connection failures it retries immediately once, then after one minute, doubling the delay up to five minutes. The postmaster restarts an exited worker after 15 seconds, down from 60.
Spock 5.0.14
Upgrade Notes
There are no schema changes in 5.0.14.
On PostgreSQL 16 and later, we recommend setting the new
spock.failover_slots_databasesetting on each standby to the Spock database. It makes sure a subscriber is not missing transactions after the standby is promoted in a failover. Without it, a few transactions that committed on the primary shortly before the failover may never be sent to subscribers. Slot copies are then synchronized as in 5.0.13, and each one is reported once with a WARNING. The database has to be named because the failover slot worker runs once per server, not in any one database. The setting requires a restart. While it is set, the worker stays connected to that database, soDROP DATABASEandALTER DATABASE ... RENAMEon it fail unless you useWITH (FORCE)or clear the setting. See Configuring Spock.AutoDDL no longer replicates CLUSTER without a table, CLUSTER on a partitioned table, or, on PostgreSQL 19, REPACK with ANALYZE or CONCURRENTLY. These commit on their own partway through and broke the apply worker. They now run only on the node where they are issued, so run them on each node yourself. During a rolling upgrade, a node still on 5.0.13 can still send them, so avoid them or turn off AutoDDL until every node is on 5.0.14.
Bug Fixes
On a physical standby, the failover slot worker kept advancing a slot copy that had been invalidated, so it looked current but could not serve a subscriber after a promotion. The worker now reports such a copy, drops it and recreates it from the primary. The new
spock.failover_slots_recreate_invalidatedsetting turns that off.Creating a slot copy on the standby held up the sync of every other slot until the primary’s slot caught up, and a copy still waiting at promotion was kept with positions it could not serve. A new copy is now a temporary slot until the primary has caught up, and is dropped if the standby is promoted first.
A slot copy carried the primary’s positions but not its snapshot, so after a promotion the transactions that committed before decoding was consistent were never sent. With the new
spock.failover_slots_databasesetting the worker decodes each copy on the standby so that it has a consistent snapshot.On PostgreSQL 17 and later, a copy made by native slot sync whose slot the primary later dropped made the worker fail and restart every minute. The worker now leaves it and reports it once.
A physical slot named in
spock.pg_standby_slot_namesthat does not exist was never reported when the other named slots already satisfiedspock.standby_slots_min_confirmed, so the walsender could wait on it silently. The missing slot is now named in a warning even when the quorum is met, and the warning is issued again if the setting is reloaded to name a different missing slot.A slot listed twice in
spock.pg_standby_slot_nameswas counted twice, so with the defaultspock.standby_slots_min_confirmedof -1,'sb1,sb1'needed two confirmations from one slot and held replication untilwal_sender_timeouton every attempt. Repeated names are now ignored.An apply worker could fail with
unable to find an empty exception log slotwhile most entries were still free, for example when subscriptions with the same name in different databases started at the same time. The error also left a Spock shared memory lock held, so the manager workers,spock.sub_create()andspock.sub_show_status()hung until the server was restarted. The error is now raised only when the log is really full, the lock is released first, and the worker restarts afterspock.restart_delay_default.Under
last_update_wins, an incoming UPDATE always won against a local row that VACUUM had frozen, even when the local change was newer, so nodes could end up with different values. Since PostgreSQL 16, VACUUM can freeze recently written rows. Spock now finds the commit timestamp of a frozen row from its original transaction ID.A procedure that ran COMMIT or ROLLBACK, called over the extended query protocol (psycopg, JDBC) with a bound parameter, could crash the backend and restart the node.
spock.wait_for_sync_event()runs ROLLBACK, so just waiting for a sync event from such a client was enough. Spock read the statement after the procedure had freed it. It now decides whether the statement is DDL before running it.A replicated CLUSTER without a table crashed the apply worker on the subscriber, restarting the postmaster and replaying the statement on every restart. CLUSTER on a partitioned table, and REPACK with ANALYZE or CONCURRENTLY on PostgreSQL 19, had the same problem or hung the worker. These forms are no longer replicated. See Upgrade Notes.
Spock failed to build against PostgreSQL 19 RC1, which changed the signature of
RelationFindReplTupleByIndex().The Debian packages for different PostgreSQL major versions could not have their debug symbol packages installed together, because each one shipped the same build-id file for
spockctrl.spockctrlis no longer in the-dbgsympackage.
Spock 5.0.13
Upgrade Notes
- There are no schema changes in 5.0.13.
Bug Fixes
A promoted standby of a subscriber could replay transactions the subscriber had already applied. The subscription’s replication origin was not written to the WAL, so a standby resumed from the last checkpoint’s position. The apply and sync workers now log the origin’s progress after each commit.
spock.sub_wait_for_sync()andspock.table_wait_for_sync()crashed the backend if the subscription was dropped during the wait. They now report that the subscription does not exist.pg_dump and pg_restore failures during structure sync were reported with a stale
errnomessage such asInvalid argument. The error now gives the child’s exit code or signal.Sync failed with
function does not existagainst an origin older than 5.0.7, which lacksspock.pause_apply_workers()andspock.resume_apply_workers(). Sync now skips pausing and resuming in that case.
Spock 5.0.12
Upgrade Notes
There are no schema changes in 5.0.12.
PostgreSQL’s 2026 security fix for CVE-2026-6471 (back-patched to every supported major) added the
output_plugin_librariesparameter, and a library may no longer be used as an output plugin unless it is listed there. Its default excludesspock_output, so on a server carrying the fix logical decoding fails withlibrary "spock_output" may not be used as an output plugin. The check runs whenever decoding starts, not only at slot creation, so this stops an established cluster after a minor-version upgrade - not just new subscriptions. Setoutput_plugin_libraries = 'pgoutput, test_decoding, spock_output'on every node, physical standbys included, and only on servers that have the parameter- on older releases an unrecognised parameter stops the server from starting. See Configuring Spock. The regression and TAP test suites and the Docker test image now check for the parameter and set it themselves.
When the apply worker fails for a reason that has nothing to do with the data (a deadlock, a lock timeout, a provider that is restarting), it now restarts and tries again instead of treating the failure as an exception. See Bug Fixes. If the problem never goes away, you will see the apply worker restart every
spock.restart_delay_default(5 seconds by default) rather than a disabled subscription or a discarded transaction.
Bug Fixes
The apply worker now retries after temporary errors. Some errors have nothing to do with the replicated data: PostgreSQL picked the apply worker as a deadlock victim,
lock_timeoutfired, the server briefly ran out of a resource (SQLSTATE class 53), or the provider was restarting or still in recovery (57P02, 57P03). All of these succeed if tried again. Before, they went down the same path as a permanent data error, so depending onspock.exception_behaviourthe subscription was disabled or the transaction was written tospock.exception_logand thrown away, even though the provider would happily have sent it again. Now the worker exits without moving the replication origin, the manager starts it again, and the provider resends the transaction. Every restart path, including the existing one for a lost connection, now waitsspock.restart_delay_defaultbefore starting again, so a problem that does not clear cannot turn into a tight restart loop.Tables with
GENERATED ALWAYS AS ... STOREDcolumns caused replication errors. Generated columns were handled like ordinary columns during the initial table copy, in the replication protocol, when filling in defaults for missing columns, and during conflict resolution. They are now left out everywhere, and the subscriber computes them from the column definition.AutoDDL failed after utility commands that run outside a transaction block, such as
CLUSTERwith no table name. These commands commit after each table, so by the time the AutoDDL hook ran there was no open transaction and no snapshot, and the catalog lookups and the queue insert failed. AutoDDL now starts a transaction and takes a snapshot itself when it needs to.spock.get_lsn_from_commit_ts()could hang on an idle node. The function scans the node’s WAL for the last local commit at or before a timestamp, but the scan had no stopping point, so once it caught up it sat waiting for WAL that nobody was going to write. Anadd_noderun was seen stuck behind this call for over eleven minutes. The scan now stops at the end of WAL as it stood when it began, takes the commit timestamp and origin from the WAL record instead ofpg_commit_ts, counts local two-phase commits written by other applications, and refuses to run on a server in recovery. A timestamp with no matching commit still returns the slot’srestart_lsn, now logged at DEBUG1.A failure between transactions could make the apply worker mishandle the next one. When a transaction fails to apply, the worker restarts, the provider resends it, and the worker runs it again in what the code calls replay mode: each row is tried in a subtransaction so the failing row can be written to
spock.exception_logandspock.exception_behaviourcan decide what to do with it. Replay mode is meant for that one transaction. But an error raised between transactions switched the worker into replay mode with no failed transaction to attach it to, and the flag stayed set for whatever the provider sent next. That transaction, which had never failed, ran as a replay and underTRANSDISCARDorSUB_DISABLEwas thrown away or used to disable the subscription. The worker now turns replay mode on only for the transaction that actually failed, and any other transaction clears the recorded failure.A replayed transaction that applied nothing was still committed. Under
TRANSDISCARDandSUB_DISABLEevery row of a replay runs in a subtransaction that is always rolled back, so a replay applies no rows. The check for “replayed but hit no error” ran only after the replication origin had moved forward and the transaction had committed, so the origin ended up past a transaction that was never applied. The transaction was lost while the log said it had been discarded on purpose. The check now runs first and the transaction is rolled back instead, so the provider resends it. Transactions skipped withspock.sub_alter_skiplsnare exempt.Two subscriptions whose names share a prefix (for example
subandsub_parallel) shared one exception-log slot, because the lookup compared only the first few characters. Sharing the slot means sharing the commit LSN that marks a transaction as having already failed, so a failure recorded by one subscription could push the other into replay mode for a transaction that never failed. The lookup now compares the whole name. The same code also read, and could have written, one entry past the end of the array.The failover-slots worker died whenever the walreceiver reconnected to the primary. Without
spock.primary_dsnthe worker takes the primary’s connection string from the walreceiver, which blanks that string for the whole of every connection attempt, not only at standby startup. The connection then failed, the worker exited, and failover slots stopped syncing until it restarted. The worker now waits for the next cycle.Two retry messages for serialization failures are lowered from LOG to DEBUG1, but the check that decides whether to print them at the new level was backwards. With default settings they went to the server log no matter what
log_min_messagessaid. Also marked a deliberate switch fall-through in the apply worker so clang stops warning about it on every build before PostgreSQL 19.Restarting an apply worker in the middle of a transaction could disable the subscription. The worker records the commit LSN of every transaction it begins, not only ones that fail, and a clean shutdown left the marker behind, so the provider’s resend of the interrupted transaction looked like a transaction that had already failed. Under
SUB_DISABLEthat disabled the subscription for no real error. The marker is now cleared when the worker exits onSIGTERM.A column that exists on the provider but not on the subscriber put the apply worker in a restart loop. The error was raised while opening the table, before the per-row subtransaction exception handling needs, so
spock.exception_behaviournever got a say and the error came back on every retry without end. A missing column is now handled like a missing table: the first attempt raises the error, the retry discards the change and logs it through the normal exception path. The message also names every column the local table is missing, so repairing a drifted schema no longer costs one column per apply attempt.Tuple data arriving on the wire is now checked against the local column definition before it is used. Each attribute is copied out of the message into its own buffer and its length checked, so a tuple that does not fit the local column is rejected rather than applied. That is what happens after a provider-only
ALTER COLUMN TYPEwith DDL replication off: the apply worker exits and retries until the two schemas agree. Names and attribute counts in the RELATION message are validated too, and a subscriber built without lz4 now rejects an lz4-compressed value instead of storing it.
Other Changes
Refreshed the
attoptionsserver patch for theheap_update()change in PostgreSQL 17.11, 18.5 and 19 beta 3. One hunk’s context lines no longer matched and the patch was rejected. Only context lines changed.Spock builds against PostgreSQL 19 beta 3 and 4, with a new
compat/19layer for the API changes in that beta (CLUSTERfolded intoREPACK, the recovery-conflict signalling changes, tuple-descriptor finalisation, and the flattenedReorderBufferTXNcommit-time field).CREATE EXTENSIONaccepts major version 19, and CI and the release packaging cover it. This is preliminary: PostgreSQL 19 is still in beta, the compatibility layer will change before it is released, and Spock on 19 is not supported for production use.Dropped Debian bullseye from the platforms the release workflow builds packages for. It has reached end of life.
Removed the old Z0DAN Python files and their TAP test.
add_nodeandremove_nodeare provided by the SQL implementation.New documentation on running logical slot failover under Patroni on PostgreSQL 17 and later. It covers the parameters you need, the settings to put in the bootstrap DCS, and what to do about
synchronized_standby_slotson a switchover. A sample Patronion_role_changecallback,samples/set_synchronized_standby_slots.sh, resetssynchronized_standby_slotsafter a promotion. See Logical Slot Failover.Documented the
wait_if_disabledargument ofspock.wait_for_sync_event().TAP suite: tests share one set of log and wait helpers instead of each carrying a copy, cluster startup waits for the servers to be ready instead of sleeping 17 seconds, and a single test can be run on its own with
prove. New tests cover retry after temporary errors, real deadlocks, replay mode carrying over between transactions,spock.get_lsn_from_commit_ts(), a worker restart in the middle of a transaction, and a column missing on the subscriber.
Spock 5.0.11
New Features
Add
spock.use_native_failover_slots(default off, PGC_POSTMASTER). When enabled, spock marks logical slots with the FAILOVER flag on PG17+, yields to PostgreSQL’s native slotsync worker on PG17 whensync_replication_slots=on, and does not register spock’s own failover-slot worker on PG18+. Off preserves the existing worker-based behavior. Read on the subscriber node that creates the logical replication slot; changing it requires a server restart. See Logical Slot Failover for setup steps and the required post-promotionsynchronized_standby_slotsrunbook.Sync failover slots to the standby every 1s by default instead of a hard-coded 60s, shrinking the window in which a promotion can find a stale slot. The interval is now tunable via
spock.failover_slots_naptime(and the feedback-wait retry viaspock.failover_slots_feedback_naptime), both SIGHUP-settable in millisecondsNever copy the
pgedge_aceschema to a node joining viaadd_node. ACE state is node-local, so its objects are now excluded from both the schema copy and the data sync, even when an ACE table belongs to a replication set.
Bug Fixes
- Fixed a bug where a transient provider connection loss could incorrectly disable a subscription under SUB_DISABLE exception handling. A transaction retransmitted after a reconnect is no longer misclassified as an apply failure, so replication resumes normally instead of stopping.
Spock 5.0.10
Bug Fixes
- Improve apply performance on tables with a unique index over a frequently NULL column. Rows with a NULL in such a key are now recognized as non-conflicting without an unnecessary index scan, avoiding a slowdown that grew with table size.
- Correctly handle conflicts on
NULLS NOT DISTINCTunique indexes. On these indexes (PostgreSQL 15+) two NULL values are treated as equal, so matching NULL-keyed rows are now resolved through normal conflict resolution (last-update-wins) instead of failing with a duplicate-key error. - Fix a
could not open relationerror in the apply worker when an index is dropped while replication is running. The worker now refreshes its cached view of a table’s indexes before using it. - Fix gradual memory growth during a transaction that logs to
spock.exception_log. Memory used while recording exceptions is now released per row instead of accumulating until the transaction commits. - Record the real cause of a discarded transaction in
spock.exception_loginstead of the opaque placeholderunavailable. The failing command’s message is now stored (prefixed with its SQLSTATE where informative), and the other rows of the transaction note that they were discarded as collateral, making it possible to provide the root cause of the exception. - Fix ZODAN (
add_node) version checking. Spock versions were compared as text, so5.0.10sorted below5.0.4and a valid node was wrongly rejected. Versions are now compared numerically, and nodes may differ in patch level as long as their major.minor matches, allowing rolling upgrades. - Fix a spurious “tiebreaker values are equal” WARNING on timestamp-tied conflicts in single-writer topologies (and on node-id hash collisions). The tiebreaker now compares the applying node against the remote sender, and node-id collisions are detected at node creation.
Spock 5.0.9
New Features
- Initial PostgreSQL 19 support. Adds the server-side patches required to build and run Spock against PostgreSQL 19.
Bug Fixes
- Fix silently dropped writes after a synchronous-standby failover. Spock could report an incorrect replication position to the publisher, so a promoted standby resumed from the wrong point and lost the changes in between. The position reported to the publisher is now always taken from the publisher’s own WAL stream.
- Fix
spock_failover_slotsstalling on PG17+ standbys. Slot synchronization could hold replication-slot and proc-array locks exclusively long enough to block every backend trying to start up on the standby, freezing the worker and any new connections. The sync path now uses shorter, shared locks matching PostgreSQL’s own slot code. - Fix manager-worker respawn loop when databases are dropped or have
connections disabled (
datconnlimit = -2) concurrently with Spock starting a per-database worker. The database OID is now revalidated immediately before the worker is registered to avoid race. - Reduce per-row work and memory growth in the apply path. Replicated changes no longer re-open a table’s indexes for every row, and transient memory is freed per row instead of building up over the transaction.
Performance
- Skip building conflict log messages that would not be logged. When the log
level is suppressed, Spock no longer formats the conflicting rows for an
ereport()that would be discarded, speeding up apply on high-conflict workloads. Recording conflicts inspock.resolutionsis unaffected.
Spock 5.0.8
Bug Fixes
- Fix subscriber crash on transactions larger than 2 GB.
apply_replay_byteswas declared asint, causing signed-integer overflow and a crash when a single replicated transaction exceeded 2 GB of WAL data. Changed touint64. - The apply worker now exits cleanly when the upstream connection dies
(firewall reload, walsender SIGKILL/RST, walsender ping timeout) and the
manager respawns it from the last durably-committed remote LSN. Previously
a stale libpq socket fd produced an
epoll_ctl()cascade with a follow-onerror during exception handlingper disconnect, and a corner of the recovery path could silently advance the replication origin past the in-flight remote transaction, causing it to be skipped on reconnect. - Removed native PG17+/PG18 slot-sync integration. Spock no longer creates slots with (FAILOVER), does not defer to PostgreSQL’s slotsync worker, and keeps spock_failover_slots active on PG18; the spock worker is once again the only path for failover-slot sync on 5.x.
- spock_failover_slots: handle primary disconnects and post-promotion edge cases. Reconnects to the primary on transient failure during sync; fixes a PG15/16 PANIC where a freshly promoted standby could enter a crash loop because the synchronized slot’s restart_lsn was below the standby’s WAL floor; tolerates invalid/zero LSNs and catalog_xmin values that previously tripped assertions.
Spock 5.0.7
New Features
Logical Slot Failover Improvements
- On PostgreSQL 17+, Spock now creates all logical replication slots with
the
FAILOVERflag, allowing PostgreSQL’s built-in slotsync worker (sync_replication_slots = on) to automatically synchronize them to physical standbys. - On PostgreSQL 18+, Spock’s own
spock_failover_slotsbackground worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section in the configuration guide for requiredpostgresql.confsettings. - On PostgreSQL 17, Spock’s worker remains active but automatically yields
to the native slotsync worker if
sync_replication_slots = onis set, preventing conflicts.
Bug Fixes
- Preserve the original error message in
spock.exception_logwhen applying inTRANSDISCARDorSUB_DISABLEmode. Previously the original error was written only to the server log and lost before the retry pass; every row in the discarded transaction was logged witherror_message = NULL(stored as “unknown”). The originally-failing row now carries the real error message, while the bystander rows in the same transaction are recorded as “unavailable” instead of the misleading “unknown” fallback. - Fix missing data when adding a new node. An apply worker that committed
between
ensure_replication_slot_snapshotandadjust_progress_infocould advancespock.progresspast the COPY snapshot boundary, causing the new node to permanently skip those changes. Apply workers are now paused via an atomic flag and condition variable inSpockContextfor the duration of slot creation and resumed onceadjust_progress_infocompletes. - Fix apply worker crash with
epoll_ctl() failed: Invalid argumentafter a provider connection died. The socket fd captured beforestream_replay:was never refreshed, so a stale fd was passed toWaitLatchOrSocketon re-entry. The fd is now refreshed atstream_replay:and the worker exits cleanly so the postmaster can restart and reconnect it. - Fix PG15/16 failover slot loss on promotion: reconnect with retry and guard against a zero WAL flush LSN.
- ZODAN:
create_sub_on_new_node_to_src_node(Phase 9 ofadd_node) was generating subscription names assub_{subscriber}_{provider}instead of the expectedsub_{provider}_{subscriber}convention, causingremove_nodeto fail when looking up subscriptions by name. A newspock.gen_sub_name(provider_node, subscriber_node)helper is now used in place of inline name concatenations. - ZODAN: the
remove_nodecleanup loop tried to drop subscriptions by guessing names and nodes, which broke whenevercross_wireandadd_nodeused different naming conventions. It now performs a per-nodeDROPof every subscription read directly from thespock.subscriptioncatalog. - Since 5.0.2 there was a bug with spock.subscription.sub_skip_schema having the incorrect type, it should be text[]. Fixed, including in the spock-5.0.6–5.0.7.sql migration script to repair.
- Fix a rare bug where under high concurrency when using delta apply columns a ResourceOwner exception may occur.
- Have more meaningful messages appear in spock.exception_log.
Operational Improvements
- Documentation: filled out
snowflake.md; revisedupgrading_spock.md; fixed event-trigger syntax (EXECUTE FUNCTIONinstead of the deprecatedEXECUTE PROCEDURE); standardized function-reference filenames to match function names exactly; removed obsoletebatch_inserts.md - Test infrastructure aligned with
main:run_tests.shandSpockTest.pmnow use absoluteTESTLOGDIRpaths, derive per-test log filenames, and isolatepsqlfrom a developer’spsqlrc/history. New regression tests added for failover slots (018), exception-handling/TRANSDISCARD error quality (013), and the stale-fd-after-connection-death scenario (019). - Avoid unnecessarily waiting after sync_event()
Spock 5.0.6
New Features
- New
spock.feedback_frequencyGUC that controls how often feedback is sent to the WAL sender. Feedback is sent every n messages, where n is the configured value. Note that feedback is also sent everywal_sender_timeout / 2seconds. - New
spock.log_origin_changeGUC to control logging of row origin changes to the PostgreSQL log. Origin changes caused by replication are no longer written to thespock.resolutionstable, as they are informational and not true conflicts. Three modes are available:none— Do not log origin changes (default)remote_only_differs— Log only when a row from one remote publisher is updated by a different remote publishersince_sub_creation— Log origin changes for tuples modified after subscription creation (suppresses noise from pg_restored data)
- New
sub_created_atcolumn onspock.subscriptionto help distinguish pre-existing data (e.g. from pg_restore) from post-subscription data. - COPY TO is considered read-only and can now be run when a node is in read-only mode.
Performance Improvements
- Deferred
spock.progresscatalog writes. The progress table was previously updated on every committed transaction and every keepalive, causing significant table bloat and I/O overhead. Progress catalog writes are now batched and flushed at most once per second from the main apply loop. Shared memory is still updated immediately internally for correctness.
Bug Fixes
- Fix initdb assertion failure in attoptions patch for PG15/16/17.
- Fix two bugs in the table re-sync routine: WAL sending is now switched off during truncate and re-sync to prevent data loss, and the infinite wait was fixed when no more DML is committed by using the last committed LSN instead of the last received LSN.
- Use NULL for unknown
local_origininspock.resolutionsinstead of an invalid origin ID when origin cannot be determined (e.g. pg_dump, frozen transactions, truncated commit timestamps). Also fixed off-by-one errors inspock_conflict_row_to_json()that were overwriting thelocal_originNULL flag. - Fix Zodan initialization issue:
present_final_cluster_statenow executes a COMMIT to allow newly created subscriptions to update their state, and final cluster state now checks all subscriptions across the cluster. - Suppress hot_standby_feedback off error messages in log in case a read replica is used for reporting and not failover (it is required for failover).
- Fix bug when applying changes to a table that has been dropped.
Operational Improvements
add_nodeis now restricted to run only on a new (uninitialized) node, preventing accidental misuse.
Spock 5.0.5 on Feb 12, 2026
- Fix segfault that occurs when using new Postgres minor releases like 18.2.
- Zero Downtime Add Node (Zodan) minor bug fixes and improvements
- Updated documentation
Spock 5.0.4 on Oct 8, 2025
- Reduce memory usage for transactions with many inserts.
- When a subscriber’s apply worker updates a row that came from the same
origin, spock will no longer log it in the
spock.resolutionstable, reversing behavior that has been in place since 5.0.0.- Improved handling to block replicating DDL when adding an extension.
- Improved documentation
- Zero Downtime Add Node Improvements:
- New health checks and verifications (ex: version compatibility) before and during the add node process.
- New remove node SQL procedure (
spock.remove_node()in samples/Zodan/zodremove.sql) and python script (samples/Zodan/zodremove.py). This also handles removing nodes that were partially added when the user decided to undo this work. - Handle DSN strings that contain quotes.
- Bug fixes:
- Log messages containing credentials will now obfuscate password information.
- Fix bug when the subscriber receives DML for tables that do not exist.
This case will be handled according to the configured
spock.exception_behavioursetting (SUB_DISABLE,DISCARD,TRANSDISCARD). - Fix bug where spock incorrectly outputs a message that DDL was replicated when a transaction is executing in repair mode.
v5.0.3 on Sep 26, 2025
- Spock 5.0.3 adds support for Postgres 18.
- When using row filters with Postgres 18 such as in the functions spock.repset_add_table() or spock.repset_add_partition(), allowable filters are now stricter. Expressions may not use UDFs nor reference another table, similar to native logical replication in Postgres.
v5.0.2 on Sept 22, 2025
- Improved logging for all Zodan phases in both the stored procedure and Python examples.
- You can use the new Zodan skip_schema parameter to exclude schemas when
you’re adding a node, preventing local extension metadata from being copied.
- Added skip_schema option to sub_create. When synchronize_structure = true, schemas listed in skip_schema are not synced.
- dblink-based stored procedure for add node leverages skip_schema to skip preexisting schemas on the new node, avoiding failures on already existing schemas.
- Python add_node now mirrors stored procedure semantics, including skip_schema handling, structure sync, and logging. It works as a direct alternative to the procedure and no longer requires the dblink extension.
- Spock has been updated to use the PostgreSQL License.
v5.0.1 on Aug 27, 2025
- Bug fix for an incorrect commit timestamp being used for the case of updating a row that was inserted in the same transaction. A consequence was possible incorrect resolution handling for updates.
- Use the default search_path in the replicate_ddl() function.
- Prevent false positives for conflict detection when using partial unique indexes.
- New sample files for adding nodes with zero downtime.
- Python example
- Added enhanced add node support in stored procedures in
samples/zodan.sql
- Add a second node when there is only one node.
- Extended support for adding 3rd, 4th and subsequent nodes.
- Chain adding new nodes off of the previously added new node (eg: add N2 off N1, then add N3 off N2).
v5.0 on July 15, 2025
- Spock functions and stored procedures now support node additions and major
PostgreSQL version. This means:
- existing nodes are able to maintain full read and write capability while a new node is populated and added to the cluster.
- You can perform PostgreSQL major version upgrades as a rolling upgrade by adding a new node with the new major PostgreSQL version, and then removing old nodes hosting the previous version.
- Exception handling performance improvements are now managed with the spock.exception_replay_queue_size GUC.
- Previously, replication lag was estimated on the source node; this meant that if there were no transactions being replicated, the reported lag could continue to increase. Lag tracking is now calculated at the target node, with improved accuracy.
- Spock 5.0 implements LSN Checkpointing with
spock.sync()andspock.wait_for_sync_event(). This feature allows you to identify a checkpoint in the source node WAL files, and watch for the LSN of the checkpoint on a replica node. This allows you to guarantee that a DDL change, has replicated from the source node to all other nodes before publishing an update. - The
spockctrlcommand line utility and sample workflows simplify the management of a Spock multi-master replication setup for PostgreSQL.spockctrlprovides a convenient interface for:- node management
- replication set management
- subscription management
- ad-hoc SQL execution
- workflow automation
- Previously, replicated
DELETEstatements that attempted to delete a missing row were logged as exceptions. Since the purpose of aDELETEstatement is to remove a row, we no longer log these as exceptions. Instead these are now logged in theResolutionstable. INSERTconflicts resulting from a duplicate primary key or identity replica are now transformed into anUPDATEthat updates all columns of the existing row, using Last-Write-Wins (LWW) logic. The transaction is then logged in the node’sResolutionstable, as either:keep localif the local node’sINSERThas a later timestamp than the arrivingINSERTapply remoteif the arrivingINSERTfrom the remote node had a later timestamp
- In a cluster composed of distributed and physical replica nodes, Spock 5.0
improves performance by tracking the Log Sequence Numbers (LSNs) of
transactions that have been applied locally but are still waiting for
confirmation from physical replicas. A final
COMMITconfirmation is provided only after those LSNs are confirmed on the physical replica. This provides a two-phase acknowledgment:- Once when the target node has received and applied the transaction.
- Once when the physical replica confirms the commit.
- The
spock.check_all_uc_indexesGUC is an experimental feature (disabledby default); use this feature at your own risk. If this GUC isenabled, Spock will continue to check unique constraint indexes, after checking the primary key / replica identity index. Only one conflict will be resolved, using Last-Write-Wins logic. If a second conflict occurs, an exception is recorded in thespock.exception_logtable.
Version 4.1
- Hardening Parallel Slots for OLTP production use.
- Commit Order
- Skip LSN
- Optionally stop replicating in an Error
- Enhancements to Automatic DDL replication
Version 4.0
- Full re-work of parallel slots implementation to support mixed OLTP workloads
- Improved support for delta_apply columns to support various data types
- Improved regression test coverage
- Support for Large Object Logical Replication
- Support for pg17
The retained v3.3 production-release notes list the following enhancements over v3.2:
- Automatic replication of DDL statements
Version 3.2
- Support for pg14
- Support for Snowflake Sequences
- Support for setting a database to ReadOnly
- A couple small bug fixes from pgLogical
- Native support for Failover Slots via integrating pg_failover_slots extension
- Parallel slots support for insert only workloads
Version 3.1
- Support for both pg15 and pg16
- Prelim testing for online upgrades between pg15 & pg16
- Regression testing improvements
- Improved support for in-region shadow nodes (in different AZ’s)
- Improved and documented support for replication and maintaining partitioned tables.
Version 3.0 (Beta) includes the following important enhancements beyond the BDR/pg_logical base:
- Support for pg15 (support for pg10 thru pg14 dropped)
- Support for Asynchronous Multi-Master Replication with conflict resolution
- Conflict-free delta-apply columns
- Replication of partitioned tables (to help support geo-sharding)
- Making database clusters location aware (to help support geo-sharding)
- Better error handling for conflict resolution
- Better management & monitoring stats and integration
- A ‘pii’ table for making it easy for personally identifiable data to be kept in country
- Better support for minimizing system interruption during switch-over and failover
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.2.20 - pglogical to Spock function names
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock’s function names are shorter than pglogical’s, so a cluster or a script being ported from pglogical 2 needs almost every call renamed. This page maps each pglogical function to its Spock equivalent.
Verified against pglogical 2.4.8 and Spock 6.0.0. Where a Spock function has a reference page, its name links to it.
Nodes
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_node() | spock.node_create() |
pglogical.drop_node() | spock.node_drop() |
pglogical.alter_node_add_interface() | spock.node_add_interface() |
pglogical.alter_node_drop_interface() | spock.node_drop_interface() |
pglogical.pglogical_node_info() | spock.node_info() |
Subscriptions
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_subscription() | spock.sub_create() |
pglogical.drop_subscription() | spock.sub_drop() |
pglogical.alter_subscription_interface() | spock.sub_alter_interface() |
pglogical.alter_subscription_disable() | spock.sub_disable() |
pglogical.alter_subscription_enable() | spock.sub_enable() |
pglogical.alter_subscription_add_replication_set() | spock.sub_add_repset() |
pglogical.alter_subscription_remove_replication_set() | spock.sub_remove_repset() |
pglogical.show_subscription_status() | spock.sub_show_status() |
pglogical.show_subscription_table() | spock.sub_show_table() |
Replication sets
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_replication_set() | spock.repset_create() |
pglogical.alter_replication_set() | spock.repset_alter() |
pglogical.drop_replication_set() | spock.repset_drop() |
pglogical.replication_set_add_table() | spock.repset_add_table() |
pglogical.replication_set_add_all_tables() | spock.repset_add_all_tables() |
pglogical.replication_set_remove_table() | spock.repset_remove_table() |
pglogical.replication_set_add_sequence() | spock.repset_add_seq() |
pglogical.replication_set_add_all_sequences() | spock.repset_add_all_seqs() |
pglogical.replication_set_remove_sequence() | spock.repset_remove_seq() |
pglogical.show_repset_table_info() | spock.repset_show_table() |
Synchronisation
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.alter_subscription_synchronize() | spock.sub_alter_sync() |
pglogical.alter_subscription_resynchronize_table() | spock.sub_resync_table() |
pglogical.synchronize_sequence() | spock.sync_seq() |
pglogical.wait_for_subscription_sync_complete() | spock.sub_wait_for_sync() |
pglogical.wait_for_table_sync_complete() | spock.table_wait_for_sync() |
pglogical.wait_slot_confirm_lsn() | spock.wait_slot_confirm_lsn() |
DDL, utilities and version information
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.replicate_ddl_command() | spock.replicate_ddl() |
pglogical.table_data_filtered() | spock.table_data_filtered() |
pglogical.xact_commit_timestamp_origin() | spock.xact_commit_timestamp_origin() |
pglogical.pglogical_gen_slot_name() | spock.spock_gen_slot_name() |
pglogical_version() | spock.spock_version() |
pglogical_version_num() | spock.spock_version_num() |
pglogical_max_proto_version() | spock.spock_max_proto_version() |
pglogical_min_proto_version() | spock.spock_min_proto_version() |
Functions with no Spock equivalent
pglogical.queue_truncate() has no counterpart. Spock controls whether
TRUNCATE replicates with the replication set’s replicate_truncate
option, set with spock.repset_create()
or spock.repset_alter(),
rather than with a function call.
Spock functions with no pglogical ancestor
Spock adds functions that pglogical never had, so a port is not finished when
the last name in the table above has been changed. See the
function list for the full set; the additions
include spock.sync_event(), spock.wait_for_sync_event(),
spock.repset_add_partition(), spock.sub_alter_options() and
spock.sub_alter_skiplsn().
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.3 - LOLOR
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The English source is 1.3.0 development snapshot; latest stable tag v1.2.3, pinned at 1548836b0df0. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
On a normal drop, the event trigger checks replication and stored objects, then calls lolor.disable() if needed to restore the native function names. The object-access hook rejects removal if those names are still parked. Migrate the objects back to native storage before dropping the extension. Pinned implementation
lolor is an extension that makes Postgres-style large objects compatible with logical Replication.
Postgres supports large objects as related chunks as described in the pg_largeobject table. Large objects provide stream-style access to user data stored in a special large-object structure in the catalog. Large objects stored in catalog tables require special handling during replication; the lolor extension allows for the storage of large objects in non-catalog tables, aiding in replication of large objects.
lolor creates and manages large object related tables in the lolor schema:
Postgres large objects allow you to store large files within the database. Each large object is recognised by an OID that is assigned at the time of its creation. lolor stores objects in smaller segments within a separate system table and generates associated OIDs for large objects that are distinct from those of native large objects.
Use of the lolor extension requires Postgres 16 or newer.
Migrating large objects
Migration is a manual step in both directions: you decide when to move existing large objects into lolor storage, and you move them back before dropping the extension. Dropping the extension never moves data: it is refused while any object remains in lolor storage.
Native to lolor (manual)
If your database already contains native Postgres large objects, call
migrate_from_native() after enabling the extension. The migration preserves
original OIDs, owners, ACLs, and data, so existing application references remain
valid.
The function returns the number of large objects migrated. It is safe to call when there are no native large objects. This step is intentionally not automatic: it requires superuser privileges and should be performed during a maintenance window.
Lolor to native (before DROP EXTENSION)
Move the large objects back to native Postgres storage, then drop the extension:
Both paths preserve OIDs, owners, ACLs, comments and data, and copy pages verbatim so sparse large objects stay sparse.
A helper supports verifying a migration across nodes:
An object access hook refuses to remove the extension while it is enabled or
while any object remains in lolor storage, on every path that reaches it
(DROP EXTENSION, DROP SCHEMA lolor CASCADE, DROP OWNED BY). The drop
itself only puts the native pg_catalog.lo_* names back. To discard whatever
is in lolor storage instead, a superuser can set lolor.allow_unsafe_drop = on
for the session that runs the drop. It skips every check, and the drop then
does not restore the native function names either, so run lolor.disable()
first if lolor is enabled. While lolor is enabled, a normal drop renames the
native functions back, so it has the same requirements as lolor.disable():
no other session connected to the database, and a client session. A disabled
lolor renames nothing, and the drop has no such requirement.
lolor.enable() and lolor.disable() refuse while
any other session is connected to the database, and refuse to run from
anything but a client session. Reconnect client sessions after enable() or
disable(): libpq caches the large object function OIDs per connection.
Two helpers find and repair objects whose roles have been dropped:
When the spock extension is installed, both migration functions run under
spock.repair_mode(), so the row-shuffling migration DML is not replicated
to other nodes. This is essential for migrate_to_native(): its deletes from
the lolor tables would otherwise replicate while the native re-creation stayed
local, destroying large objects on the other nodes.
Even with spock, migration is refused if a non-spock logical replication slot
(e.g. pgoutput, wal2json) exists, since repair mode only suppresses spock’s
own output plugin and those consumers would still decode the migration DML:
migrate_to_native() raises an ERROR, while migrate_from_native() warns and
returns -1 without doing anything. Drop the offending slots before migrating.
Without spock, the migration DML cannot be excluded from logical decoding, so
both functions refuse to migrate while logical replication slots exist in the
database: migrate_from_native() raises a WARNING and returns -1 without
doing anything (0 is reserved for “nothing to migrate”), while
migrate_to_native() raises an ERROR. Drop all logical replication slots before
migrating; merely disabling a subscription is not sufficient, since its slot
retains the changes and delivers them when replication resumes.
Dropping the extension
In a replicated cluster the lolor tables are published, subscribed, or both, and the drop is refused while any of that is still true: the drop itself would succeed, but the other side would keep sending or expecting rows for tables this node no longer has. Unwind replication first, in this order:
Stop creating and changing large objects on every node, and let replication drain. Then confirm the nodes agree:
Stop publishing the tables. With Spock, remove them from the replication set on every provider node that publishes them:
With native logical replication, drop them from the publication instead:
A publication created
FOR TABLES IN SCHEMA lolordrops them withALTER PUBLICATION mypub DROP TABLES IN SCHEMA lolor. AFOR ALL TABLESpublication publishes them for as long as it exists: drop it, or recreate it with an explicit table list.Stop subscribing to them. A node that synchronized the tables when its spock subscription was created still counts them as replicated; refresh the subscription on that node so it forgets tables that are no longer in the provider’s replication sets:
A native subscription is refreshed with:
From here no node publishes the tables and no subscription expects changes for them, so the order of the per-node steps below does not matter.
Migrate the data out on every node, connecting to each node directly; with spock the migration runs in repair mode and is not replicated:
The migration refuses while a logical replication slot of any plugin other than spock’s exists in the database, and a native subscription keeps its slot on the publisher even when refreshed or disabled. Drop the native subscriptions that point at the node, which removes their slots, before migrating there.
Drop the extension on each node, connecting to each node directly, with no other client session connected to the database:
Without replication there is a single node: stop large object use, run
lolor.migrate_to_native(), and drop the extension, with the same
single-session requirement while lolor is enabled.
Limitations
- Native Postgres large object functionality cannot be used while you are using the lolor extension.
- lolor does not support the following statements against objects held in lolor storage:
ALTER LARGE OBJECT,GRANT ON LARGE OBJECT,COMMENT ON LARGE OBJECT, andREVOKE ON LARGE OBJECT. Owners, ACLs and comments set while an object was in native storage are preserved across migration in both directions. lolor.enable(),lolor.disable(), the migration functions,CREATE EXTENSION lolor, and dropping the extension while lolor is enabled, refuse while any other session is connected to the database, the same rule asALTER DATABASE ... RENAME: a renamed function keeps its OID, so a session that already resolved thelo_*functions keeps calling the previous implementation, and the row movement cannot be made atomic for other backends either. The calling session must reconnect afterenable()ordisable(). They also refuse to run from anything but a client session, so replicated DDL cannot drive them from an apply worker. Only client sessions count: background workers such as replication apply workers do not call thelo_*functions by name. To count reliably, each of these operations takes an exclusive lock on the database first, so a new connection to it waits until the operation’s transaction ends. In single-user mode they run without the session check.- The loaded library and the installed extension must be the same version for
lolor.enable(),lolor.disable(), the migration functions,lolor.check_orphans(),lolor.fix_orphans()and dropping the extension. After installing new library files, runALTER EXTENSION lolor UPDATEin each database before using them; until then they refuse and name both versions. - Objects in lolor storage are rows in ordinary tables and so cannot participate in
pg_shdepend.DROP ROLE,DROP OWNED BYandREASSIGN OWNED BYdo not see them: a role that owns them or appears in their ACL can be dropped without a warning, andREASSIGN OWNED/DROP OWNEDleave them untouched. Before dropping a role, runREASSIGN OWNED BYorDROP OWNED BYin each database that has lolor, thenDROP ROLE. For the role that owns the extension useREASSIGN OWNED BY:DROP OWNED BYwould remove the extension too, and is refused while any object remains in lolor storage. Afterwards runlolor.check_orphans()in each such database and repair anything it reports withlolor.fix_orphans(new_owner);lolor.migrate_to_native()refuses while orphans exist. - Dropping lolor is refused while
lolor.pg_largeobject,lolor.pg_largeobject_metadataorlolor.pg_largeobject_descriptionis in a spock replication set, a publication or a subscription on this node, or was synchronized to this node through a spock subscription, whichever way the drop is spelled. The drop itself would succeed; what breaks is replication afterwards, since the other side keeps sending rows for a table this node no longer has. Remove the tables from the replication set, publication or subscription first, then migrate the objects out and drop. The refusal is enforced when the tables are deleted, not only by the event trigger, so disabling event triggers does not get around it. A spock subscriber knows the tables as replicated only from their initial synchronization; a table added to a replication set later is not seen by the check on that node. The step-by-step order is in Dropping the extension. - Role OIDs come from a cluster-wide counter that wraps around, so a new role can receive a dropped role’s OID and silently become the owner or grantee of that role’s orphaned objects. This cannot be detected after the fact, which is another reason to run
lolor.check_orphans()promptly after dropping roles. - Large object migration is node-local. Native large objects live in
pg_catalog.pg_largeobject, which is never replicated, so each node holds an independent set andmigrate_from_native()migrates only the local node’s objects; with spock installed, the migration DML runs in repair mode and is not replicated. Run the migration on every node that holds native large objects, connecting to each node directly. It refuses to run inside an apply worker, so sending it through DDL replication fails on every subscriber. Migrated objects keep their original native OIDs, which are not node-encoded: if different nodes hold different objects under the same OID, the nodes’ lolor contents will diverge and later replicated changes to those objects can conflict. Newly created large objects are collision-free, since new OIDs are node-encoded vialolor.nodeand checked against existing rows. To make that hazard an error rather than silent divergence, collect the other nodes’ OIDs withlolor.native_lo_oids()and pass them in:SELECT lolor.migrate_from_native(peer_oids => ARRAY[...])refuses when any of them collide. After migrating every node, comparelolor.digest()across nodes to confirm they converged.
Continue reading
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4.4.3.1 - Installing and Configuring lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
lolor is supported on Postgres versions 16 and later.
lolor ships with pgEdge Distributed Postgres and pgEdge Enterprise Postgres, so a pgEdge deployment provides the extension for you. The Control Plane installs the lolor package on each node as part of standard cluster setup.
If you manage Postgres yourself, you can compile and install the extension from the source code, following the same guidelines as any other Postgres extension built with PGXS. Make sure that your PATH environment variable includes the directory where pg_config (under your PostgreSQL installation) is located.
lolor must be loaded at server start. Add it to shared_preload_libraries in postgresql.conf and restart; CREATE EXTENSION lolor, LOAD 'lolor' and any call that reaches one of lolor’s functions fail with lolor must be loaded via "shared_preload_libraries" when the library was loaded on demand; the native pg_catalog.lo_* functions are not affected while lolor is not installed or is disabled. The guard that protects large objects when the extension is dropped is an object access hook, which is only in place in every backend when the library is preloaded.
Then connect to your Postgres database and create the extension with the command:
Configuring lolor
You must set the lolor.node parameter on each node in your replication cluster before using the extension. The value can be from 1 to 15 (0 means unset); it is encoded in the four low bits of every large object OID lolor generates, so each node must use a different value.
You can also change the search_path to pick large object related tables from the lolor schema:
lolor renames any existing methods in pg_catalog.lo_* to pg_catalog.lo_*_orig, and new versions of these methods are introduced. If you remove the extension, the renamed pg_catalog.lo_*_orig functions are restored to their initial names.
When you replicate large objects with Spock, the tables pg_largeobject, pg_largeobject_metadata and pg_largeobject_description must belong to your replication set. The third table holds the comment of each object that was migrated from native storage; without it, a lo_unlink() leaves the comment behind on the other nodes, and a node that is added or resynchronized later does not receive the comments. Connect to the lolor database and add them with spock.repset_add_table:
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4.4.3.2 - lolor Release Notes
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
lolor 1.3.0
These notes describe pinned main development. The latest stable tag checked on November 21, 2026 remains v1.2.3.
On a normal drop, the event trigger checks replication and stored objects, then calls lolor.disable() if needed to restore the native function names. The object-access hook rejects removal if those names are still parked. Migrate the objects back to native storage before dropping the extension. Pinned implementation
- Add bidirectional large object migration between native PostgreSQL and lolor storage, implemented as a direct relation-to-relation copy in C (
lolor.migrate_storage()) rather than a loop through the large object API:lolor.migrate_from_native(peer_oids oid[] DEFAULT NULL)moves native large objects into lolor storage. It is a manual step afterCREATE EXTENSION lolor, requires superuser, and returns the number of objects moved or -1 if the migration was refused.lolor.migrate_to_native()moves them back, whether or not lolor is enabled. It is a manual step before dropping the extension; the drop is refused while any object remains in lolor storage and no longer migrates anything itself.- Both directions preserve OIDs, owners, ACLs, comments and the exact page layout, so sparse objects stay sparse. Ownership and ACLs are recorded in
pg_shdependon the way back, soDROP ROLE,REASSIGN OWNEDandDROP OWNEDsee the objects again. Comments are parked inlolor.pg_largeobject_descriptionwhile an object is in lolor storage. Native objects are removed with the same bookkeeping asDROP(dependencies, comments and labels), but without the per-object locksDROPtakes, so a database with more large objects than the lock table can hold is migrated without raisingmax_locks_per_transaction. - Storage layouts are verified against the running server at migration time. Security labels, which lolor storage cannot represent, cause
migrate_from_native()to refuse. OID conflicts are reported with the conflicting OIDs. - Migration holds
ShareRowExclusiveLockon both stores until commit. Ordinary large object access takesRowExclusiveLock, which does not conflict with itself, so a concurrentlo_write()could otherwise be lost silently. Opposing migrations take their locks in a fixed order and cannot deadlock. - Both migration functions refuse while any other session is connected to the database, and refuse to run from anything but a client session.
- With spock installed, both functions run under
spock.repair_mode(). If a logical slot spock cannot suppress exists, a non-spock slot or any slot when spock is absent, they refuse rather than let subscribers decode the migration as row changes. - Migration is node-local: native large objects are never replicated, so run the migration on each node by connecting to it directly. Do not send it through DDL replication, which would run it inside every subscriber’s apply worker. Native OIDs are not node-encoded, so pass the other nodes’ OIDs (from
lolor.native_lo_oids()) aspeer_oidsto turn a cross-node collision into a refusal, and comparelolor.digest()across nodes afterwards. migrate_to_native()refuses with a clear error while any object refers to a dropped role, instead of failing part-way with “role N was concurrently dropped”; remove those objects withlo_unlink()and retry.
- New helpers
lolor.digest()andlolor.native_lo_oids()for cross-node checks after a node-local migration. - New helpers
lolor.check_orphans()andlolor.fix_orphans(new_owner)for objects whose owner, grantee or grantor has been dropped. Objects in lolor storage cannot participate inpg_shdepend, soDROP ROLEdoes not notice them;check_orphans()lists them and which reference is dangling, andfix_orphans()reassigns dead owners, replacing them in the ACL asREASSIGN OWNEDwould so that grants they made survive, and drops entries that still name a missing role. - Server-side large-object file permissions. Versions 1.0 through 1.2.2 granted excessive default execution rights on replacement file-import and export functions. Use the corrected extension SQL and verify function privileges after upgrade. Review which roles actually need server-side file access.
- The extension is no longer marked
trusted. Installing lolor renames functions inpg_catalogfor the whole database, which a non-superuser should not be able to do. - Fixed
DROP ROLEfailing with “unrecognized object class”. Creating a large object recorded apg_shdependrow whoseclassIdwas the OID oflolor.pg_largeobject, an ordinary table rather than a catalog. Any role that had created a large object became undroppable, and the rows were never cleaned up becauseinv_drop()deleted withPERFORM_DELETION_SKIP_ORIGINAL. lolor no longer records these rows, and the upgrade removes the ones already present.- The cleanup is per database, so
ALTER EXTENSION lolor UPDATEmust be run in every database that has lolor. Until it is,DROP ROLEanywhere in the cluster keeps reporting “owner of objects in database X”. - A database that ran
DROP EXTENSION loloron an earlier version still has the rows, now pointing at a table that no longer exists, and no upgrade script will run there. Clean it by hand as superuser in that database: find the stale class OIDs withSELECT DISTINCT classid FROM pg_shdepend WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND classid NOT IN (SELECT oid FROM pg_class), thenDELETE FROM pg_shdepend WHERE dbid = <that dbid> AND classid IN (<those OIDs>).
- The cleanup is per database, so
- lolor must now be listed in
shared_preload_libraries. Loading it on demand is refused:CREATE EXTENSION lolor,LOAD 'lolor'and any call that reaches one of lolor’s functions fail withlolor must be loaded via "shared_preload_libraries"; the nativepg_catalog.lo_*functions are not affected while lolor is not installed or is disabled. The drop guard below is an object access hook, which is only present in every backend and worker when the library is preloaded, and a missing or broken library now fails at server start rather than at the firstlo_open(). Upgrade in this order: install the new library files, addlolortoshared_preload_libraries, restart, then runALTER EXTENSION lolor UPDATEin each database. Between the file install and the restart, any session that loads the new library on demand gets that error, so restart promptly. - Removing the extension is guarded by an object access hook.
DROP EXTENSION,DROP SCHEMA lolor CASCADE,DROP OWNED BYand any other path that reaches the extension are refused while lolor is enabled or while any object remains in lolor storage, checked in the catalog at the moment of deletion from whichever backend performs it. The drop no longer migrates the objects out itself: runlolor.migrate_to_native()first. The event trigger only puts the nativepg_catalog.lo_*names back. The new superuser settinglolor.allow_unsafe_dropskips both checks and discards the contents of lolor storage. Because the drop renames the native functions back, it has the same requirements aslolor.disable(): no other session connected to the database, and a client session. - Dropping lolor is refused while its tables are in a spock replication set, a publication on this node, including one created
FOR ALL TABLESorFOR TABLES IN SCHEMA lolor, or a subscription on this node, or were synchronized to it through a spock subscription. The drop would succeed and replication would break afterwards: the other side keeps sending rows for a table this node no longer has, and a subscription removed byDROP OWNED BYleaves its slot behind. The error names the memberships; remove the tables from them first. The check is enforced when the tables are deleted, so it holds with event triggers disabled. lolor.enable()andlolor.disable()refuse to run from anything but a client session, so replicated DDL cannot execute them inside an apply worker, where a refusal would leave that node’s replication retrying forever.CREATE EXTENSION lolorhas the same requirements aslolor.enable(), since the install script renames the native functions the same way: no other session connected to the database, and a client session.lolor.enable(),lolor.disable()andlolor.is_enabled()now probe exact function signatures inpg_catalog. They previously matched onpronameacross every schema, so any user withCREATEon any schema could define a function namedlolor_lo_openand wedge lolor into a permanent “inconsistent state” that also blockedDROP EXTENSION. Both now emit a notice that client sessions must reconnect, since libpq caches the large object function OIDs per connection, and refuse while any other session is connected to the database, since a renamed function keeps its OID and other sessions cannot be made to see the switch.- The session check behind
lolor.enable(),lolor.disable(), the migration functions and the drop is done in C and takes an exclusive lock on the database before counting, so a session connecting at the same moment either is counted or waits until the operation’s transaction ends. Previously it was a snapshot ofpg_stat_activityand could miss such a session. Single-user mode is no longer refused. lolor.enable(),lolor.disable(), the migration functions,lolor.check_orphans(),lolor.fix_orphans()and dropping the extension refuse while the loaded library and the installed extension are different versions. A drop with new library files and an older installed extension would otherwise run that version’sdisable(), which still has the unqualified function lookups fixed in this release. RunALTER EXTENSION lolor UPDATEfirst.- Fixed the
lolor.nodeupper bound. The GUC accepted 0..16 while a generated OID reserves four bits for the node id, so node 16 did not fit: the node field of every OID it generated read back as 0. The bound is now derived from the encoding (LOLOR_MAX_NODE_ID), giving 0..15. If you havelolor.node = 16configured, the server still starts but logs16 is outside the valid range for parameter "lolor.node" (0 .. 15)and falls back to 0, which is the node id it was effectively using already. Set it to a value in 0..15, and check for OID collisions against whichever node is genuinely 0. - Expanded test coverage: TAP tests for dump/restore, streaming and logical replication, standby promotion, the drop paths, migration fidelity and locking, and cross-node OID collisions; regression tests for
lo_lseek,lo_tell,lo_truncate, the 64-bit interface, sparse objects, comment round trips,pg_shdependrestoration, permission enforcement, the orphan helpers and name squatting. The regression suite runs on its own preloaded instance. - Security hardening: addressed Codacy/Flawfinder warnings.
lolor 1.2.3
- Add support for PostgreSQL 19
- Add in-repo release workflow and RPM/DEB packaging
- Improve CI: build the test cluster from source, add PostgreSQL 19 to the test matrix, and bound test run time
lolor 1.2.2
- Fix lolor upgrades
- Fix issues with pg_upgrade. Note that this fixes upgrades with pg_upgrade going forward.
ALTER EXTENSION UPDATEfor upgrading the extension itself works, so if wanting to run pg_upgrade, first update your extension to 1.2.2, then run pg_upgrade - Address CVEs CVE-2022-26520, GHSA-673j-qm5f-xpv8
- PATH updated to match native Postgres packaging layout
- Make table OID caching safer
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4.4.3.3 - Using lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The following command examples demonstrate using lolor:
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4.4.3.4 - Using pg_upgrade with lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The pg_upgrade utility is used for upgrading Postgres versions.
You can use pg_upgrade with the lolor extension installed provided that you are using lolor version 1.2.2 or later. If you are using an older version of lolor, you will need to upgrade the extension first.
Both clusters must list lolor in shared_preload_libraries; without it the new cluster cannot load lolor’s library, so restoring the extension fails.
Before running pg_upgrade, you must disable lolor. After executing pg_upgrade, you can enable lolor. Use psql or another client to disable lolor:
Next, execute the upgrade. A sample pg_upgrade command appears below:
Then, use psql to enable lolor:
Reconnect any client sessions afterwards. lolor.enable() and
lolor.disable() change which function OID owns each pg_catalog.lo_* name,
and libpq resolves those OIDs once per connection and caches them for the life
of the connection. A session that used a large object before the switch would
otherwise keep calling the previous implementation.
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4.4.4 - Snowflake
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
The English source is v2.6.1, pinned at 9506e1bd5c1f. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
Using a Snowflake sequence allows you to take full advantage of the benefits offered by a distributed, multi-master replication solution. Snowflake is a Postgres extension that provides an int8 and sequence based unique ID solution to optionally replace the Postgres built-in bigserial data type.
Internally, snowflakes are 64 bit integers represented externally as bigint values. The 64 bits are divided into bit fields:
- bit 63 - unused (sign of int8)
- bits 22-62 - timestamp with millisecond precision
- bits 12-21 - unique pgEdge Distributed Postgres node number
- bits 0-11 - counter within one millisecond
- The timestamp is a 41-bit unsigned value representing millisecond precision and an epoch of 2023-01-01.
- The counter is a 12-bit unsigned value that increments per ID allocation. This provides for 4096 unique IDs per millisecond, or 4 million IDs per second.
- The node number is a 10-bit unique identifier for the Postgres instance inside a global cluster. This value is set with the
snowflake.nodeGUC in thepostgresql.conffile.
Snowflake sequences let you:
- add or modify data in different regions while ensuring a unique transaction sequence.
- preserve unique transaction identifiers without manual/administrative management of a numbering scheme.
- compare ID generation times across nodes. Clock skew and the interval between ID generation and commit can affect the observed order.
Snowflake sequences also alleviate concerns that network lag could disrupt sequences in distributed transactions.
A Snowflake sequence is made up of a timestamp, a counter, and a unique node identifier; these components are sized to ensure over 18 trillion unique sequence numbers. The extension supports versatile commands and functions that simplify creating a new Snowflake sequence or converting an existing sequence.
Continue reading
- Changelog
- Converting a PostgreSQL Sequence to a Snowflake Sequence
- Creating a Snowflake Sequence in a New Cluster
- Reviewing Sequence Definitions in your Table Meta-data
- Snowflake Functions
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.4.1 - Changelog
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
All notable changes to the Snowflake extension are documented here.
2.6.1
Changed
- Version bump to 2.6.1 (no catalog changes). Includes release packaging and CI updates since 2.6.0.
2.6.0
Added
- Added support for Postgres 19
2.5.0
Added
- PG18 support: added a PG18 test configuration and adjusted the Docker build to skip LLVM bitcode compilation on PG18.
Changed
- Adopted three-digit (
MAJOR.MINOR.PATCH) versioning. The extension version is now2.5.0.
Fixed
- Fixed dump/restore of snowflake-converted sequences.
convert_sequence_to_snowflake()previously leftMAXVALUEat(old last_value + 1), butsnowflake.nextval()bypassesMAXVALUEand writes snowflake-sized values, sopg_dumpcould emit asetval()that failed to restore. Sequences are now converted withAS bigint MAXVALUE 9223372036854775807, and sequences converted by earlier versions are auto-repaired on upgrade. (SUP-140) - Fixed the SQL command used to convert sequences to Snowflake.
Security / CI
- Pinned GitHub Actions to full commit SHAs to harden against supply chain attacks.
- Removed
shell=Trueand shell-injection risks from test runner and helper subprocess calls; useshlex.split()for correct argument tokenization. - Fixed a SQL injection warning and a missing parameter in
execute_sqlite_query, and suppressed Bandit B603 warnings on internal test helper subprocess calls. - Fixed the Dockerfile
ARGhandling for newer BuildKit versions. - Updated the copyright year to 2026.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.4.2 - Converting a PostgreSQL Sequence to a Snowflake Sequence
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
You cannot directly create a snowflake sequence; you must first create a sequence in Postgres and then convert it. Sequences are created explicitly with the CREATE SEQUENCE command but are also implicitly created by GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY table columns or SERIAL and BIGSERIAL columns. GENERATED AS IDENTITY is the recommended ANSI SQL method.
You can use the snowflake.convert_sequence_to_snowflake() function to convert individual sequences to snowflake sequences. Note that this converts the sequence definition; existing values in a sequence column will not change. The command syntax in SQL is:
`SELECT snowflake.convert_sequence_to_snowflake('sequence_name');`
Where
sequence_name is the name of a sequence.
There are a number of ways to return a list of sequences. One way is to use the Postgres psql client to execute the following command:
Another way is to query metadata catalog information directly in psql or another SQL editor.
The second command will include data type information, which is useful for learning which sequences will be converted to the BIGINT data type (64 bits).
Example: Converting an Existing Sequence
The example that follows demonstrates using the psql command line to convert a sequence; in this example, we are using a table named orders that has three columns; the last column is a sequence named id:
After creating the table, we insert data into the orders table. We only need to provide content for the first two columns, since the sequence definition keeps track of the value of the third column and adds it as needed:
When we select the rows from our table, we can see the sequence numbers in the id column:
To convert the sequence definition for the orders table to use Snowflake sequences, invoke the following command in psql or another SQL editor:
The conversion process modifies the sequence definition to use Snowflake sequences, but does not update existing rows. If we reconnect with psql and add new rows to the table, the new row’s id will be a Snowflake sequence:
In the query results that follows, you can see the unformatted sequence values in the id column, and the same information in the format column, formatted with the snowflake.format(id) function. The rows added before the conversion to Snowflake sequences show a fixed timestamp of 2022-12-31 19:00:00-05, while the Snowflake sequences have a unique id and timestamp.
Original entries in the table display a Postgres sequence, while entries made after the conversion display Snowflake sequences:
INCREMENT and Caching
Within the same millisecond, snowflake will allow a maximum of 4096 values. Some frameworks like the ORM framework Hibernate may be configured to try to fetch a sequence value, cache and assign a range by using an INCREMENT value for the sequence. Snowflake sequences honor the increment value, but you should not use a value greater than 4096. If you would like to change the increment value, use ALTER SEQUENCE <seq_name> INCREMENT <increment_value> NO MAXVALUE.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.4.3 - Creating a Snowflake Sequence in a New Cluster
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
Before you use Snowflake sequences, each node in your cluster must have a unique snowflake.node identifier. The value ranges from 1 to 1023, and it must be distinct on every node in the cluster.
Setting snowflake.node in a managed deployment
A pgEdge deployment assigns snowflake.node for you, deriving the value from each node’s place in the cluster:
- the Control Plane sets
snowflake.nodefrom the node ordinal. - pgEdge Helm charts derive
snowflake.nodefrom each node name. - pgEdge Ansible playbooks set
snowflake.nodefrom the node zone.
When you deploy with one of these methods, no further action is needed to configure the node identifier.
Setting snowflake.node manually
For a self-managed or from-source installation, set the value yourself. Use ALTER SYSTEM to assign a unique node number, then reload the server so the change takes effect. The following example sets the node identifier to 10:
You can also add the parameter to the postgresql.conf file directly. The following line identifies the host as node 11:
After you edit postgresql.conf, reload the server for the change to take effect. You can reload from psql:
You can also reload the server with pg_ctl:
Once Snowflake is configured, you can begin to use Snowflake sequences by first converting them from Postgres sequences.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.4.4 - Reviewing Sequence Definitions in your Table Meta-data
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
If you query the table meta-data before performing a sequence conversion with the \d+ orders command, the PostgreSQL sequence is defined in the Default column:
After performing a conversion, the \d+ table_name command shows a Default value of snowflake.nextval('orders_id_seq'::regclass):
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.4.5 - Snowflake Functions
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
You can query the following Snowflake functions at the psql command line to return useful information about tables that use Snowflake sequences.
snowflake.nextval([sequence regclass])
Generates the next Snowflake in the specified sequence. If no sequence is specified, the internal, database-wide sequence snowflake.id_seq is used. For example, the following query returns the next number in the orders_id_seq sequence:
snowflake.currval([sequence regclass])
Returns the current value of the specified sequence. This value is undefined until the function snowflake.nextval() has been called for the sequence in the current session. For example, the following query returns the current value of the orders_id_seq sequence:
snowflake.get_epoch(snowflake int8) Returns the Unix timestamp in seconds as a NUMERIC with three decimal places. Snowflake IDs store milliseconds relative to 2023-01-01 UTC. The function adds the offset from the Unix epoch before returning the value. The example returns 1704996539.845:
You can use the to_timestamp(snowflake.get_epoch(<value>)) function to convert the epoch into a timestamp. For example:
In v2.6.1, bits 12–21 of 136169504773242881 encode node 0 and the low 12 bits encode count 1. For this ID, get_node() returns 0, get_count() returns 1, and format() reports "id": 0 and "count": 1. The upstream transcripts below show different values. Pinned bit layout
snowflake.get_count(snowflake int8) Returns the count part of the given Snowflake as int4 value; count resets to 0 for each new millisecond. For example:
snowflake.get_node(snowflake int8) Returns the node number encoded in the ID. It reflects the snowflake.node setting at allocation time. Decoding does not read the issuing host’s configuration file. The historical upstream transcript follows.
snowflake.format(snowflake int8) Returns a jsonb object of the given Snowflake in the form: {"id": 1, "ts": "2023-10-16 17:57:26.361+00", "count": 0}. For example:
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4.5 - SafeSession
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
The English source is v1.1, pinned at d66225fcceef. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
pgEdge SafeSession is a PostgreSQL extension that enforces read-only sessions for specified database roles. It provides defense-in-depth protection using executor and utility hooks to block all write operations, DDL, and other potentially dangerous commands.
Features
- Block DML (INSERT, UPDATE, DELETE, MERGE) for restricted roles
- Block DDL (CREATE, ALTER, DROP, TRUNCATE, etc.)
- Block COPY FROM and COPY TO PROGRAM
- Block GRANT/REVOKE, VACUUM/ANALYZE
- Block volatile C-language function execution (which can bypass the executor)
- Prevent tampering with read-only GUC settings
- Role membership inheritance: members of restricted roles are also restricted
- Superuser exemption: superusers are never restricted, even if they are members of restricted roles
- Session-user anchored: SET ROLE cannot escape restrictions
- Configurable protection layers via GUCs
Requirements
- PostgreSQL 14 or later
- Must be loaded via
shared_preload_libraries
Installation
Build from Source
Configure PostgreSQL
Add the extension to shared_preload_libraries in
postgresql.conf:
Restart PostgreSQL for the change to take effect.
Create the Extension (Optional)
The extension is fully functional once loaded via
shared_preload_libraries. Running CREATE EXTENSION is
optional, but registers it in the pg_extension catalog
so it appears in \dx output:
Configuration
All GUCs are SUSET parameters (only superusers can modify them).
pgedge_safesession.roles
A comma-separated list of PostgreSQL role names whose sessions will be restricted to read-only operations.
Any session authenticated as one of these roles, or as a role that is a member of one of these roles, will be restricted to read-only operations.
pgedge_safesession.block_dml
Default: on
Block INSERT, UPDATE, DELETE, and MERGE for restricted roles.
pgedge_safesession.block_ddl
Default: on
Block DDL and other utility commands for restricted roles. Uses a whitelist approach: only explicitly allowed statements (SELECT, EXPLAIN, transaction control, SET, SHOW, LISTEN/NOTIFY, cursors, DO blocks) can execute.
pgedge_safesession.block_c_functions
Default: on
Block C-language function execution for restricted roles. By default, only volatile C functions are blocked. IMMUTABLE and STABLE C functions (such as PostGIS geometry operations or pgvector distance operators) are allowed since they promise no side effects.
pgedge_safesession.block_all_c_functions
Default: off
When enabled, blocks all C-language functions
regardless of volatility. This provides stricter
protection at the cost of blocking read-only extension
functions. Only applies when block_c_functions is on.
What is Blocked
For restricted sessions (with all protections enabled), the following operations are blocked:
- DML: INSERT, UPDATE, DELETE, MERGE (PostgreSQL 15+),
including data-modifying CTEs
(
WITH c AS (INSERT ... RETURNING ...) ...) - DDL: CREATE, ALTER, DROP, TRUNCATE, and all other schema modification commands
- COPY FROM: data import (COPY TO is allowed)
- COPY TO PROGRAM: program execution via COPY
- CREATE TABLE AS / SELECT INTO: table creation from
queries, including their
EXPLAIN ANALYZEforms - EXPLAIN ANALYZE of a writing statement: it executes the statement, so it is treated as a write
- GRANT / REVOKE: privilege modifications
- VACUUM / ANALYZE: maintenance commands
- CHECKPOINT: forces heavy I/O and emits WAL
- Two-phase commit: PREPARE TRANSACTION, COMMIT PREPARED, ROLLBACK PREPARED
- Side-effecting functions: volatile functions in
untrusted languages (C, internal, or an untrusted PL
such as
plpython3u), plus any volatile built-in (pg_catalog) function that is not on a small allow-list of built-ins confirmed to have no observable side effect (random(),clock_timestamp(), and similar). A volatile built-in is blocked by default; only functions verified harmless are exempted, so a new PostgreSQL release that adds a side-effecting built-in is blocked automatically. ADOblock orCALLin an untrusted language is blocked for the same reason. Arguments count as part of the statement, so a blocked function is rejected whether it is called directly, passed as aCALLargument, or passed as anEXECUTEparameter (including throughEXPLAIN EXECUTEandCREATE TABLE AS ... EXECUTE). A function reached only indirectly, through a view body, a row-level security policy’sUSING/WITH CHECKqual, or a domainCHECKconstraint, is rejected the same way as a direct call. For a domain this holds however the coercion that runs the constraint is reached: a cast, a prepared statement’s declared parameter type, a parameter bound over the extended query protocol, a PL/pgSQL variable’s declared type, or a function’sRETURNStype. - Fast-path function calls: the protocol behind libpq’s
PQfn, which the large-object client API is built on. It bypasses the parser and planner entirely, so the same function policy is applied to it directly. - Exclusive locks: LOCK TABLE with modes above ROW SHARE
- GUC tampering: any attempt to relax
transaction_read_onlyordefault_transaction_read_only, whether by setting one of them to a false value, by RESET or SET TO DEFAULT, or through SET TRANSACTION READ WRITE and SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE
What is Allowed
- SELECT: all read queries, including those using WHERE clauses, aggregates, and built-in functions
- EXPLAIN: query plans. Plain EXPLAIN only plans and is always allowed; EXPLAIN ANALYZE is allowed only when the statement it runs does not write.
- Transaction control: BEGIN, COMMIT, ROLLBACK, SAVEPOINT
- SET / RESET: non-protected GUC changes (e.g., work_mem)
- SET TRANSACTION: ISOLATION LEVEL and READ ONLY (tightening the transaction is allowed)
- Asserting read-only: setting
transaction_read_onlyordefault_transaction_read_onlyto on, which asks for the state that is already enforced. Clients that assert read-only on every connection they open, such as a connection pool with writes disabled, therefore work against restricted roles. - SHOW: display settings
- LISTEN / NOTIFY: notification channels
- Cursors: DECLARE, FETCH, CLOSE
- Connection-pooler resets: DISCARD ALL, DISCARD PLANS, and RESET ALL (they cannot relax the restriction, which is re-asserted per statement)
- DO blocks and CALL: in a trusted language (PL/pgSQL, SQL, …); any write inside is caught by the executor hook
- PL/pgSQL and SQL functions: read-only functions execute normally; any write attempt inside a function is caught by the executor hook, and a blocked function called from a SQL function body is rejected before the call runs
- IMMUTABLE/STABLE functions, and harmless volatile
built-ins such as
random()andclock_timestamp()
Security Model
Session User is the Anchor
The session user identity (set at connection time) is the
primary check. Even if a restricted user executes
SET ROLE to assume another role, the session user remains
restricted. This prevents bypass via role switching.
Superuser Exemption
Superusers are never restricted, even if they are members of a restricted role. The superuser check is based on the session user, so SECURITY DEFINER functions owned by superusers cannot bypass restrictions when called from a restricted session.
SECURITY DEFINER Functions
A SECURITY DEFINER function temporarily changes the effective user to the function owner. However, SafeSession checks the session user, not the effective user. This means a restricted session cannot use a SECURITY DEFINER function owned by a privileged user to perform writes.
Role Membership Inheritance
If role app_reader is listed in
pgedge_safesession.roles, then any role that is a member
of app_reader is also restricted. Membership is tested
with PostgreSQL’s is_member_of_role_nosuper(), so it
follows actual grants only.
The distinction matters because PostgreSQL otherwise reports a superuser as a member of every role in the database, with no grant behind it, which is the right answer for a privilege test and the wrong one here. Any mechanism that briefly makes the current user a superuser whilst the session user is not, such as a SECURITY DEFINER function owned by a superuser or an extension like supautils elevating a privileged role for a single command, would otherwise appear to be acting as a member of every restricted role and be blocked. Enforcement still anchors on the session user, so such elevation is not a way out of the restriction either: a restricted session stays restricted inside a superuser-owned SECURITY DEFINER function.
Restriction Changes and Cached Plans
Side-effecting function calls are detected when a statement or expression is parsed, and again when it is planned (to catch a function reached only through a view body or an RLS qual, which are substituted during query rewrite, after parse analysis), rather than when it is executed, so a plan cached before a session became restricted would otherwise be replayed without either check running again. That matters because a session can become restricted part-way through its life: the roles list can be edited and the configuration reloaded, or a role can be granted membership of a listed role, whilst sessions are open.
Becoming restricted is therefore treated as an invalidation
event, and the session’s cached plans are discarded exactly
as DISCARD PLANS does, so that everything is re-analysed
under the new state. This covers prepared statements and the
plans PL/pgSQL caches for its expressions alike. Plans built
whilst a session was restricted are left alone when the
restriction is lifted, since they have already been checked.
Belt-and-Suspenders
For every restricted session SafeSession also forces the
current transaction read-only (XactReadOnly), re-asserted
on each statement. This provides an additional layer of
protection that cannot be turned off: even if something
bypasses the hooks and attempts direct heap writes,
PostgreSQL’s own internal read-only checks will catch it.
The setting is applied without writing any session-level
GUC, so it leaves no state behind and does not interfere
with connection poolers.
Known Limitations
- The allow-list of harmless volatile built-in functions is deliberately conservative rather than exhaustive: a volatile built-in that is actually harmless but missing from the list is blocked anyway, which can surface as a restricted session being refused a read-only built-in call that a future release should add to the list. This is a usability trade-off in favour of failing closed: a newly added side-effecting built-in is blocked by default rather than silently allowed. A volatile function in a trusted language is allowed to run, and any write it performs is caught at execution instead.
- Enforcement anchors on the session user. A superuser can
still use
SET SESSION AUTHORIZATIONto become a restricted role (that is how the restriction is entered); this is by design and is not a bypass. - The roles list must be set from the server configuration
(
shared_preload_librariesis required, and the roles are normally set inpostgresql.confor withALTER SYSTEM). Setting it only for a single session withSETwould be undone by that session’sDISCARD ALLorRESET ALL. - SafeSession and Spock both install executor, utility, and planner hooks. They chain correctly, but if both are deployed the interaction has not been exhaustively tested.
- A blocked function is caught either when it appears in a
statement’s parse tree or when the executor compiles it as
part of an expression. A function PostgreSQL calls directly
through
fmgr, without compiling an expression around it, is seen by neither: a type’s own input and output functions, and an index access method’s support functions, are the cases that arise in practice. Reaching one requires a type or operator class that somebody else defined, since a restricted role cannot create either.
Example
Licence
See the Licence page for details.
Continue reading
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
4.4.5.1 - Changelog
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
All notable changes to the pgEdge SafeSession will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[1.1] - 2026-11-06
Changed
- Release workflow installs the repository client certificate before configuring the pgEdge package repositories, and verifies that the key matches the certificate, that the certificate and its issuer are within their validity periods, and that the chain issuer is the expected one
- Release workflow fails if the repository rewrite fails
- Release workflow pins the builder action by commit SHA
- Packaging no longer builds for Debian bullseye
- Packaging defaults now target v1.1
- Removed pgEdge Labs branding from the README and documentation landing page
[1.0] - 2026-08-25
Added
SECURITY.md, documenting how to report a vulnerability
[1.0-beta1] - 2026-08-21
Added
Initial release of pgEdge SafeSession
GUC
pgedge_safesession.roles(SUSET) to specify restricted rolesExecutorStart hook to block DML (INSERT, UPDATE, DELETE, MERGE) and C-language function execution
ProcessUtility hook to block DDL, COPY FROM, GRANT/REVOKE, VACUUM/ANALYZE, exclusive locks, and GUC tampering
Session-user anchored role checking: SET ROLE cannot escape restrictions
Superuser exemption: superusers are never restricted
Role membership inheritance via
is_member_of_role()Belt-and-suspenders: automatic
default_transaction_read_only = onfor restricted sessionsSECURITY DEFINER bypass prevention: session user is always checked regardless of effective user
Comprehensive regression test suite covering:
- Basic DML blocking
- SET ROLE bypass prevention
- PL/pgSQL and SQL function enforcement
- DDL blocking
- COPY FROM/TO handling
- CREATE TABLE AS / SELECT INTO blocking
- SECURITY DEFINER function enforcement
- Role membership inheritance and superuser exemption
Configurable protection layers via new SUSET GUCs:
block_dml: toggle DML blocking (default: on)block_ddl: toggle DDL blocking (default: on)block_c_functions: toggle C-language function blocking (default: on)block_all_c_functions: block all C functions regardless of volatility (default: off)
COPY TO PROGRAM blocking for restricted sessions
SET TRANSACTION READ WRITE blocking for restricted sessions
New regression tests for advanced attack vectors (PREPARE/EXECUTE, DO blocks, aggregates, WHERE clauses, SET TRANSACTION)
New regression tests for GUC toggle behavior
Changed
- C-language function blocking now only blocks VOLATILE
C functions by default. IMMUTABLE and STABLE C functions
(e.g., PostGIS geometry operations, pgvector distance
operators) are allowed. Use
block_all_c_functions = onto restore the previous behavior of blocking all C functions. - Built-in function blocking now denies any VOLATILE
built-in by default, allowing only a curated list of
built-ins confirmed to have no observable side effect
(e.g.,
random(),clock_timestamp()). Previously, built-ins were allowed by default and blocked only if their name matched a fixed denylist, regardless of volatility. PostgreSQL ships hundreds of volatile built-ins, and the old denylist covered only a small fraction of them.
Fixed
The fixes extend read-only policy enforcement to indirect function calls, transaction state and index maintenance. Role membership changes trigger checks on cached plans. After updating, test read-only pool settings, prepared queries and monitoring views with the restricted role, and review its grants.
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
4.4.5.2 - LICENCE()
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
The PostgreSQL License
Copyright (c) 2025 - 2026, pgEdge, Inc.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL pgEdge, Inc. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF pgEdge, Inc. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pgEdge, Inc. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN “AS IS” BASIS, AND pgEdge, Inc. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
4.4.6 - About this site
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This independent PGSTY community edition collects pgEdge extension documentation, centered on Spock, with LOLOR, Snowflake, and SafeSession.
4.4.6.1 - Sources and attribution
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Versions and sources
The English edition was updated on November 21, 2026. Spock follows a pre-release tag; SafeSession and Snowflake follow release tags; LOLOR follows unreleased 1.3.0 development. Chinese covers all four component snapshots.
| Extension | English source | Channel |
|---|---|---|
| spock | d05e2e2b6a82 | v6.0.0-beta.2; pre-release |
| Spock 5.0 maintenance supplement | e710faa6fe21 | v5.0.15-rc.2 release notes and configuration changes |
| lolor | 1548836b0df0 | 1.3.0 development; latest stable v1.2.3 |
| safesession | d66225fcceef | v1.1 |
| snowflake | 9506e1bd5c1f | v2.6.1 |
Copyright and adaptations
Original notices credit pgEdge, Inc., the PostgreSQL Global Development Group, and The Regents of the University of California. Spock’s LICENSE and COPYRIGHT files use different year ranges, as do Snowflake’s notices. Each file is preserved separately and verbatim.
Adaptations include MkDocs admonition conversion, local link rewriting, stable heading IDs, navigation, Chinese translations, and editorial guides. Commands, conditions, limitations, and warnings retain their upstream meaning. No publication date is invented for undated material; snapshot_date in the manifest refers only to the pinned commit.
Every imported page links to its exact source commit. Credits are carried into HTML, print, Markdown, and LLMS outputs. See the complete license texts.
Chinese translations
The community edition has 118 English/Chinese page pairs. This review added 66 Chinese pages, revised all 32 earlier GLM-assisted drafts against the English edition, and restored the article text on four Chinese section indexes. The SafeSession manual and changelog and the LOLOR release notes describe security issues from the administrator’s perspective, including affected behavior and fixes. The import manifest records the scope of the AI-assisted self-review for each page.
Independence
This community site does not imply official pgEdge endorsement or stewardship of the upstream extensions. Product and company names identify their respective sources.
4.4.6.2 - License texts
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The extension documentation is used under each repository’s PostgreSQL License. The files below preserve the original bytes, copyright years, and disclaimers. Scripts and configuration inherited from the former pgEdge community site retain MIT terms; OINK uses Apache-2.0. The source edition carries the PG.CENTER attribution notice. For additions in this edition, see the Mimus license.
spock
lolor
safesession
snowflake
4.4.6.3 - Maintenance and coverage
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Reading and feedback
Search for function names, settings, or terms. Page controls provide light/dark modes, Paper / Slate / Ink / Terminal presets, Markdown, and print views. Paired translations support Duo View.
This site maintains documentation, not pgEdge software support. Report software issues to the relevant upstream repository. Documentation updates compare the pinned snapshot with a new revision before updating the import manifest.
Coverage
The four pinned upstream manuals have 118 English/Chinese page pairs, including section indexes, function references, release notes and source notices. Technical examples were compared with the English Markdown. Deployment procedures have not been exercised against a database in this documentation review.
Known upstream issues
- Step 3 of the two-node tutorial asks readers to edit
pg_hba.conf, but its example path ends inpostgresql.conf. Authentication rules belong in the instance’s actualpg_hba.conf;SHOW hba_file;reports its location. - The limitations page lists
CREATE TABLE...AS...under statements that are not replicated, then says that it is replicated. This contradiction is preserved from the snapshot; verify behavior for the version in use.
These issues occur in the pinned source snapshot and have not been submitted upstream by this site. Editorial notes are identified separately from the source text.
5 - MySQL
A MySQL client can create a table on TCP port 3306 and a PostgreSQL client can read it on port 5432. Mimus 19.0.1 runs PostgreSQL 19.0 with the OpenHalo protocol hooks and the standalone pg_mysql 1.0 extension. The two connections share tables, roles and transactions committed by other sessions. Each uses its own wire protocol and SQL dialect.
Which database am I using?
All MySQL connections enter the PostgreSQL database selected by mysql.database (default postgres). Inside it, a MySQL “database” is a PostgreSQL schema. With the example settings, mysql … app selects schema app and psql -d postgres sees its table as app.notes. A MySQL USE changes the selected schema on that connection.
First connection
Install and connect takes you from matching source trees to an ordinary login, an insert and a native PostgreSQL read. For additional hosts and existing services, see server configuration and authentication.
Before moving an application
Start with the columns that identify rows and the transactions that read them. An unsigned 64-bit key can exceed the supported range, and two plain reads in a writable REPEATABLE READ transaction can see different commits. Check your source values and replay one complete transaction with your own driver. SQL and types · Tested drivers · Migration and recovery · Limits and troubleshooting
How it works
OpenHalo contributed the protocol and grammar. Mimus pairs the 300/301 kernel changes with a separately built extension. MySQL kernel patches · Source versions and credits
Use a separate instance for applications that need the SQL Server protocol. For additional dialect reference see the PG.CENTER OpenHalo manual. Instance configuration · OpenHalo reference
5.1 - Install and connect
This walkthrough uses a fresh Linux instance, a local PostgreSQL administrator and a MariaDB mysql client. Install the OpenSSL command-line tool for the certificate step. Both ports must be free. At the end, the application owns one schema and can create and read its own tables. The TLS certificate below is for this loopback example.
Install the matching server and extension
This example builds the 19.0.1-r4 server and MySQL extension from two local repositories, pgsty/mimus in mimus/ and pgsty/pg_mysql in pg_mysql/. The candidate branches are pending upload. Run the commands in Bash from their common parent directory. Have the administrator prepare a fresh /usr/mimus-19 prefix writable by the build user. On Debian 13 the build uses build-essential, git, tar, bison, flex, perl (including FindBin), pkg-config, libicu-dev, libssl-dev, libreadline-dev and zlib1g-dev.
Expect PostgreSQL 19.0 and the installed control file. If the exact kernel is already installed, set PREFIX to that installation and skip the kernel archive, configure and make steps. The extension uses its installed server headers and PGXS through bin/pg_config. The server account needs read and execute access to the installation. Kernel and source identities
Initialize, preload and restart
In a shell running as OS user postgres, choose an unused data directory. The native socket uses peer authentication and the TCP loopback entries use SCRAM. Start PostgreSQL once, then enable the second listener. On an existing service, preserve its other preload entries and use its usual restart command.
Expect pg_mysql. SQL installation is per PostgreSQL database. Preloading is cluster-wide and takes effect at restart.
Prepare the database and role in psql
From the same shell, run psql -X -v ON_ERROR_STOP=1 -d postgres. As the database superuser, enter the following. At the password prompt, choose a password for the new role. The fresh database grants CONNECT to PUBLIC; if you revoked it, grant CONNECT ON DATABASE postgres to app_user.
Expect extension version 1.0. Earlier development builds, including unified RC2, also report 1.0. To move an application from one of those builds, install into a fresh cluster and restore its application schema and data. Check direct calls to private helper functions before restoring views. Schema ownership gives app_user the rights required by this example.
Write with mysql and read with psql
In the same OS shell, connect over TCP as the ordinary database role. Supply the password just set. If the client runs under another OS account, give it a readable copy of the public certificate and adjust the CA path.
At the mysql prompt, run these statements in schema app.
With the default configuration the first query returns app, 5.7.32-log and mimus. The TLS check returns 1, and the last query returns one row, 1 | hello. Type exit, then cross-check on the native port as the database administrator.
Connect from another host
Configure the intended interface, HBA rule, trusted CA and server identity before opening the listener to the application. Oracle MySQL and MariaDB use different TLS option names. Authentication and TLS
5.2 - Server configuration and authentication
SQL object index
Look up a function overload, operator, type or MySQL metadata relation by its installed signature. pg_mysql 1.0 object index
Inspect the running server
Use native psql as the administrator. These are the 14 PostgreSQL settings registered by pg_mysql 1.0. boot_val is the compiled default, setting the effective value in this backend. A MySQL @@ variable belongs to a different namespace. For example, SELECT @@max_allowed_packet reports the packet limit, while the PostgreSQL configuration entry has the mysql. prefix.
Cluster settings requiring restart
| Parameter | Default and accepted values | Effect |
|---|---|---|
mysql.listener_on | on, boolean | Enables the MySQL TCP listener when the module is preloaded. Set off to stop accepting connections on this protocol at the next start. |
mysql.port | 3306, integer 0–65535 | 0 disables the listener. The native PostgreSQL port defaults to 5432. |
mysql.listen_addresses | Unset. Comma-separated host names or IP addresses, or * | Unset or empty inherits PostgreSQL listen_addresses. An empty inherited list disables TCP. Bind a specific interface for application access. |
mysql.auth_cache_size | 1024, integer 0–1000000 entries | Shared fast-auth cache capacity in users. At 0 each password login uses full authentication. |
mysql.rsa_private_key_file | mysql_rsa_private_key.pem, file path | RSA private key for full authentication without TLS. Relative paths start at the data directory. An OpenSSL build generates a missing key. An empty path disables RSA key loading. |
mysql.auto_create_extension | on, boolean | On the first authenticated MySQL superuser connection, install the SQL extension if missing, before reporting login success. An ordinary user needs it installed already. Standbys and binary upgrade suppress automatic installation. |
Cluster settings applied by reload
Edit the active configuration and run SELECT pg_reload_conf(); in an administrative PostgreSQL session. Reconnect to verify handshake settings and the target database.
| Parameter | Default and accepted values | When a client sees it |
|---|---|---|
mysql.database | postgres, PostgreSQL database name | New connections bind to this database. Create it and install the extension there first. Existing connections stay in their original database. |
mysql.compat_version | 5.7.32-log, string | Reloadable major.minor.patch with an optional -suffix. The handshake, VERSION() and @@version return the full string. The numeric part determines the handshake collation and which versioned comments execute. An invalid value leaves the active version in effect on reload. |
mysql.default_authentication_plugin | caching_sha2_password or mysql_clear_password, default the former | Advertised at the next login. The server checks the role’s PostgreSQL credentials. |
mysql.max_allowed_packet | 67108864, integer 1024–1073741823 bytes | Limit for an incoming MySQL message or accumulated prepared-statement long data. Read the effective limit with SELECT @@max_allowed_packet. |
mysql.deadlock_timeout | 50ms, 0–2147483647 ms | Dynamic default for MySQL sessions. A positive value also defaults log_lock_waits to off. Zero inherits PostgreSQL defaults. Explicit PostgreSQL server, role, database and session settings take precedence. |
If reloading mysql.compat_version changes which ? placeholders occur in an executable comment, the next execution of that prepared statement returns error 1615 (HY000). Prepare it again and bind the parameters for the new version. Statements with the same parameter positions can continue on the existing connection.
Session settings
| Parameter | Default and accepted values | Scope |
|---|---|---|
mysql.parser | mysql (default), postgres; postgresql is an alias | Selects the grammar for subsequent queries arriving over the MySQL protocol. The connection still returns MySQL packets. Native connections use the PostgreSQL parser. |
mysql.statement_rollback | on, boolean | Inside a MySQL transaction, an ordinary statement error rolls back to a hidden savepoint. With off an error can abort the transaction. Deadlocks and serialization failures require a full transaction retry. |
mysql.default_collation | case_insensitive (default), string. Also accepts case_sensitive, ignore_accents, MySQL collation names and default or empty for database default | Default used by subsequent MySQL DDL for character columns without an explicit column or table collation. MySQL names follow the dialect mapping. Existing columns keep their definitions. |
An application can set session options for its connection. For example, in mysql, switch parsers, issue PostgreSQL SQL over the same socket, then switch back.
Admit a client
Once the listener is up, authentication depends on the target PostgreSQL database, role, TLS and HBA match. Configure passwords, HBA and TLS
Where to find the schemas
Connect with native psql to the database named in mysql.database. Application schemas sit alongside the extension schemas. A connection to a different native database has its own catalogs and installed extensions.
5.2.1 - Password authentication and TLS
Password authentication
Authenticate as a PostgreSQL role with LOGIN and CONNECT on the target database. PostgreSQL evaluates pg_hba.conf using that database, role, transport and client address. The first matching rule wins. MySQL schema selection and its privileges come later. The listener handles reject, trust, password, md5, scram-sha-256 and cert; other HBA authentication methods return an unsupported-method error. PostgreSQL HBA matching
Full and cached login
With MariaDB CLI 11.8.9 over TLS, a trust rule accepts a passwordless login. Supplying a password on that path produces error 1047. For a password-based login, use a matching scram-sha-256 HBA entry.
With the default plugin, a cache miss requires full authentication over TLS or an RSA-OAEP password exchange on a non-TLS connection. The server verifies the password using the role’s PostgreSQL verifier. A scram-sha-256 HBA entry requires a SCRAM verifier. Later connections can use the fast challenge/response path. Changing the role password invalidates the old cached credential. RSA protects the password exchange only. To protect queries and rows in transit, use TLS. For a legacy client requiring mysql_clear_password, require TLS by HBA and enable that plugin on the client.
Require and verify TLS
Configure an OpenSSL-enabled server with ssl=on, a server certificate and private key (ssl_cert_file, ssl_key_file). The certificate must cover the name or IP used by the client. For example, put these rules above broader host rules for the application subnet, substituting your actual CIDR. They apply to this role and PostgreSQL database on both TCP protocols. Reload HBA after editing.
With Oracle MySQL use --ssl-mode=VERIFY_IDENTITY --ssl-ca=ca.pem. With MariaDB use --ssl-verify-server-cert --ssl-ca=ca.pem. Connect to the certificate’s host and check the TLS status of this backend in the MySQL client.
5.2.2 - pg_mysql object index
All counts in this index come from one fresh installation of pg_mysql 1.0 on Mimus 19.0.1. Its source matches pg_mysql commit 0d51adc. For changes between this snapshot and r4, see the source comparison through 1e631f9.
Look up a function by name, match an operator and its operands, or find the PostgreSQL object behind an information_schema view. Each signature has a permanent page anchor.
SQL objects
| Category | Entries | Look up |
|---|---|---|
| Schemas | 4 | Namespace names as seen from PostgreSQL and MySQL. |
| Types and domains | 97 | 3 binary base types, 23 domains and 71 enumerations. |
| Collations | 5 | Choose a collation for character comparisons or check a column’s ordering dependency. |
| Casts | 88 | 80 assignment and 8 implicit casts. |
| Functions | 1859 | Find a function by name, then choose the overload that matches the argument types. |
| Aggregates | 7 | SQL aggregates, their input types and the result produced for a group. |
| Operators | 665 | Match the symbol and both operand types. NONE in the left slot denotes a unary prefix operator. |
| Metadata views | 20 | Query the MySQL name through the dialect or the PostgreSQL name from psql. SHOW helpers and the pending foreign key view are identified by their purpose. |
| Metadata tables | 180 | These physical tables provide compatibility metadata. Seed counts describe a fresh install. Performance Schema tables start empty. |
| Index access method, classes and families | 51 | 1 access method, 27 operator classes and 23 operator families. |
Index and constraint dependencies
| Category | Entries | Look up |
|---|---|---|
| Operator family members | 168 | 127 strategy operators and 41 support function registrations. |
| Table indexes | 119 | 61 explicit indexes and 58 indexes backing primary keys. |
| Primary keys and domain checks | 71 | 58 primary keys and 13 domain checks. |
| NOT NULL in metadata schemas | 341 | Column constraints in the compatibility catalogs outside Performance Schema, ordered by the owning table’s initial. |
| NOT NULL in performance_schema.events_* | 481 | Catalog constraint names and column definitions for Performance Schema event tables. |
| NOT NULL in other performance_schema tables | 589 | Catalog constraint names and column definitions for the remaining Performance Schema tables. |
Version and counting rules
Source links point to the files and lines used for this installation. Generated definition links to the SQL statement that created the object. C links to the C implementation of the SQL entry point.
The 4,745 entries in this installation include 2,976 direct extension members and 1,769 dependent objects (family entries, table indexes and constraints). PostgreSQL also records 497 derived types as extension members. These comprise one row type for each of the 180 tables and 20 views, and one array type for each of those 200 row types and the 97 declared types. Look up a row type under its relation’s name, or an array under its element type. Counts exclude those derived types. Each overload counts once. A type’s forward declaration and completed definition share one entry.
Seed rows are documented with their tables. PUBLIC receives schema USAGE and SELECT on the extension tables and views, plus REFERENCES on mysql.dual. Restricted function privileges are noted with the relevant function. Relation grants
5.2.2.1 - Schemas
Namespace names as seen from PostgreSQL and MySQL.
| Signature | Purpose | Source definition |
|---|---|---|
mys_informa_schema | MySQL information_schema metadata. | SQL |
mys_sys | Backing schema for MySQL sys. | SQL |
mysql | Dialect functions, operators, types and compatibility relations. | SQL |
performance_schema | Table shapes used by Performance Schema queries. | SQL |
5.2.2.2 - Types and domains
SQL types used by column declarations, binary literals and metadata tables.
Binary base types
| Signature | Purpose | Source definition |
|---|---|---|
mysql.binary_n | Length-qualified fixed-width BINARY storage. | Generated definition |
mysql.hexlit | MySQL hex/bit literal with byte-string and numeric interpretations. | SQL |
mysql.varbinary_n | Length-qualified variable-width VARBINARY storage. | Generated definition |
Domains
| Signature | Purpose | Source definition |
|---|---|---|
mysql."bigint signed" | Domain over bigint | SQL |
mysql."bigint unsigned" | Domain over bigint · CHECK ((0 <= VALUE)) | SQL |
mysql."binary" | Domain over bytea | SQL |
mysql."int signed" | Domain over integer | SQL |
mysql."int unsigned" | Domain over bigint · CHECK (((0 <= VALUE) AND (VALUE <= ‘4294967295’::bigint))) | SQL |
mysql."mediumint signed" | Domain over integer · CHECK (((’-8388608’::integer <= VALUE) AND (VALUE <= 8388607))) | SQL |
mysql."mediumint unsigned" | Domain over integer · CHECK (((0 <= VALUE) AND (VALUE <= 16777215))) | SQL |
mysql."real" | Domain over double precision | SQL |
mysql."smallint signed" | Domain over smallint | SQL |
mysql."smallint unsigned" | Domain over integer · CHECK (((0 <= VALUE) AND (VALUE <= 65535))) | SQL |
mysql."smallint" | Domain over smallint | SQL |
mysql."tinyint signed" | Domain over smallint · CHECK (((’-128’::integer <= VALUE) AND (VALUE <= 127))) | SQL |
mysql."tinyint unsigned" | Domain over smallint · CHECK (((0 <= VALUE) AND (VALUE <= 255))) | SQL |
mysql."tinyint1 signed" | Domain over smallint · CHECK (((’-128’::integer <= VALUE) AND (VALUE <= 127))) | SQL |
mysql."tinyint1 unsigned" | Domain over smallint · CHECK (((0 <= VALUE) AND (VALUE <= 255))) | SQL |
mysql.blob | Domain over bytea | SQL |
mysql.datetime | Domain over timestamp without time zone | SQL |
mysql.double | Domain over double precision | SQL |
mysql.mediumint | Domain over integer · CHECK (((’-8388608’::integer <= VALUE) AND (VALUE <= 8388607))) | SQL |
mysql.tinyint | Domain over smallint · CHECK (((’-128’::integer <= VALUE) AND (VALUE <= 127))) | SQL |
mysql.tinyint1 | Domain over smallint · CHECK (((’-128’::integer <= VALUE) AND (VALUE <= 127))) | SQL |
mysql.varbinary | Domain over bytea | SQL |
mysql.year_ | Domain over integer · CHECK (((1901 <= VALUE) AND (VALUE <= 2155))) | SQL |
Metadata enumerations
| Signature | Purpose | Source definition |
|---|---|---|
mys_informa_schema.enum_collations_pad_attribute | Used by mys_informa_schema.collations.pad_attribute. Allowed values are ‘PAD SPACE’, ‘NO PAD’. | SQL |
mys_informa_schema.enum_referential_constraints_delete_rule | Allowed values are ‘NO ACTION’, ‘RESTRICT’, ‘CASCADE’, ‘SET NULL’, ‘SET DEFAULT’. | SQL |
mys_informa_schema.enum_referential_constraints_match_option | Allowed values are ‘NONE’, ‘PARTIAL’, ‘FULL’. | SQL |
mys_informa_schema.enum_referential_constraints_update_rule | Allowed values are ‘NO ACTION’, ‘RESTRICT’, ‘CASCADE’, ‘SET NULL’, ‘SET DEFAULT’. | SQL |
mys_informa_schema.enum_resource_groups_resource_group_type | Used by mys_informa_schema.resource_groups.resource_group_type. Allowed values are ‘SYSTEM’, ‘USER’. | SQL |
mysql.enum_mysql_user | Used by mysql.“user”.account_locked. Allowed values are ‘N’, ‘Y’. | SQL |
mysql.enum_mysql_user_ssl_type | Used by mysql.“user”.ssl_type. Allowed values are ‘’, ‘ANY’, ‘X509’, ‘SPECIFIED’. | SQL |
mysql.enum_proc | Allowed values are ‘FUNCTION’, ‘PROCEDURE’. | SQL |
mysql.enum_security | Allowed values are ‘INVOKER’, ‘DEFINER’. | SQL |
performance_schema.enum_bin_log_trans_comp_stats_log_type | Used by performance_schema.binary_log_transaction_compression_stats.log_type. Allowed values are ‘BINARY’, ‘RELAY’. | SQL |
performance_schema.enum_error_log_prio | Used by performance_schema.error_log.prio. Allowed values are ‘System’, ‘Error’, ‘Warning’, ‘Note’. | SQL |
performance_schema.enum_evs_st_cur_nes_event_type | Used by performance_schema.events_stages_current.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_st_his_long_nes_event_type | Used by performance_schema.events_stages_history_long.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_st_his_nes_event_type | Used by performance_schema.events_stages_history.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_stms_sumy_by_prg_obj_type | Used by performance_schema.events_statements_summary_by_program.object_type. Allowed values are ‘EVENT’, ‘FUNCTION’, ‘PROCEDURE’, ‘TABLE’, ‘TRIGGER’. | SQL |
performance_schema.enum_evs_stmts_cur_exe_engine | Used by performance_schema.events_statements_current.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_evs_stmts_cur_nes_event_type | Used by performance_schema.events_statements_current.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_stmts_his_exe_engine | Used by performance_schema.events_statements_history.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_evs_stmts_his_long_exe_engine | Used by performance_schema.events_statements_history_long.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_evs_stmts_his_long_nes_event_type | Used by performance_schema.events_statements_history_long.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_stmts_his_nes_event_type | Used by performance_schema.events_statements_history.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_trans_cur_access_mode | Used by performance_schema.events_transactions_current.access_mode. Allowed values are ‘READ ONLY’, ‘READ WRITE’. | SQL |
performance_schema.enum_evs_trans_cur_autocommit | Used by performance_schema.events_transactions_current.autocommit. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_evs_trans_cur_nes_event_type | Used by performance_schema.events_transactions_current.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_trans_cur_state | Used by performance_schema.events_transactions_current.state. Allowed values are ‘ACTIVE’, ‘COMMITTED’, ‘ROLLED BACK’. | SQL |
performance_schema.enum_evs_trans_his_access_mode | Used by performance_schema.events_transactions_history.access_mode. Allowed values are ‘READ ONLY’, ‘READ WRITE’. | SQL |
performance_schema.enum_evs_trans_his_autocommit | Used by performance_schema.events_transactions_history.autocommit. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_evs_trans_his_long_access_mode | Used by performance_schema.events_transactions_history_long.access_mode. Allowed values are ‘READ ONLY’, ‘READ WRITE’. | SQL |
performance_schema.enum_evs_trans_his_long_autocommit | Used by performance_schema.events_transactions_history_long.autocommit. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_evs_trans_his_long_nes_event_type | Used by performance_schema.events_transactions_history_long.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_trans_his_long_state | Used by performance_schema.events_transactions_history_long.state. Allowed values are ‘ACTIVE’, ‘COMMITTED’, ‘ROLLED BACK’. | SQL |
performance_schema.enum_evs_trans_his_nesting_event_type | Used by performance_schema.events_transactions_history.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_trans_his_state | Used by performance_schema.events_transactions_history.state. Allowed values are ‘ACTIVE’, ‘COMMITTED’, ‘ROLLED BACK’. | SQL |
performance_schema.enum_evs_waits_cur_nesting_event_type | Used by performance_schema.events_waits_current.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_waits_his_long_nesting_event_type | Used by performance_schema.events_waits_history_long.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_evs_waits_his_nesting_event_type | Used by performance_schema.events_waits_history.nesting_event_type. Allowed values are ‘TRANSACTION’, ‘STATEMENT’, ‘STAGE’, ‘WAIT’. | SQL |
performance_schema.enum_host_cache_host_validated | Used by performance_schema.host_cache.host_validated. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_perf_timers_timer_name | Used by performance_schema.performance_timers.timer_name. Allowed values are ‘CYCLE’, ‘NANOSECOND’, ‘MICROSECOND’, ‘MILLISECOND’, ‘THREAD_CPU’. | SQL |
performance_schema.enum_pl_exe_engine | Used by performance_schema.processlist.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_pre_stmts_ins_exec_eng | Used by performance_schema.prepared_statements_instances.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_pre_stmts_ins_owner_obj_type | Used by performance_schema.prepared_statements_instances.owner_object_type. Allowed values are ‘EVENT’, ‘FUNCTION’, ‘PROCEDURE’, ‘TABLE’, ‘TRIGGER’. | SQL |
performance_schema.enum_r_a_cn_as_gt_tott | Used by performance_schema.replication_applier_configuration.assign_gtids_to_anonymous_transactions_type. Allowed values are ‘OFF’, ‘LOCAL’, ‘UUID’. | SQL |
performance_schema.enum_r_a_cn_re_ro_ft | Used by performance_schema.replication_applier_configuration.require_row_format. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_r_a_cn_re_ta_pkc | Used by performance_schema.replication_applier_configuration.require_table_primary_key_check. Allowed values are ‘STREAM’, ‘ON’, ‘OFF’. | SQL |
performance_schema.enum_r_a_f_cnf_by | Used by performance_schema.replication_applier_filters.configured_by. Allowed values are ‘STARTUP_OPTIONS’, ‘CHANGE_REPLICATION_FILTER’, ‘STARTUP_OPTIONS_FOR_CHANNEL’, ‘CHANGE_REPLICATION_FILTER_FOR_CHANNEL’. | SQL |
performance_schema.enum_repl_al_st_by_wk_ser_state | Used by performance_schema.replication_applier_status_by_worker.service_state. Allowed values are ‘ON’, ‘OFF’. | SQL |
performance_schema.enum_repl_app_gl_fil_cnf_by | Used by performance_schema.replication_applier_global_filters.configured_by. Allowed values are ‘STARTUP_OPTIONS’, ‘CHANGE_REPLICATION_FILTER’. | SQL |
performance_schema.enum_repl_app_st_by_co_ser_st | Used by performance_schema.replication_applier_status_by_coordinator.service_state. Allowed values are ‘ON’, ‘OFF’. | SQL |
performance_schema.enum_repl_app_st_ser_state | Used by performance_schema.replication_applier_status.service_state. Allowed values are ‘ON’, ‘OFF’. | SQL |
performance_schema.enum_repl_con_conf_auto_position | Used by performance_schema.replication_connection_configuration.auto_position. Allowed values are ‘1’, ‘0’. | SQL |
performance_schema.enum_repl_con_conf_get_public_key | Used by performance_schema.replication_connection_configuration.get_public_key. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_repl_con_conf_gtid_only | Used by performance_schema.replication_connection_configuration.gtid_only. Allowed values are ‘1’, ‘0’. | SQL |
performance_schema.enum_repl_con_conf_sou_con_auto_fo | Used by performance_schema.replication_connection_configuration.source_connection_auto_failover. Allowed values are ‘1’, ‘0’. | SQL |
performance_schema.enum_repl_con_conf_ssl_allowed | Used by performance_schema.replication_connection_configuration.ssl_allowed. Allowed values are ‘YES’, ‘NO’, ‘IGNORED’. | SQL |
performance_schema.enum_repl_con_conf_ssl_verify_svr_cert | Used by performance_schema.replication_connection_configuration.ssl_verify_server_certificate. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_repl_con_status_service_state | Used by performance_schema.replication_connection_status.service_state. Allowed values are ‘ON’, ‘OFF’, ‘CONNECTING’. | SQL |
performance_schema.enum_setup_actors_enabled | Used by performance_schema.setup_actors.enabled. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_actors_history | Used by performance_schema.setup_actors.history. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_consumers_enabled | Used by performance_schema.setup_consumers.enabled. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_instruments_enabled | Used by performance_schema.setup_instruments.enabled. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_instruments_timed | Used by performance_schema.setup_instruments.timed. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_objects_enabled | Used by performance_schema.setup_objects.enabled. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_objects_object_type | Used by performance_schema.setup_objects.object_type. Allowed values are ‘EVENT’, ‘FUNCTION’, ‘PROCEDURE’, ‘TABLE’, ‘TRIGGER’. | SQL |
performance_schema.enum_setup_objects_timed | Used by performance_schema.setup_objects.timed. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_threads_enabled | Used by performance_schema.setup_threads.enabled. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_setup_threads_history | Used by performance_schema.setup_threads.history. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_socket_instances_state | Used by performance_schema.socket_instances.state. Allowed values are ‘IDLE’, ‘ACTIVE’. | SQL |
performance_schema.enum_threads_execution_engine | Used by performance_schema.threads.execution_engine. Allowed values are ‘PRIMARY’, ‘SECONDARY’. | SQL |
performance_schema.enum_threads_history | Used by performance_schema.threads.history. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_threads_instrumented | Used by performance_schema.threads.instrumented. Allowed values are ‘YES’, ‘NO’. | SQL |
performance_schema.enum_variables_info_variable_source | Used by performance_schema.variables_info.variable_source. Allowed values are ‘COMPILED’, ‘GLOBAL’, ‘SERVER’, ‘EXPLICIT’, ‘EXTRA’, ‘USER’, ‘LOGIN’, ‘COMMAND_LINE’, ‘PERSISTED’, ‘DYNAMIC’. | SQL |
5.2.2.3 - Collations
Choose a collation for character comparisons or check a column’s ordering dependency.
| Signature | Purpose | Source definition |
|---|---|---|
mysql.case_insensitive | ICU secondary strength, ignoring case. | SQL |
mysql.case_sensitive | C collation for case-sensitive ordering. | SQL |
mysql.ignore_accents | ICU primary strength with case level enabled. | SQL |
mysql.utf8mb4_bin | Unicode code-point order with PAD SPACE. | SQL |
mysql.utf8mb4_general_ci | MySQL general_ci comparison weights and PAD SPACE. | SQL |
5.2.2.4 - Casts
Look up a source and target type. The section gives the least restrictive context in which PostgreSQL can use that cast.
An assignment cast also works in an explicit CAST. An implicit cast can participate in function and operator resolution.
Assignment
| Signature | Purpose | Source definition |
|---|---|---|
"char" → double precision | Call mysql.convert_char_to_float8(“char”). | SQL |
bigint → bit varying | Call mysql.cast_bigint_to_varbit(bigint). | SQL |
bit varying → bigint | Call mysql.cast_varbit_to_bigint(bit varying). | SQL |
bit varying → integer | Call mysql.cast_varbit_to_int(bit varying). | SQL |
bit varying → smallint | Call mysql.cast_varbit_to_smallint(bit varying). | SQL |
bit → bytea | Call mysql.cast_bit_to_bytea(bit). | SQL |
bit → text | Call mysql.bit_to_text(bit). | SQL |
boolean → bigint | Call mysql.cast_boolean_to_bigint(boolean). | SQL |
boolean → bit varying | Call mysql.cast_bool_to_varbit(boolean). | SQL |
boolean → bytea | Call mysql.cast_boolean_to_bytea(boolean). | Generated definition |
boolean → double precision | Call mysql.cast_boolean_to_float8(boolean). | Generated definition |
boolean → mysql.binary_n | Call mysql.cast_boolean_to_binary_n(boolean). | Generated definition |
boolean → mysql.varbinary_n | Call mysql.cast_boolean_to_varbinary_n(boolean). | Generated definition |
boolean → numeric | Call mysql.cast_boolean_to_numeric(boolean). | Generated definition |
boolean → real | Call mysql.cast_boolean_to_float4(boolean). | Generated definition |
boolean → smallint | Call mysql.cast_boolean_to_tinyint(boolean). | SQL |
bytea → bit | Call mysql.bytea2bit(bytea). | SQL |
bytea → bit varying | Call mysql.bytea2varbit(bytea). | SQL |
bytea → boolean | Call mysql.bytea2bool(bytea). | SQL |
bytea → character | Call mysql.bytea2bpchar(bytea). | SQL |
bytea → character varying | Call mysql.bytea2varchar(bytea). | SQL |
bytea → date | Call mysql.bytea2date(bytea). | SQL |
bytea → double precision | Call mysql.bytea2float8(bytea). | SQL |
bytea → mysql.binary_n | Call mysql.binary_n(bytea,integer,boolean). | Generated definition |
bytea → mysql.varbinary_n | Call mysql.varbinary_n(bytea,integer,boolean). | Generated definition |
bytea → numeric | Call mysql.bytea2numeric(bytea). | SQL |
bytea → real | Call mysql.bytea2float4(bytea). | SQL |
bytea → text | Call mysql.bytea2text(bytea). | SQL |
bytea → time with time zone | Call mysql.bytea2timetz(bytea). | SQL |
bytea → time without time zone | Call mysql.bytea2time(bytea). | SQL |
bytea → timestamp with time zone | Call mysql.bytea2timestamptz(bytea). | SQL |
bytea → timestamp without time zone | Call mysql.bytea2timestamp(bytea). | SQL |
character varying → bigint | Call mysql.cast_varchar_to_bigint(character varying). | SQL |
character varying → double precision | Call mysql.convert_varchar_to_float8(character varying). | SQL |
character varying → integer | Call mysql.cast_varchar_to_int(character varying). | SQL |
character varying → mysql.binary_n | Call mysql.binary_n(character varying,integer,boolean). | Generated definition |
character varying → mysql.varbinary_n | Call mysql.varbinary_n(character varying,integer,boolean). | Generated definition |
character varying → smallint | Call mysql.cast_varchar_to_tinyint(character varying). | SQL |
character → bigint | Call mysql.cast_char_to_bigint(character). | SQL |
character → integer | Call mysql.cast_char_to_int(character). | SQL |
character → mysql.binary_n | Call mysql.binary_n(character,integer,boolean). | Generated definition |
character → mysql.varbinary_n | Call mysql.varbinary_n(character,integer,boolean). | Generated definition |
character → smallint | Call mysql.cast_char_to_tinyint(character). | SQL |
integer → bit varying | Call mysql.cast_int_to_varbit(integer). | SQL |
mysql.binary_n → character | Call mysql.binary_n_bpchar(mysql.binary_n). | Generated definition |
mysql.binary_n → character varying | Call mysql.binary_n_varchar(mysql.binary_n). | Generated definition |
mysql.binary_n → mysql.binary_n | Call mysql.binary_n(mysql.binary_n,integer,boolean). | Generated definition |
mysql.binary_n → mysql.varbinary_n | Call mysql.varbinary_n(mysql.binary_n,integer,boolean). | Generated definition |
mysql.binary_n → text | Call mysql.binary_n_text(mysql.binary_n). | Generated definition |
mysql.hexlit → bigint | Call mysql.hexlit_int8(mysql.hexlit). | SQL |
mysql.hexlit → bit | Call mysql.hexlit_bit(mysql.hexlit,integer,boolean). | SQL |
mysql.hexlit → bit varying | Call mysql.hexlit_varbit(mysql.hexlit,integer,boolean). | SQL |
mysql.hexlit → boolean | Call mysql.hexlit_bool(mysql.hexlit). | SQL |
mysql.hexlit → character | Call mysql.hexlit_bpchar(mysql.hexlit). | SQL |
mysql.hexlit → character varying | Call mysql.hexlit_varchar(mysql.hexlit). | SQL |
mysql.hexlit → double precision | Call mysql.hexlit_float8(mysql.hexlit). | SQL |
mysql.hexlit → integer | Call mysql.hexlit_int4(mysql.hexlit). | SQL |
mysql.hexlit → mysql.binary_n | Call mysql.binary_n(mysql.hexlit,integer,boolean). | Generated definition |
mysql.hexlit → mysql.varbinary_n | Call mysql.varbinary_n(mysql.hexlit,integer,boolean). | Generated definition |
mysql.hexlit → numeric | Call mysql.hexlit_numeric(mysql.hexlit). | SQL |
mysql.hexlit → real | Call mysql.hexlit_float4(mysql.hexlit). | SQL |
mysql.hexlit → smallint | Call mysql.hexlit_int2(mysql.hexlit). | SQL |
mysql.hexlit → text | Call mysql.hexlit_text(mysql.hexlit). | SQL |
mysql.varbinary_n → character | Call mysql.varbinary_n_bpchar(mysql.varbinary_n). | Generated definition |
mysql.varbinary_n → character varying | Call mysql.varbinary_n_varchar(mysql.varbinary_n). | Generated definition |
mysql.varbinary_n → mysql.binary_n | Call mysql.binary_n(mysql.varbinary_n,integer,boolean). | Generated definition |
mysql.varbinary_n → mysql.varbinary_n | Call mysql.varbinary_n(mysql.varbinary_n,integer,boolean). | Generated definition |
mysql.varbinary_n → text | Call mysql.varbinary_n_text(mysql.varbinary_n). | Generated definition |
smallint → bit varying | Call mysql.cast_smallint_to_varbit(smallint). | SQL |
text → bigint | Call mysql.cast_text_to_bigint(text). | SQL |
text → date | Call mysql.cast_text_to_date(text). | SQL |
text → double precision | Call mysql.convert_text_to_float8(text). | SQL |
text → integer | Call mysql.cast_text_to_int(text). | SQL |
text → mysql.binary_n | Call mysql.binary_n(text,integer,boolean). | Generated definition |
text → mysql.varbinary_n | Call mysql.varbinary_n(text,integer,boolean). | Generated definition |
text → smallint | Call mysql.cast_text_to_tinyint(text). | SQL |
text → time without time zone | Call mysql.cast_text_to_time(text). | SQL |
text → timestamp with time zone | Call mysql.cast_text_to_timestamptz(text). | SQL |
text → timestamp without time zone | Call mysql.cast_text_to_timestamp(text). | SQL |
time without time zone → timestamp without time zone | Call mysql.time_to_timestamp(time without time zone). | SQL |
Implicit
| Signature | Purpose | Source definition |
|---|---|---|
bigint → boolean | Call mysql.cast_bigint_to_boolean(bigint). | SQL |
bit varying → boolean | Call mysql.cast_varbit_to_boolean(bit varying). | SQL |
bit → boolean | Call mysql.cast_bit_to_boolean(bit). | SQL |
mysql.binary_n → bytea | Reuse the binary representation. | Generated definition |
mysql.hexlit → bytea | Reuse the binary representation. | SQL |
mysql.varbinary_n → bytea | Reuse the binary representation. | Generated definition |
smallint → boolean | Call mysql.cast_smallint_to_boolean(smallint). | SQL |
text → interval | Call mysql.“interval”(text,integer). | SQL |
5.2.2.5 - Functions
Find a function by name, then choose the overload that matches the argument types.
The first five categories contain functions for application SQL. The remaining categories list the entry points used by the dialect, operators, indexes and metadata queries.
By purpose
| Category | Entries | Look up |
|---|---|---|
| String and binary functions | 324 | Use the return type to distinguish text and byte-string overloads. |
| Numeric functions | 45 | Rounding, division, base conversion and numeric calculations. |
| Date and time functions | 162 | Date arithmetic, formatting, parsing, extraction and clock values. |
| Conditional functions | 335 | IF, IFNULL and ISNULL. Match each branch’s type as well as the condition type. |
| Session functions | 18 | Connection identity, selected database, named locks and statement state. |
| Type conversion helpers | 112 | Internal routines used by casts, coercion and expression rewriting. |
| Comparison operator functions | 278 | Internal entry points behind equality and ordering comparisons. |
| Arithmetic operator functions | 193 | Internal routines for arithmetic on mixed MySQL operand types. |
| Bitwise and logical operator functions | 181 | Internal routines for bit operations and truth-value tests. |
| Pattern and JSON operator functions | 41 | Internal routines for LIKE, regular expressions and JSON field access. |
| String and number helpers | 9 | Internal routines used by string searches, validation and rounding. |
| Temporal conversion helpers | 15 | Internal routines for date normalization, week modes and numeric date arithmetic. |
| Binary and string storage helpers | 48 | Internal routines for type I/O, binary expression evaluation and string results. |
| Aggregate support functions | 12 | Internal transition and final functions invoked while computing an aggregate. |
| Index support functions | 24 | Internal functions for index access, key comparison, hashing and operator-class registration. |
| Session state and variable helpers | 16 | Internal interfaces behind SET, SHOW, user variables and authentication cache management. |
| DDL and write helpers | 15 | Internal routines invoked by column expressions, sequences and row triggers. |
| SHOW and metadata helpers | 31 | Internal routines that format catalog values and construct result sets for MySQL clients. |
By function name
_
_add_bool · _add_null · _calc_days_in_year · _calc_week · _calc_weekday · _convert_format_to_halo_for_number_datetime · _convert_format_to_halo_for_string_datetime · _convert_format_to_halo_for_string_number_datetime · _convert_format_to_halo_for_string_string_datetime · _date_padding · _process_for_number_datetime · _process_for_string_number_datetime · _sub_bool · _sub_null · _week_mode
A
adddate · addtime · amend_def_val · amend_def_val_for_internal · anycompatibleandbytea · anycompatiblecondandbytea · anycompatiblecondorbytea · anycompatibledivbytea · anycompatibleeqbytea · anycompatiblegebytea · anycompatiblegtbytea · anycompatiblelebytea · anycompatiblelikebytea · anycompatibleltbytea · anycompatiblemibytea · anycompatiblemodbytea · anycompatiblemulbytea · anycompatiblenebytea · anycompatiblenlikebytea · anycompatiblenonarray_or_text · anycompatiblenregexpbinbytea · anycompatiblenregexpbytea · anycompatibleorbytea · anycompatibleplbytea · anycompatibleregexpbinbytea · anycompatibleregexpbytea · anynonarray_or_text · array_to_string_for_mysql · ascii · auto_increment_advance
B
bigint_add_char · bigint_add_text · bigint_add_varchar · bigint_and_bigint · bigint_bitxor_bigint · bigint_divide_char · bigint_divide_text · bigint_divide_varchar · bigint_like_text · bigint_minus_char · bigint_minus_text · bigint_minus_varchar · bigint_mod_char · bigint_mod_text · bigint_mod_varchar · bigint_multi_char · bigint_multi_text · bigint_multi_varchar · bigint_not_like_text · bigint_or_bigint · bigint_xor_bigint · bigintbgeqtext · bigintbgtext · bigintleeqtext · bigintletext · bin · binary_n · binary_n_bpchar · binary_n_cmp · binary_n_cmp_bytea · binary_n_cmp_varbinary_n · binary_n_eq · binary_n_ge · binary_n_gt · binary_n_hash · binary_n_hash_extended · binary_n_in · binary_n_le · binary_n_lt · binary_n_ne · binary_n_out · binary_n_recv · binary_n_send · binary_n_text · binary_n_typmodin · binary_n_typmodout · binary_n_varchar · binary_regular_expr · binary_regular_expr_not · binary_truth · bit_and_varbit · bit_and_varbit_final · bit_count · bit_eq_boolean · bit_or_varbit · bit_or_varbit_final · bit_to_text · bit_xor_varbit · bit_xor_varbit_final · bool_and_int2 · bool_and_int4 · bool_and_int8 · bool_or_bool · bool_or_int2 · bool_or_int4 · bool_or_int8 · boolcondandbool · boolean_eq_bit · boolean_eq_varbit · booleqint2 · booleqint4 · booleqint8 · boolneint2 · boolneint4 · boolneint8 · bpcharlike · bpcharnlike · btrim · bytea2bit · bytea2bool · bytea2bpchar · bytea2date · bytea2float4 · bytea2float8 · bytea2int2 · bytea2int4 · bytea2int8 · bytea2numeric · bytea2text · bytea2time · bytea2timestamp · bytea2timestamptz · bytea2timetz · bytea2varbit · bytea2varchar · bytea_and_hexlit · bytea_cmp_binary_n · bytea_cmp_varbinary_n · bytea_div_hexlit · bytea_eq_hexlit · bytea_ge_hexlit · bytea_gt_hexlit · bytea_le_hexlit · bytea_like_hexlit · bytea_lt_hexlit · bytea_mi_hexlit · bytea_mod_hexlit · bytea_mul_hexlit · bytea_ne_hexlit · bytea_nlike_hexlit · bytea_nseq_hexlit · bytea_or_hexlit · bytea_pl_hexlit · bytea_shl_hexlit · bytea_shr_hexlit · bytea_xor_hexlit · byteaandanycompatible · byteaandbytea · byteacondandanycompatible · byteacondandbytea · byteacondoranycompatible · byteacondorbytea · byteadivanycompatible · byteadivbytea · byteaeqanycompatible · byteageanycompatible · byteagebytea · byteagtanycompatible · byteagtbytea · bytealeanycompatible · bytealebytea · bytealikeanycompatible · bytealtanycompatible · bytealtbytea · byteamianycompatible · byteamibytea · byteamodanycompatible · byteamodbytea · byteamulanycompatible · byteamulbytea · byteaneanycompatible · byteanlikeanycompatible · byteanregexpanycompatible · byteanregexpbinanycompatible · byteanregexpbinbytea · byteanregexpbytea · byteaoranycompatible · byteaorbytea · byteaplanycompatible · byteaplbytea · bytearegexpanycompatible · bytearegexpbinanycompatible · bytearegexpbinbytea · bytearegexpbytea
C
cast_bigint_to_boolean · cast_bigint_to_varbit · cast_bit_to_boolean · cast_bit_to_bytea · cast_bool_to_varbit · cast_boolean_to_bigint · cast_boolean_to_binary_n · cast_boolean_to_bytea · cast_boolean_to_float4 · cast_boolean_to_float8 · cast_boolean_to_numeric · cast_boolean_to_tinyint · cast_boolean_to_varbinary_n · cast_char · cast_char_to_bigint · cast_char_to_int · cast_char_to_tinyint · cast_int_to_varbit · cast_numeric_source · cast_smallint_to_boolean · cast_smallint_to_varbit · cast_text_to_bigint · cast_text_to_date · cast_text_to_int · cast_text_to_time · cast_text_to_timestamp · cast_text_to_timestamptz · cast_text_to_tinyint · cast_varbit_to_bigint · cast_varbit_to_boolean · cast_varbit_to_int · cast_varbit_to_smallint · cast_varchar_to_bigint · cast_varchar_to_int · cast_varchar_to_tinyint · ceil · ceil_for_mysql · ceiling · char_add_bigint · char_add_char · char_divide_bigint · char_divide_char · char_eq_char_for_date_format · char_length · char_minus_bigint · char_minus_char · char_mod_bigint · char_mod_char · char_multi_bigint · char_multi_char · character_length · check_set · clear_user_variables · column_default · column_domain · column_extra · column_generation · concat · concat_one · concat_pair · concat_ws · concat_ws_bytes · connection_id · conv · convert_bigint_to_varbit · convert_char_to_float8 · convert_date_to_float8 · convert_digit_text_to_text_for_mysql · convert_int_to_varbit · convert_smallint_to_varbit · convert_text_hex_to_text_varbit · convert_text_to_bigint_for_mysql · convert_text_to_digit_text_for_mysql · convert_text_to_float8 · convert_text_to_int8 · convert_text_varbit_to_bigint · convert_time_text_to_numeric_for_mysql · convert_time_to_float8 · convert_timestamp_to_float8 · convert_to_time_format · convert_tz · convert_using · convert_varbit_to_bigint · convert_varbit_to_int · convert_varbit_to_smallint · convert_varchar_to_float8 · curdate · curdate_add · curdate_sub · current_user · curtime
D
database · date · date_add · date_add_bigint · date_add_int · date_add_smallint · date_eq_text · date_format · date_ge_text · date_gt_text · date_le_text · date_lt_text · date_minus_bigint · date_minus_int · date_minus_smallint · date_ne_text · date_sub · datediff · dateeqtext · datenetext · day · dayname · dayofmonth · dayofweek · dayofyear · decimal_column_type · decimal_ps · div_float4_float4 · div_float4_float8 · div_float8_float4 · div_float8_float8 · div_float8_text · div_int2_int2 · div_int2_int4 · div_int2_int8 · div_int4_int2 · div_int4_int4 · div_int4_int8 · div_int8_int2 · div_int8_int4 · div_int8_int8 · div_text_float8 · div_text_text · dummy_min_finalfunc_for_bytea · dummy_min_sfunc_for_bytea
E
elt · elt_index · export_set · extract
F
field · find_in_set · float8_and_hexlit · float8_div_hexlit · float8_eq_hexlit · float8_ge_hexlit · float8_gt_hexlit · float8_le_hexlit · float8_lt_hexlit · float8_mi_hexlit · float8_mod_hexlit · float8_mul_hexlit · float8_ne_hexlit · float8_nseq_hexlit · float8_or_hexlit · float8_pl_hexlit · float8_shl_hexlit · float8_shr_hexlit · float8_xor_hexlit · floor · floor_for_mysql · flush_auth_cache · format · found_rows · from_days · from_unixtime
G
generated_column · generated_numeric · generated_value · generated_varchar · get_column_extra · get_column_key · get_func_def · get_funcs_procs_parameters · get_lock · get_mysql_proc_arg_mode · get_mysql_type_name · get_proc_def · get_seq_in_index · get_system_global_variable · get_system_session_variable · get_system_variable · get_user_var · getenv
H
hex · hexlit_and_bytea · hexlit_and_float8 · hexlit_and_hexlit · hexlit_and_int2 · hexlit_and_int4 · hexlit_and_int8 · hexlit_and_numeric · hexlit_and_text · hexlit_and_varbit · hexlit_bit · hexlit_bool · hexlit_bpchar · hexlit_cmp · hexlit_cmp_support · hexlit_div_bytea · hexlit_div_float8 · hexlit_div_hexlit · hexlit_div_int2 · hexlit_div_int4 · hexlit_div_int8 · hexlit_div_numeric · hexlit_div_text · hexlit_div_varbit · hexlit_eq · hexlit_eq_bytea · hexlit_eq_float8 · hexlit_eq_int2 · hexlit_eq_int4 · hexlit_eq_int8 · hexlit_eq_numeric · hexlit_eq_text · hexlit_eq_varbit · hexlit_float4 · hexlit_float8 · hexlit_ge · hexlit_ge_bytea · hexlit_ge_float8 · hexlit_ge_int2 · hexlit_ge_int4 · hexlit_ge_int8 · hexlit_ge_numeric · hexlit_ge_text · hexlit_ge_varbit · hexlit_gt · hexlit_gt_bytea · hexlit_gt_float8 · hexlit_gt_int2 · hexlit_gt_int4 · hexlit_gt_int8 · hexlit_gt_numeric · hexlit_gt_text · hexlit_gt_varbit · hexlit_hash · hexlit_hash_extended · hexlit_in · hexlit_int2 · hexlit_int4 · hexlit_int8 · hexlit_le · hexlit_le_bytea · hexlit_le_float8 · hexlit_le_int2 · hexlit_le_int4 · hexlit_le_int8 · hexlit_le_numeric · hexlit_le_text · hexlit_le_varbit · hexlit_like · hexlit_like_bytea · hexlit_like_text · hexlit_lt · hexlit_lt_bytea · hexlit_lt_float8 · hexlit_lt_int2 · hexlit_lt_int4 · hexlit_lt_int8 · hexlit_lt_numeric · hexlit_lt_text · hexlit_lt_varbit · hexlit_mi_bytea · hexlit_mi_float8 · hexlit_mi_hexlit · hexlit_mi_int2 · hexlit_mi_int4 · hexlit_mi_int8 · hexlit_mi_numeric · hexlit_mi_text · hexlit_mi_varbit · hexlit_mod_bytea · hexlit_mod_float8 · hexlit_mod_hexlit · hexlit_mod_int2 · hexlit_mod_int4 · hexlit_mod_int8 · hexlit_mod_numeric · hexlit_mod_text · hexlit_mod_varbit · hexlit_mul_bytea · hexlit_mul_float8 · hexlit_mul_hexlit · hexlit_mul_int2 · hexlit_mul_int4 · hexlit_mul_int8 · hexlit_mul_numeric · hexlit_mul_text · hexlit_mul_varbit · hexlit_ne · hexlit_ne_bytea · hexlit_ne_float8 · hexlit_ne_int2 · hexlit_ne_int4 · hexlit_ne_int8 · hexlit_ne_numeric · hexlit_ne_text · hexlit_ne_varbit · hexlit_nlike · hexlit_nlike_bytea · hexlit_nlike_text · hexlit_not · hexlit_nseq_bytea · hexlit_nseq_float8 · hexlit_nseq_hexlit · hexlit_nseq_int2 · hexlit_nseq_int4 · hexlit_nseq_int8 · hexlit_nseq_numeric · hexlit_nseq_text · hexlit_nseq_varbit · hexlit_numeric · hexlit_or_bytea · hexlit_or_float8 · hexlit_or_hexlit · hexlit_or_int2 · hexlit_or_int4 · hexlit_or_int8 · hexlit_or_numeric · hexlit_or_text · hexlit_or_varbit · hexlit_out · hexlit_pl_bytea · hexlit_pl_float8 · hexlit_pl_hexlit · hexlit_pl_int2 · hexlit_pl_int4 · hexlit_pl_int8 · hexlit_pl_numeric · hexlit_pl_text · hexlit_pl_varbit · hexlit_recv · hexlit_send · hexlit_shl_bytea · hexlit_shl_float8 · hexlit_shl_hexlit · hexlit_shl_int2 · hexlit_shl_int4 · hexlit_shl_int8 · hexlit_shl_numeric · hexlit_shl_text · hexlit_shl_varbit · hexlit_shr_bytea · hexlit_shr_float8 · hexlit_shr_hexlit · hexlit_shr_int2 · hexlit_shr_int4 · hexlit_shr_int8 · hexlit_shr_numeric · hexlit_shr_text · hexlit_shr_varbit · hexlit_text · hexlit_um · hexlit_varbit · hexlit_varchar · hexlit_xor_bytea · hexlit_xor_float8 · hexlit_xor_hexlit · hexlit_xor_int2 · hexlit_xor_int4 · hexlit_xor_int8 · hexlit_xor_numeric · hexlit_xor_text · hexlit_xor_varbit · hour
I
if · ifnull · index_key_name · index_key_parts · insert · instr · int2_and_bool · int2_and_hexlit · int2_and_int2 · int2_and_int4 · int2_and_int8 · int2_div_hexlit · int2_eq_hexlit · int2_eq_varbit · int2_ge_hexlit · int2_gt_hexlit · int2_le_hexlit · int2_lt_hexlit · int2_mi_hexlit · int2_mod_hexlit · int2_mul_hexlit · int2_ne_hexlit · int2_nseq_hexlit · int2_or_bool · int2_or_hexlit · int2_or_int2 · int2_or_int4 · int2_or_int8 · int2_pl_hexlit · int2_shl_hexlit · int2_shr_hexlit · int2_xor_hexlit · int2andint4 · int2andint8 · int2andnumeric · int2eqbool · int2leftmoveint2 · int2leftmoveint4 · int2leftmoveint8 · int2nebool · int2orint4 · int2orint8 · int2ornumeric · int2rightmoveint2 · int2rightmoveint4 · int2rightmoveint8 · int4_and_bool · int4_and_hexlit · int4_and_int2 · int4_and_int4 · int4_and_int8 · int4_div_hexlit · int4_eq_hexlit · int4_eq_varbit · int4_ge_hexlit · int4_gt_hexlit · int4_le_hexlit · int4_lt_hexlit · int4_mi_hexlit · int4_mod_hexlit · int4_mul_hexlit · int4_ne_hexlit · int4_nseq_hexlit · int4_or_bool · int4_or_hexlit · int4_or_int2 · int4_or_int4 · int4_or_int8 · int4_pl_hexlit · int4_shl_hexlit · int4_shr_hexlit · int4_xor_hexlit · int4andint2 · int4andint8 · int4andnumeric · int4andtext · int4eqbool · int4leftmoveint2 · int4leftmoveint4 · int4leftmoveint8 · int4nebool · int4orint2 · int4orint8 · int4ornumeric · int4rightmoveint2 · int4rightmoveint4 · int4rightmoveint8 · int8_and_bool · int8_and_hexlit · int8_and_int2 · int8_and_int4 · int8_div_hexlit · int8_eq_hexlit · int8_eq_varbit · int8_ge_hexlit · int8_gt_hexlit · int8_le_hexlit · int8_lt_hexlit · int8_mi_hexlit · int8_mod_hexlit · int8_mul_hexlit · int8_ne_hexlit · int8_nseq_hexlit · int8_or_bool · int8_or_hexlit · int8_or_int2 · int8_or_int4 · int8_pl_hexlit · int8_shl_hexlit · int8_shr_hexlit · int8_xor_hexlit · int8andint2 · int8andint4 · int8andnumeric · int8eqbool · int8leftmoveint2 · int8leftmoveint4 · int8leftmoveint8 · int8nebool · int8orint2 · int8orint4 · int8ornumeric · int8rightmoveint2 · int8rightmoveint4 · int8rightmoveint8 · int_div · integerbgeqtext · integerbgtext · integerleeqtext · integerletext · interval · interval_pl_text · is_and_eq · is_free_lock · is_numeric · is_used_lock · is_valid_binary · is_valid_hex · isnull
J
json_object_field · json_unquote
L
last_day · last_insert_id · lcase · left · length · lenient_float8 · lenient_int · lenient_numeric · lenient_varchar · load_file · locate · log · log2 · lower · lpad · ltrim
M
make_set · makedate · maketime · microsecond · mid · minute · mod · mod_int2_int2 · mod_int2_int4 · mod_int2_int8 · mod_int4_int2 · mod_int4_int4 · mod_int4_int8 · mod_int8_int2 · mod_int8_int4 · mod_int8_int8 · month · monthname · mys_div_float8 · mys_div_int8 · mys_div_numeric · mys_mod_int8 · mys_mod_numeric · mys_uint64_bitnot · mys_uint64_bitop
N
now · numeric_and_hexlit · numeric_div_hexlit · numeric_eq_hexlit · numeric_ge_hexlit · numeric_gt_hexlit · numeric_le_hexlit · numeric_lt_hexlit · numeric_mi_hexlit · numeric_mod_hexlit · numeric_mul_hexlit · numeric_ne_hexlit · numeric_nseq_hexlit · numeric_or_hexlit · numeric_pl_hexlit · numeric_shl_hexlit · numeric_shr_hexlit · numeric_timestamp · numeric_xor_hexlit · numericandint2 · numericandint4 · numericandint8 · numericbgeqtext · numericbgtext · numericeqtext · numericleeqtext · numericletext · numericnetext · numericorint2 · numericorint4 · numericorint8
O
octet_length · on_update_current_timestamp
P
part_list_columns · pending_fk_definitions · pending_fk_guard · period_add · period_diff · prefix_1042_cmp · prefix_17_cmp · prefix_25_cmp · prefix_53875699983efc79eeb9e023e66605f5_cmp · prefix_b8aba7e65857eaf6a91ca737fb14b87b_cmp · prefix_handler · prefix_like · prefix_not_like · prefix_options
Q
R
rand · raw_bytes · register_prefix_binary · register_prefix_type · regular_expr · regular_expr_not · release_all_locks · release_lock · replace · right · round · row_count · rpad · rtrim
S
schema · sec_to_time · second · session_user · set_system_charset_variable · set_system_global_variable · set_system_names_variable · set_system_session_variable · set_system_variable · set_user_var · set_user_var_in_expr · setval · show_create_function · show_create_procedure · show_create_table · show_create_table_impl · show_create_trigger · show_create_view · show_create_view_impl · show_diagnostics · show_system_variable · show_table_columns · show_table_full_columns · show_table_indexs · show_table_indexs_for_8 · sleep · smallintbgeqtext · smallintbgtext · smallintleeqtext · smallintletext · space · sqrt · str_to_date · str_to_double · strcmp · string_result · subdate · substr · substring · substring_index · subtime · sum_bool · sum_text · sum_text_final · sysdate
T
text_add_bigint · text_add_text · text_and_hexlit · text_and_text · text_avg_accum · text_div_hexlit · text_divide_bigint · text_divide_text · text_eq_date · text_eq_hexlit · text_eq_time · text_eq_timestamp · text_eq_timestamptz · text_ge_date · text_ge_hexlit · text_ge_time · text_ge_timestamp · text_ge_timestamptz · text_gt_date · text_gt_hexlit · text_gt_time · text_gt_timestamp · text_gt_timestamptz · text_instr · text_le_date · text_le_hexlit · text_le_time · text_le_timestamp · text_le_timestamptz · text_like_bigint · text_like_hexlit · text_locate2 · text_locate3 · text_lt_date · text_lt_hexlit · text_lt_time · text_lt_timestamp · text_lt_timestamptz · text_mi_hexlit · text_mi_interval · text_minus_bigint · text_minus_text · text_mod_bigint · text_mod_hexlit · text_mod_text · text_mul_hexlit · text_multi_bigint · text_multi_text · text_ne_date · text_ne_hexlit · text_ne_time · text_ne_timestamp · text_ne_timestamptz · text_nlike_hexlit · text_not_like_bigint · text_nseq_hexlit · text_or_anycompatiblenonarray · text_or_anynoarray · text_or_hexlit · text_or_text · text_pl_hexlit · text_pl_interval · text_shl_hexlit · text_shr_hexlit · text_xor_hexlit · textbgbigint · textbgeqbigint · textbgeqinteger · textbgeqnumeric · textbgeqsmallint · textbginteger · textbgnumeric · textbgsmallint · texteq · texteqdate · texteqnumeric · texteqtime · texteqtimestamp · textlebigint · textleeqbigint · textleeqinteger · textleeqnumeric · textleeqsmallint · textleinteger · textlenumeric · textlesmallint · textne · textnedate · textnenumeric · textnetime · textnetimestamp · time_add_bigint · time_eq_text · time_format · time_ge_text · time_gt_text · time_le_text · time_lt_text · time_minus_bigint · time_ne_text · time_to_sec · time_to_timestamp · timediff · timeeqtext · timenetext · timestamp · timestamp_add_bigint · timestamp_eq_text · timestamp_ge_text · timestamp_gt_text · timestamp_le_text · timestamp_lt_text · timestamp_minus_bigint · timestamp_ne_text · timestampadd · timestampdiff · timestampeqtext · timestampnetext · timestamptz_eq_text · timestamptz_ge_text · timestamptz_gt_text · timestamptz_le_text · timestamptz_lt_text · timestamptz_ne_text · to_days · truncate
U
ucase · unhex · unix_timestamp · upper · user · utc_date · utc_time · utc_timestamp · uuid · uuid_short
V
varbinary_n · varbinary_n_bpchar · varbinary_n_cmp · varbinary_n_cmp_binary_n · varbinary_n_cmp_bytea · varbinary_n_eq · varbinary_n_ge · varbinary_n_gt · varbinary_n_hash · varbinary_n_hash_extended · varbinary_n_in · varbinary_n_le · varbinary_n_lt · varbinary_n_ne · varbinary_n_out · varbinary_n_recv · varbinary_n_send · varbinary_n_text · varbinary_n_typmodin · varbinary_n_typmodout · varbinary_n_varchar · varbit_and_hexlit · varbit_div_hexlit · varbit_eq_boolean · varbit_eq_hexlit · varbit_eq_int2 · varbit_eq_int4 · varbit_eq_int8 · varbit_ge_hexlit · varbit_gt_hexlit · varbit_le_hexlit · varbit_lt_hexlit · varbit_mi_hexlit · varbit_mod_hexlit · varbit_mul_hexlit · varbit_ne_hexlit · varbit_nseq_hexlit · varbit_numeric · varbit_or_hexlit · varbit_pl_hexlit · varbit_shl_hexlit · varbit_shr_hexlit · varbit_xor_hexlit · varchar_add_bigint · varchar_add_varchar · varchar_divide_bigint · varchar_divide_varchar · varchar_minus_bigint · varchar_minus_varchar · varchar_mod_bigint · varchar_mod_varchar · varchar_multi_bigint · varchar_multi_varchar · version
W
week · weekday · weekofyear
Y
5.2.2.5.1 - String and binary functions
Use the return type to distinguish text and byte-string overloads.
ascii
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ascii(bytea) → integer | Read the numeric value of the first byte. | Generated definition · C |
mysql.ascii(mysql.binary_n) → integer | Read the numeric value of the first byte. | Generated definition · C |
mysql.ascii(mysql.hexlit) → integer | Read the numeric value of the first byte. | Generated definition · C |
mysql.ascii(mysql.varbinary_n) → integer | Read the numeric value of the first byte. | Generated definition · C |
bin
| Signature | Purpose | Source definition |
|---|---|---|
mysql.bin(bigint) → text | Represent an integer in base two. | SQL |
btrim
| Signature | Purpose | Source definition |
|---|---|---|
mysql.btrim(bytea) → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(bytea, "any") → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.binary_n) → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.binary_n, "any") → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.hexlit) → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.hexlit, "any") → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.varbinary_n) → bytea | Trim both ends of the byte string. | Generated definition · C |
mysql.btrim(mysql.varbinary_n, "any") → bytea | Trim both ends of the byte string. | Generated definition · C |
char_length
| Signature | Purpose | Source definition |
|---|---|---|
mysql.char_length(bytea) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.char_length(mysql.binary_n) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.char_length(mysql.hexlit) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.char_length(mysql.varbinary_n) → integer | Count characters in text or bytes in a binary string. | Generated definition |
character_length
| Signature | Purpose | Source definition |
|---|---|---|
mysql.character_length(bytea) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.character_length(mysql.binary_n) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.character_length(mysql.hexlit) → integer | Count characters in text or bytes in a binary string. | Generated definition |
mysql.character_length(mysql.varbinary_n) → integer | Count characters in text or bytes in a binary string. | Generated definition |
concat
| Signature | Purpose | Source definition |
|---|---|---|
mysql.concat(VARIADIC "any") → text | Concatenate the arguments in order. | SQL · C |
concat_ws
| Signature | Purpose | Source definition |
|---|---|---|
mysql.concat_ws(text, VARIADIC "any") → text | Join values with the supplied separator. | SQL · C |
elt
| Signature | Purpose | Source definition |
|---|---|---|
mysql.elt(VARIADIC "any") → text | Pick the string at the given one-based position. | SQL · C |
export_set
| Signature | Purpose | Source definition |
|---|---|---|
mysql.export_set(bigint, text, text, text, bigint) → text | Render set and unset bits using the supplied strings. | SQL |
field
find_in_set
| Signature | Purpose | Source definition |
|---|---|---|
mysql.find_in_set(bigint, text) → integer | Find a value in a comma-separated list. | SQL |
mysql.find_in_set(text, text) → integer | Find a value in a comma-separated list. | SQL |
format
| Signature | Purpose | Source definition |
|---|---|---|
mysql.format(numeric, bigint) → text | Format a number with the requested decimal places. | SQL |
hex
| Signature | Purpose | Source definition |
|---|---|---|
mysql.hex(bigint) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(bit varying) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(boolean) → text | Encode the value in hexadecimal. | SQL |
mysql.hex(bytea) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(character) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(double precision) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(integer) → text | Encode the value in hexadecimal. | SQL |
mysql.hex(mysql.binary_n) → text | Encode the value in hexadecimal. | Generated definition · C |
mysql.hex(mysql.hexlit) → text | Encode the value in hexadecimal. | Generated definition · C |
mysql.hex(mysql.varbinary_n) → text | Encode the value in hexadecimal. | Generated definition · C |
mysql.hex(numeric) → text | Encode the value in hexadecimal. | SQL · C |
mysql.hex(smallint) → text | Encode the value in hexadecimal. | SQL |
mysql.hex(text) → text | Encode the value in hexadecimal. | SQL · C |
insert
| Signature | Purpose | Source definition |
|---|---|---|
mysql.insert(text, integer, integer, text) → text | Replace part of a string at a specified position. | SQL |
instr
json_unquote
| Signature | Purpose | Source definition |
|---|---|---|
mysql.json_unquote(json) → text | Remove JSON string quoting. | SQL |
lcase
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lcase(bigint) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(bytea) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lcase(date) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(integer) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(mysql."smallint") → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(mysql.binary_n) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lcase(mysql.hexlit) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lcase(mysql.varbinary_n) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lcase(numeric) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(text) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(time without time zone) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(timestamp with time zone) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
mysql.lcase(timestamp without time zone) → text | Convert text to lowercase. Binary strings retain their bytes. | SQL |
left
length
| Signature | Purpose | Source definition |
|---|---|---|
mysql.length(bytea) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.length(mysql.binary_n) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.length(mysql.hexlit) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.length(mysql.varbinary_n) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.length(num bigint) → integer | Count the bytes in the value’s string representation. | SQL |
mysql.length(num character) → integer | Count the bytes in the value’s string representation. | SQL |
mysql.length(num integer) → integer | Count the bytes in the value’s string representation. | SQL |
mysql.length(num mysql."smallint") → integer | Count the bytes in the value’s string representation. | SQL |
mysql.length(num numeric) → integer | Count the bytes in the value’s string representation. | SQL |
mysql.length(text) → integer | Count the bytes in the value’s string representation. | SQL |
load_file
| Signature | Purpose | Source definition |
|---|---|---|
mysql.load_file(text) → text | Read a server-side file. EXECUTE is restricted. | SQL |
locate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.locate(bytea, bytea) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, bytea, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.binary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.binary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.hexlit) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.hexlit, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.varbinary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, mysql.varbinary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, text) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(bytea, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, bytea) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, bytea, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.binary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.binary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.hexlit) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.hexlit, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.varbinary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, mysql.varbinary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, text) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.binary_n, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, bytea) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, bytea, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.binary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.binary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.hexlit) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.hexlit, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.varbinary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, mysql.varbinary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, text) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.hexlit, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, bytea) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, bytea, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.binary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.binary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.hexlit) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.hexlit, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.varbinary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, mysql.varbinary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, text) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(mysql.varbinary_n, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(numeric, numeric) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, numeric, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, text) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, time without time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, time without time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, timestamp with time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, timestamp with time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, timestamp without time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(numeric, timestamp without time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, bytea) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, bytea, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.binary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.binary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.hexlit) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.hexlit, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.varbinary_n) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, mysql.varbinary_n, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | Generated definition · C |
mysql.locate(text, numeric) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, numeric, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, text) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, text, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, time without time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, time without time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, timestamp with time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, timestamp with time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, timestamp without time zone) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
mysql.locate(text, timestamp without time zone, integer) → integer | Find the first occurrence of a substring, optionally from a given position. | SQL |
lower
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lower(bytea) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lower(mysql.binary_n) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lower(mysql.hexlit) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
mysql.lower(mysql.varbinary_n) → bytea | Convert text to lowercase. Binary strings retain their bytes. | Generated definition · C |
lpad
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lpad(bigint, integer, text) → text | Pad on the left to the requested length. | SQL |
mysql.lpad(text, integer, text) → text | Pad on the left to the requested length. | SQL |
ltrim
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ltrim(bytea) → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(bytea, "any") → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.binary_n) → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.binary_n, "any") → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.hexlit) → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.hexlit, "any") → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.varbinary_n) → bytea | Trim the beginning of a byte string. | Generated definition · C |
mysql.ltrim(mysql.varbinary_n, "any") → bytea | Trim the beginning of a byte string. | Generated definition · C |
make_set
| Signature | Purpose | Source definition |
|---|---|---|
mysql.make_set(bigint, VARIADIC text[]) → text | Select strings using the set bits of a mask. | SQL |
mid
| Signature | Purpose | Source definition |
|---|---|---|
mysql.mid(bigint, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(bigint, integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(date, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(date, integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(integer, integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(mysql."smallint", integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(mysql."smallint", integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(str text, pos integer, len integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(text, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(time without time zone, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(time without time zone, integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(timestamp with time zone, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(timestamp with time zone, integer, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(timestamp without time zone, integer) → text | Extract a slice starting at the given position. | SQL |
mysql.mid(timestamp without time zone, integer, integer) → text | Extract a slice starting at the given position. | SQL |
octet_length
| Signature | Purpose | Source definition |
|---|---|---|
mysql.octet_length(bytea) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.octet_length(mysql.binary_n) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.octet_length(mysql.hexlit) → integer | Count the bytes in the value’s string representation. | Generated definition |
mysql.octet_length(mysql.varbinary_n) → integer | Count the bytes in the value’s string representation. | Generated definition |
replace
| Signature | Purpose | Source definition |
|---|---|---|
mysql.replace(bytea, "any", "any") → bytea | Replace occurrences of a search string. | Generated definition · C |
mysql.replace(mysql.binary_n, "any", "any") → bytea | Replace occurrences of a search string. | Generated definition · C |
mysql.replace(mysql.hexlit, "any", "any") → bytea | Replace occurrences of a search string. | Generated definition · C |
mysql.replace(mysql.varbinary_n, "any", "any") → bytea | Replace occurrences of a search string. | Generated definition · C |
mysql.replace(text, text, text) → text | Replace occurrences of a search string. | SQL · C |
right
rpad
| Signature | Purpose | Source definition |
|---|---|---|
mysql.rpad(bigint, integer, text) → text | Pad on the right to the requested length. | SQL |
mysql.rpad(text, integer, text) → text | Pad on the right to the requested length. | SQL |
rtrim
| Signature | Purpose | Source definition |
|---|---|---|
mysql.rtrim(bytea) → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(bytea, "any") → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.binary_n) → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.binary_n, "any") → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.hexlit) → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.hexlit, "any") → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.varbinary_n) → bytea | Trim the end of a byte string. | Generated definition · C |
mysql.rtrim(mysql.varbinary_n, "any") → bytea | Trim the end of a byte string. | Generated definition · C |
space
| Signature | Purpose | Source definition |
|---|---|---|
mysql.space(integer) → text | Produce a string of spaces. | SQL |
strcmp
| Signature | Purpose | Source definition |
|---|---|---|
mysql.strcmp(text, text) → integer | Compare two strings and return their ordering. | SQL |
substr
substring
substring_index
| Signature | Purpose | Source definition |
|---|---|---|
mysql.substring_index(text, text, integer) → text | Split at a delimiter and take the requested part. | SQL · C |
ucase
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ucase(bigint) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(bytea) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.ucase(date) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(integer) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(mysql."smallint") → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(mysql.binary_n) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.ucase(mysql.hexlit) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.ucase(mysql.varbinary_n) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.ucase(numeric) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(text) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(time without time zone) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(timestamp with time zone) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
mysql.ucase(timestamp without time zone) → text | Convert text to uppercase. Binary strings retain their bytes. | SQL |
unhex
| Signature | Purpose | Source definition |
|---|---|---|
mysql.unhex(bigint) → bytea | Decode hexadecimal digits into bytes. | SQL |
mysql.unhex(bytea) → bytea | Decode hexadecimal digits into bytes. | SQL · C |
mysql.unhex(text) → bytea | Decode hexadecimal digits into bytes. | SQL · C |
upper
| Signature | Purpose | Source definition |
|---|---|---|
mysql.upper(bytea) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.upper(mysql.binary_n) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.upper(mysql.hexlit) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
mysql.upper(mysql.varbinary_n) → bytea | Convert text to uppercase. Binary strings retain their bytes. | Generated definition · C |
5.2.2.5.2 - Numeric functions
Rounding, division, base conversion and numeric calculations.
bit_count
| Signature | Purpose | Source definition |
|---|---|---|
mysql.bit_count(bigint) → integer | Count the set bits. | SQL |
mysql.bit_count(bytea) → integer | Count the set bits. | SQL |
mysql.bit_count(text) → integer | Count the set bits. | SQL |
ceil
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ceil(text) → bigint | Round up to an integer. | SQL |
ceiling
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ceiling(text) → bigint | Round up to an integer. | SQL |
conv
| Signature | Purpose | Source definition |
|---|---|---|
mysql.conv(bigint, integer, integer) → text | Convert a number between bases. | SQL |
mysql.conv(text, integer, integer) → text | Convert a number between bases. | SQL |
floor
| Signature | Purpose | Source definition |
|---|---|---|
mysql.floor(text) → bigint | Round down to an integer. | SQL |
int_div
| Signature | Purpose | Source definition |
|---|---|---|
mysql.int_div(mysql.hexlit, mysql.hexlit) → bigint | Compute the integer quotient for MySQL DIV. | SQL |
mysql.int_div(mysql.hexlit, numeric) → bigint | Compute the integer quotient for MySQL DIV. | SQL |
mysql.int_div(numeric, mysql.hexlit) → bigint | Compute the integer quotient for MySQL DIV. | SQL |
mysql.int_div(numeric, numeric) → bigint | Compute the integer quotient for MySQL DIV. | SQL |
log
| Signature | Purpose | Source definition |
|---|---|---|
mysql.log(bigint) → numeric | Compute a logarithm. | SQL |
mysql.log(integer) → numeric | Compute a logarithm. | SQL |
mysql.log(numeric) → numeric | Compute a logarithm. | SQL |
mysql.log(smallint) → numeric | Compute a logarithm. | SQL |
log2
| Signature | Purpose | Source definition |
|---|---|---|
mysql.log2(double precision) → numeric | Compute the base-two logarithm. | SQL |
mysql.log2(numeric) → numeric | Compute the base-two logarithm. | SQL |
mod
| Signature | Purpose | Source definition |
|---|---|---|
mysql.mod(bigint, bigint) → bigint | Return the remainder of division. | SQL |
mysql.mod(bigint, text) → numeric | Return the remainder of division. | SQL |
mysql.mod(integer, integer) → integer | Return the remainder of division. | SQL |
mysql.mod(integer, text) → numeric | Return the remainder of division. | SQL |
mysql.mod(mysql."smallint", mysql."smallint") → mysql."smallint" | Return the remainder of division. | SQL |
mysql.mod(mysql."smallint", text) → numeric | Return the remainder of division. | SQL |
mysql.mod(numeric, numeric) → numeric | Return the remainder of division. | SQL |
mysql.mod(numeric, text) → numeric | Return the remainder of division. | SQL |
mysql.mod(text, bigint) → numeric | Return the remainder of division. | SQL |
mysql.mod(text, integer) → numeric | Return the remainder of division. | SQL |
mysql.mod(text, mysql."smallint") → numeric | Return the remainder of division. | SQL |
mysql.mod(text, numeric) → numeric | Return the remainder of division. | SQL |
mysql.mod(text, text) → numeric | Return the remainder of division. | SQL |
rand
| Signature | Purpose | Source definition |
|---|---|---|
mysql.rand() → numeric | Generate a pseudorandom number. | SQL |
mysql.rand(bigint) → numeric | Generate a pseudorandom number. | SQL |
mysql.rand(integer) → numeric | Generate a pseudorandom number. | SQL |
round
| Signature | Purpose | Source definition |
|---|---|---|
mysql.round(integer) → integer | Round to the requested precision. | SQL |
mysql.round(integer, integer) → integer | Round to the requested precision. | SQL |
mysql.round(numeric) → integer | Round to the requested precision. | SQL |
mysql.round(numeric, integer) → numeric | Round to the requested precision. | SQL |
mysql.round(text) → numeric | Round to the requested precision. | SQL |
mysql.round(text, integer) → numeric | Round to the requested precision. | SQL |
sqrt
| Signature | Purpose | Source definition |
|---|---|---|
mysql.sqrt(bigint) → numeric | Compute the square root. | SQL |
mysql.sqrt(integer) → numeric | Compute the square root. | SQL |
mysql.sqrt(numeric) → numeric | Compute the square root. | SQL |
mysql.sqrt(smallint) → numeric | Compute the square root. | SQL |
truncate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.truncate(numeric, integer) → numeric | Truncate a number to the requested decimal place. | SQL |
5.2.2.5.3 - Date and time functions
Date arithmetic, formatting, parsing, extraction and clock values.
adddate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.adddate(date, integer) → date | Add a day count or interval to a date. | SQL |
mysql.adddate(date, interval) → date | Add a day count or interval to a date. | SQL |
mysql.adddate(numeric, integer) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.adddate(numeric, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.adddate(text, integer) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.adddate(text, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.adddate(timestamp without time zone, integer) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.adddate(timestamp without time zone, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
addtime
| Signature | Purpose | Source definition |
|---|---|---|
mysql.addtime(text, double precision) → text | Add time values. | SQL |
mysql.addtime(text, text) → text | Add time values. | SQL · C |
mysql.addtime(text, time without time zone) → text | Add time values. | SQL |
mysql.addtime(time without time zone, double precision) → time without time zone | Add time values. | SQL |
mysql.addtime(time without time zone, text) → time without time zone | Add time values. | SQL |
mysql.addtime(time without time zone, time without time zone) → time without time zone | Add time values. | SQL |
mysql.addtime(timestamp without time zone, double precision) → timestamp without time zone | Add time values. | SQL |
mysql.addtime(timestamp without time zone, text) → timestamp without time zone | Add time values. | SQL · C |
mysql.addtime(timestamp without time zone, time without time zone) → timestamp without time zone | Add time values. | SQL · C |
convert_tz
| Signature | Purpose | Source definition |
|---|---|---|
mysql.convert_tz(text, text, text) → timestamp without time zone | Convert a temporal value between time zones. | SQL |
mysql.convert_tz(timestamp without time zone, text, text) → timestamp without time zone | Convert a temporal value between time zones. | SQL |
curdate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.curdate() → date | Return the current date. | SQL |
curtime
| Signature | Purpose | Source definition |
|---|---|---|
mysql.curtime() → time without time zone | Return the current time of day. | SQL |
mysql.curtime(prec integer) → time without time zone | Return the current time of day. | SQL |
date
| Signature | Purpose | Source definition |
|---|---|---|
mysql.date(numeric) → date | Extract or parse a date. | SQL |
pg_catalog.date(text) → date | Extract or parse a date. | SQL |
date_add
| Signature | Purpose | Source definition |
|---|---|---|
mysql.date_add(date, interval) → date | Add a day count or interval to a date. | SQL |
mysql.date_add(numeric, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.date_add(text, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
mysql.date_add(timestamp without time zone, interval) → timestamp without time zone | Add a day count or interval to a date. | SQL |
date_format
| Signature | Purpose | Source definition |
|---|---|---|
mysql.date_format(text, text) → text | Format a date with MySQL percent directives. | SQL |
mysql.date_format(timestamp with time zone, text) → text | Format a date with MySQL percent directives. | SQL |
date_sub
| Signature | Purpose | Source definition |
|---|---|---|
mysql.date_sub(date, interval) → date | Subtract a day count or interval from a date. | SQL |
mysql.date_sub(numeric, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.date_sub(text, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.date_sub(timestamp without time zone, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
datediff
| Signature | Purpose | Source definition |
|---|---|---|
mysql.datediff(date, date) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(numeric, numeric) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(numeric, text) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(text, numeric) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(text, text) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(text, timestamp without time zone) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(timestamp without time zone, text) → integer | Return the difference between two dates in days. | SQL |
mysql.datediff(timestamp without time zone, timestamp without time zone) → integer | Return the difference between two dates in days. | SQL |
day
| Signature | Purpose | Source definition |
|---|---|---|
mysql.day(numeric) → integer | Return the day of the month. | SQL |
mysql.day(text) → integer | Return the day of the month. | SQL |
mysql.day(timestamp without time zone) → integer | Return the day of the month. | SQL |
dayname
| Signature | Purpose | Source definition |
|---|---|---|
mysql.dayname(numeric) → text | Return the weekday name. | SQL |
mysql.dayname(text) → text | Return the weekday name. | SQL |
mysql.dayname(timestamp without time zone) → text | Return the weekday name. | SQL |
dayofmonth
| Signature | Purpose | Source definition |
|---|---|---|
mysql.dayofmonth(numeric) → integer | Return the day of the month. | SQL |
mysql.dayofmonth(text) → integer | Return the day of the month. | SQL |
mysql.dayofmonth(timestamp without time zone) → integer | Return the day of the month. | SQL |
dayofweek
| Signature | Purpose | Source definition |
|---|---|---|
mysql.dayofweek(numeric) → integer | Number weekdays starting with Sunday as 1. | SQL |
mysql.dayofweek(text) → integer | Number weekdays starting with Sunday as 1. | SQL |
mysql.dayofweek(timestamp without time zone) → integer | Number weekdays starting with Sunday as 1. | SQL |
dayofyear
| Signature | Purpose | Source definition |
|---|---|---|
mysql.dayofyear(numeric) → integer | Return the ordinal day of the year. | SQL |
mysql.dayofyear(text) → integer | Return the ordinal day of the year. | SQL |
mysql.dayofyear(timestamp without time zone) → integer | Return the ordinal day of the year. | SQL |
extract
| Signature | Purpose | Source definition |
|---|---|---|
mysql."extract"(text, text) → numeric | Extract the requested date or time field. | SQL |
mysql."extract"(text, time without time zone) → numeric | Extract the requested date or time field. | SQL · C |
mysql."extract"(text, timestamp without time zone) → numeric | Extract the requested date or time field. | SQL · C |
from_days
| Signature | Purpose | Source definition |
|---|---|---|
mysql.from_days(integer) → date | Convert a MySQL day number to a date. | SQL |
from_unixtime
| Signature | Purpose | Source definition |
|---|---|---|
mysql.from_unixtime(double precision) → timestamp without time zone | Convert Unix time to a date/time value or formatted string. | SQL |
mysql.from_unixtime(double precision, text) → text | Convert Unix time to a date/time value or formatted string. | SQL |
hour
| Signature | Purpose | Source definition |
|---|---|---|
mysql.hour(text) → integer | Extract the hour. | SQL |
mysql.hour(time without time zone) → integer | Extract the hour. | SQL |
mysql.hour(timestamp without time zone) → integer | Extract the hour. | SQL |
last_day
| Signature | Purpose | Source definition |
|---|---|---|
mysql.last_day(date) → date | Find the last date of the month. | SQL |
mysql.last_day(numeric) → date | Find the last date of the month. | SQL |
mysql.last_day(text) → date | Find the last date of the month. | SQL |
mysql.last_day(timestamp with time zone) → date | Find the last date of the month. | SQL |
mysql.last_day(timestamp without time zone) → date | Find the last date of the month. | SQL |
makedate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.makedate(integer, integer) → date | Build a date from a year and day of year. | SQL |
maketime
| Signature | Purpose | Source definition |
|---|---|---|
mysql.maketime(integer, integer, numeric) → time without time zone | Build a time from hours, minutes and seconds. | SQL |
microsecond
| Signature | Purpose | Source definition |
|---|---|---|
mysql.microsecond(text) → integer | Extract microseconds. | SQL |
mysql.microsecond(time without time zone) → integer | Extract microseconds. | SQL |
mysql.microsecond(timestamp without time zone) → integer | Extract microseconds. | SQL |
minute
| Signature | Purpose | Source definition |
|---|---|---|
mysql.minute(text) → integer | Extract minutes. | SQL |
mysql.minute(time without time zone) → integer | Extract minutes. | SQL |
mysql.minute(timestamp without time zone) → integer | Extract minutes. | SQL |
month
| Signature | Purpose | Source definition |
|---|---|---|
mysql.month(numeric) → integer | Return the month number. | SQL |
mysql.month(text) → integer | Return the month number. | SQL |
mysql.month(timestamp without time zone) → integer | Return the month number. | SQL |
monthname
| Signature | Purpose | Source definition |
|---|---|---|
mysql.monthname(numeric) → text | Return the month name. | SQL |
mysql.monthname(text) → text | Return the month name. | SQL |
mysql.monthname(timestamp without time zone) → text | Return the month name. | SQL |
now
| Signature | Purpose | Source definition |
|---|---|---|
mysql.now() → timestamp without time zone | Return the transaction’s current timestamp. | SQL |
mysql.now(prec integer) → timestamp without time zone | Return the transaction’s current timestamp. | SQL |
period_add
| Signature | Purpose | Source definition |
|---|---|---|
mysql.period_add(integer, integer) → text | Add months to a year-month period. | SQL |
period_diff
| Signature | Purpose | Source definition |
|---|---|---|
mysql.period_diff(integer, integer) → integer | Find the difference between year-month periods in months. | SQL |
quarter
| Signature | Purpose | Source definition |
|---|---|---|
mysql.quarter(date) → integer | Return the quarter of the year. | SQL |
mysql.quarter(numeric) → integer | Return the quarter of the year. | SQL |
mysql.quarter(text) → integer | Return the quarter of the year. | SQL |
mysql.quarter(timestamp without time zone) → integer | Return the quarter of the year. | SQL |
sec_to_time
| Signature | Purpose | Source definition |
|---|---|---|
mysql.sec_to_time(bigint) → time without time zone | Convert seconds to a time value. | SQL |
second
| Signature | Purpose | Source definition |
|---|---|---|
mysql.second(text) → integer | Extract seconds. | SQL |
mysql.second(time without time zone) → integer | Extract seconds. | SQL |
mysql.second(timestamp without time zone) → integer | Extract seconds. | SQL |
str_to_date
| Signature | Purpose | Source definition |
|---|---|---|
mysql.str_to_date(text, text) → timestamp without time zone | Parse a date or time with a MySQL format string. | SQL |
subdate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.subdate(date, integer) → date | Subtract a day count or interval from a date. | SQL |
mysql.subdate(date, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(numeric, integer) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(numeric, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(text, integer) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(text, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(timestamp without time zone, integer) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
mysql.subdate(timestamp without time zone, interval) → timestamp without time zone | Subtract a day count or interval from a date. | SQL |
subtime
sysdate
| Signature | Purpose | Source definition |
|---|---|---|
mysql.sysdate() → timestamp without time zone | Read the wall clock at execution time. | SQL |
mysql.sysdate(prec integer) → timestamp without time zone | Read the wall clock at execution time. | SQL |
time_format
| Signature | Purpose | Source definition |
|---|---|---|
mysql.time_format(time without time zone, text) → text | Format a time value. | SQL |
time_to_sec
| Signature | Purpose | Source definition |
|---|---|---|
mysql.time_to_sec(text) → bigint | Convert a time value to seconds. | SQL |
mysql.time_to_sec(time without time zone) → bigint | Convert a time value to seconds. | SQL |
mysql.time_to_sec(timestamp without time zone) → bigint | Convert a time value to seconds. | SQL |
timediff
| Signature | Purpose | Source definition |
|---|---|---|
mysql.timediff(text, text) → text | Return the difference between two time values. | SQL · C |
mysql.timediff(time without time zone, time without time zone) → text | Return the difference between two time values. | SQL |
mysql.timediff(timestamp without time zone, timestamp without time zone) → text | Return the difference between two time values. | SQL · C |
timestamp
| Signature | Purpose | Source definition |
|---|---|---|
mysql."timestamp"(text, text) → timestamp without time zone | Build a timestamp from the supplied date/time arguments. | SQL |
timestampadd
| Signature | Purpose | Source definition |
|---|---|---|
mysql.timestampadd(text, integer, timestamp without time zone) → timestamp without time zone | Add a quantity in the specified temporal unit. | SQL |
timestampdiff
| Signature | Purpose | Source definition |
|---|---|---|
mysql.timestampdiff(unit text, ts1 text, ts2 text) → bigint | Measure a timestamp difference in the specified unit. | SQL |
mysql.timestampdiff(unit text, ts1 timestamp without time zone, ts2 timestamp without time zone) → bigint | Measure a timestamp difference in the specified unit. | SQL · C |
to_days
| Signature | Purpose | Source definition |
|---|---|---|
mysql.to_days(date) → integer | Convert a date to a MySQL day number. | SQL |
mysql.to_days(text) → integer | Convert a date to a MySQL day number. | SQL |
mysql.to_days(timestamp without time zone) → integer | Convert a date to a MySQL day number. | SQL |
unix_timestamp
| Signature | Purpose | Source definition |
|---|---|---|
mysql.unix_timestamp() → bigint | Return seconds since the Unix epoch. | SQL |
mysql.unix_timestamp(numeric) → numeric | Return seconds since the Unix epoch. | SQL |
mysql.unix_timestamp(text) → numeric | Return seconds since the Unix epoch. | SQL |
mysql.unix_timestamp(timestamp without time zone) → numeric | Return seconds since the Unix epoch. | SQL |
utc_date
| Signature | Purpose | Source definition |
|---|---|---|
mysql.utc_date() → date | Return the current date in UTC. | SQL |
utc_time
| Signature | Purpose | Source definition |
|---|---|---|
mysql.utc_time() → time without time zone | Return the current time of day in UTC. | SQL |
mysql.utc_time(prec integer) → time without time zone | Return the current time of day in UTC. | SQL |
utc_timestamp
| Signature | Purpose | Source definition |
|---|---|---|
mysql.utc_timestamp() → timestamp without time zone | Return the current UTC timestamp. | SQL |
mysql.utc_timestamp(prec integer) → timestamp without time zone | Return the current UTC timestamp. | SQL |
week
| Signature | Purpose | Source definition |
|---|---|---|
mysql.week(numeric) → integer | Return the week number under the selected week mode. | SQL |
mysql.week(numeric, integer) → integer | Return the week number under the selected week mode. | SQL |
mysql.week(text) → integer | Return the week number under the selected week mode. | SQL |
mysql.week(text, integer) → integer | Return the week number under the selected week mode. | SQL |
mysql.week(timestamp without time zone) → integer | Return the week number under the selected week mode. | SQL |
mysql.week(timestamp without time zone, integer) → integer | Return the week number under the selected week mode. | SQL |
weekday
| Signature | Purpose | Source definition |
|---|---|---|
mysql.weekday(numeric) → integer | Number weekdays starting with Monday as 0. | SQL |
mysql.weekday(text) → integer | Number weekdays starting with Monday as 0. | SQL |
mysql.weekday(timestamp without time zone) → integer | Number weekdays starting with Monday as 0. | SQL |
weekofyear
| Signature | Purpose | Source definition |
|---|---|---|
mysql.weekofyear(numeric) → integer | Return the week of the year. | SQL |
mysql.weekofyear(text) → integer | Return the week of the year. | SQL |
mysql.weekofyear(timestamp without time zone) → integer | Return the week of the year. | SQL |
year
| Signature | Purpose | Source definition |
|---|---|---|
mysql.year(date) → integer | Extract the year. | SQL |
mysql.year(numeric) → integer | Extract the year. | SQL |
mysql.year(text) → integer | Extract the year. | SQL |
mysql.year(timestamp without time zone) → integer | Extract the year. | SQL |
yearweek
| Signature | Purpose | Source definition |
|---|---|---|
mysql.yearweek(numeric) → integer | Return the week and its associated year. | SQL |
mysql.yearweek(qdate numeric, mode integer) → integer | Return the week and its associated year. | SQL |
mysql.yearweek(qdate text, mode integer) → integer | Return the week and its associated year. | SQL |
mysql.yearweek(qdate timestamp without time zone, mode integer) → integer | Return the week and its associated year. | SQL |
mysql.yearweek(text) → integer | Return the week and its associated year. | SQL |
mysql.yearweek(timestamp without time zone) → integer | Return the week and its associated year. | SQL |
5.2.2.5.4 - Conditional functions
IF, IFNULL and ISNULL. Match each branch’s type as well as the condition type.
if
ifnull
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ifnull(bigint, bigint) → bigint | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(bigint, character varying) → character varying | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(boolean, boolean) → boolean | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(bytea, bytea) → bytea | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(character varying, bigint) → character varying | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(character varying, character varying) → character varying | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(character varying, character) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(character varying, text) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(character, character varying) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(character, character) → character | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(character, text) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(date, date) → date | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(double precision, double precision) → double precision | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(integer, integer) → integer | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(mysql."smallint", mysql."smallint") → mysql."smallint" | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(mysql.double, mysql.double) → mysql.double | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(mysql.tinyint, mysql.tinyint) → mysql.tinyint | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(numeric, numeric) → numeric | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 bigint, p2 text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 boolean, p2 text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 date, p2 text) → timestamp without time zone | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 integer, p2 text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 mysql."smallint", p2 text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 numeric, p2 text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 time without time zone, p2 text) → timestamp without time zone | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 timestamp with time zone, p2 text) → timestamp with time zone | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(p1 timestamp without time zone, p2 text) → timestamp without time zone | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(text, bigint) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(text, character varying) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(text, character) → character varying | Return the first value when present, otherwise the fallback. | Generated definition |
mysql.ifnull(text, text) → text | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(time without time zone, time without time zone) → time without time zone | Return the first value when present, otherwise the fallback. | SQL |
mysql.ifnull(timestamp without time zone, timestamp without time zone) → timestamp without time zone | Return the first value when present, otherwise the fallback. | SQL |
isnull
5.2.2.5.5 - Session functions
Connection identity, selected database, named locks and statement state.
connection_id
| Signature | Purpose | Source definition |
|---|---|---|
mysql.connection_id() → bigint | Return the PostgreSQL backend PID for this connection. | SQL |
current_user
| Signature | Purpose | Source definition |
|---|---|---|
mysql."current_user"() → text | Effective PostgreSQL role formatted as role@%. | SQL · C |
database
| Signature | Purpose | Source definition |
|---|---|---|
mysql.database() → text | Return the MySQL database selected in this session. | SQL · C |
found_rows
| Signature | Purpose | Source definition |
|---|---|---|
mysql.found_rows() → bigint | Read the session’s found-row count. | SQL · C |
get_lock
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_lock("any", "any") → bigint | Acquire a named session lock with a timeout. | SQL · C |
is_free_lock
| Signature | Purpose | Source definition |
|---|---|---|
mysql.is_free_lock("any") → bigint | Check whether a named lock is available. | SQL · C |
is_used_lock
| Signature | Purpose | Source definition |
|---|---|---|
mysql.is_used_lock("any") → bigint | Look up the holder of a named lock. | SQL · C |
last_insert_id
| Signature | Purpose | Source definition |
|---|---|---|
mysql.last_insert_id() → bigint | Read the session’s last generated insert ID. | SQL · C |
release_all_locks
| Signature | Purpose | Source definition |
|---|---|---|
mysql.release_all_locks() → bigint | Release all named locks held by this session. | SQL · C |
release_lock
| Signature | Purpose | Source definition |
|---|---|---|
mysql.release_lock("any") → bigint | Release a named session lock. | SQL · C |
row_count
| Signature | Purpose | Source definition |
|---|---|---|
mysql.row_count() → bigint | Read the affected-row count for the previous statement. | SQL · C |
schema
| Signature | Purpose | Source definition |
|---|---|---|
mysql.schema() → text | Return the MySQL database selected in this session. | SQL · C |
session_user
| Signature | Purpose | Source definition |
|---|---|---|
mysql."session_user"() → text | Session role and client host. | SQL · C |
sleep
| Signature | Purpose | Source definition |
|---|---|---|
mysql.sleep(seconds numeric) → character varying | Wait for the requested number of seconds. | SQL |
user
| Signature | Purpose | Source definition |
|---|---|---|
mysql."user"() → text | Return PostgreSQL current_user as text. | SQL |
uuid
| Signature | Purpose | Source definition |
|---|---|---|
mysql.uuid() → text | Generate a UUID. | SQL |
uuid_short
| Signature | Purpose | Source definition |
|---|---|---|
mysql.uuid_short() → text | Generate a short MySQL-style identifier. | SQL · C |
version
| Signature | Purpose | Source definition |
|---|---|---|
mysql.version() → text | Return the advertised MySQL server version. | SQL · C |
5.2.2.5.6 - Type conversion helpers
Internal routines used by casts, coercion and expression rewriting.
B
C
H
I
| Signature | Purpose | Source definition |
|---|---|---|
mysql."interval"(text, integer) → interval | Convert text to interval. | SQL · C |
S
| Signature | Purpose | Source definition |
|---|---|---|
mysql.str_to_double(text) → double precision | Parse a string as a floating-point value. | SQL |
T
| Signature | Purpose | Source definition |
|---|---|---|
mysql.time_to_timestamp(time without time zone) → timestamp without time zone | Convert time without time zone to timestamp without time zone. | SQL |
V
5.2.2.5.7 - Comparison operator functions
Internal entry points behind equality and ordering comparisons.
A
| Signature | Purpose | Source definition |
|---|---|---|
mysql.anycompatibleeqbytea(anycompatible, bytea) → boolean | Implements = (equal). | SQL · C |
mysql.anycompatiblegebytea(anycompatible, bytea) → boolean | Implements >= (greater than or equal). | SQL · C |
mysql.anycompatiblegtbytea(anycompatible, bytea) → boolean | Implements > (greater than). | SQL · C |
mysql.anycompatiblelebytea(anycompatible, bytea) → boolean | Implements <= (less than or equal). | SQL · C |
mysql.anycompatibleltbytea(anycompatible, bytea) → boolean | Implements < (less than). | SQL · C |
mysql.anycompatiblenebytea(anycompatible, bytea) → boolean | Implements <> (not equal). | SQL · C |
B
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.char_eq_char_for_date_format(character, character) → boolean | Implements =# (compare format-specifier characters). | SQL · C |
D
| Signature | Purpose | Source definition |
|---|---|---|
mysql.date_eq_text(date, text) → boolean | Implements = (equal). | SQL |
mysql.date_ge_text(date, text) → boolean | Implements >= (greater than or equal). | SQL |
mysql.date_gt_text(date, text) → boolean | Implements > (greater than). | SQL |
mysql.date_le_text(date, text) → boolean | Implements <= (less than or equal). | SQL |
mysql.date_lt_text(date, text) → boolean | Implements < (less than). | SQL |
mysql.date_ne_text(date, text) → boolean | Implements <> (not equal). | SQL |
mysql.dateeqtext(date, text) → boolean | Test equality after converting the operands. | SQL |
mysql.datenetext(date, text) → boolean | Test inequality after converting the operands. | SQL |
F
| Signature | Purpose | Source definition |
|---|---|---|
mysql.float8_eq_hexlit(double precision, mysql.hexlit) → boolean | Implements = (equal). | Generated definition |
mysql.float8_ge_hexlit(double precision, mysql.hexlit) → boolean | Implements >= (greater than or equal). | Generated definition |
mysql.float8_gt_hexlit(double precision, mysql.hexlit) → boolean | Implements > (greater than). | Generated definition |
mysql.float8_le_hexlit(double precision, mysql.hexlit) → boolean | Implements <= (less than or equal). | Generated definition |
mysql.float8_lt_hexlit(double precision, mysql.hexlit) → boolean | Implements < (less than). | Generated definition |
mysql.float8_ne_hexlit(double precision, mysql.hexlit) → boolean | Implements <> (not equal). | Generated definition |
mysql.float8_nseq_hexlit(double precision, mysql.hexlit) → boolean | Implements <=> (null-safe equality). | Generated definition |
H
I
N
S
| Signature | Purpose | Source definition |
|---|---|---|
mysql.smallintbgeqtext(mysql."smallint", text) → boolean | Implements >= (greater than or equal). | SQL |
mysql.smallintbgtext(mysql."smallint", text) → boolean | Implements > (greater than). | SQL |
mysql.smallintleeqtext(mysql."smallint", text) → boolean | Implements <= (less than or equal). | SQL |
mysql.smallintletext(mysql."smallint", text) → boolean | Implements < (less than). | SQL |
T
V
5.2.2.5.8 - Arithmetic operator functions
Internal routines for arithmetic on mixed MySQL operand types.
_
| Signature | Purpose | Source definition |
|---|---|---|
mysql._add_bool(boolean) → smallint | Implements + (unary plus). | SQL |
mysql._add_null(text) → smallint | Implements + (unary plus). | SQL |
mysql._sub_bool(boolean) → smallint | Implements - (unary minus). | SQL |
mysql._sub_null(text) → smallint | Implements - (unary minus). | SQL |
A
| Signature | Purpose | Source definition |
|---|---|---|
mysql.anycompatibledivbytea(anycompatible, bytea) → numeric | Implements / (division). | SQL · C |
mysql.anycompatiblemibytea(anycompatible, bytea) → numeric | Implements - (subtraction). | SQL · C |
mysql.anycompatiblemodbytea(anycompatible, bytea) → numeric | Implements % (remainder). | SQL · C |
mysql.anycompatiblemulbytea(anycompatible, bytea) → numeric | Implements * (multiplication). | SQL · C |
mysql.anycompatibleplbytea(anycompatible, bytea) → numeric | Implements + (addition). | SQL · C |
B
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.char_add_bigint(character, bigint) → bigint | Implements + (addition). | SQL |
mysql.char_add_char(character, character) → bigint | Implements + (addition). | SQL |
mysql.char_divide_bigint(character, bigint) → bigint | Compute the quotient. | SQL |
mysql.char_divide_char(character, character) → bigint | Compute the quotient. | SQL |
mysql.char_minus_bigint(character, bigint) → bigint | Implements - (subtraction). | SQL |
mysql.char_minus_char(character, character) → bigint | Implements - (subtraction). | SQL |
mysql.char_mod_bigint(character, bigint) → bigint | Implements % (remainder). | SQL |
mysql.char_mod_char(character, character) → bigint | Implements % (remainder). | SQL |
mysql.char_multi_bigint(character, bigint) → bigint | Implements * (multiplication). | SQL |
mysql.char_multi_char(character, character) → bigint | Implements * (multiplication). | SQL |
D
F
| Signature | Purpose | Source definition |
|---|---|---|
mysql.float8_div_hexlit(double precision, mysql.hexlit) → double precision | Implements / (division). | Generated definition |
mysql.float8_mi_hexlit(double precision, mysql.hexlit) → double precision | Implements - (subtraction). | Generated definition |
mysql.float8_mod_hexlit(double precision, mysql.hexlit) → double precision | Implements % (remainder). | Generated definition |
mysql.float8_mul_hexlit(double precision, mysql.hexlit) → double precision | Implements * (multiplication). | Generated definition |
mysql.float8_pl_hexlit(double precision, mysql.hexlit) → double precision | Implements + (addition). | Generated definition |
H
I
M
N
| Signature | Purpose | Source definition |
|---|---|---|
mysql.numeric_div_hexlit(numeric, mysql.hexlit) → numeric | Implements / (division). | Generated definition |
mysql.numeric_mi_hexlit(numeric, mysql.hexlit) → numeric | Implements - (subtraction). | Generated definition |
mysql.numeric_mod_hexlit(numeric, mysql.hexlit) → numeric | Implements % (remainder). | Generated definition |
mysql.numeric_mul_hexlit(numeric, mysql.hexlit) → numeric | Implements * (multiplication). | Generated definition |
mysql.numeric_pl_hexlit(numeric, mysql.hexlit) → numeric | Implements + (addition). | Generated definition |
T
V
5.2.2.5.9 - Bitwise and logical operator functions
Internal routines for bit operations and truth-value tests.
A
| Signature | Purpose | Source definition |
|---|---|---|
mysql.anycompatibleandbytea(anycompatible, bytea) → bigint | Implements & (bitwise and). | SQL · C |
mysql.anycompatiblecondandbytea(anycompatible, bytea) → boolean | Implements && (logical and). | SQL · C |
mysql.anycompatiblecondorbytea(anycompatible, bytea) → boolean | Implements || (logical or). | SQL · C |
mysql.anycompatiblenonarray_or_text(anycompatiblenonarray, text) → boolean | Implements || (logical or). | SQL |
mysql.anycompatibleorbytea(anycompatible, bytea) → bigint | Implements | (bitwise or). | SQL · C |
mysql.anynonarray_or_text(anynonarray, text) → boolean | Evaluate OR after operand coercion. | SQL |
B
F
| Signature | Purpose | Source definition |
|---|---|---|
mysql.float8_and_hexlit(double precision, mysql.hexlit) → bigint | Implements & (bitwise and). | Generated definition |
mysql.float8_or_hexlit(double precision, mysql.hexlit) → bigint | Implements | (bitwise or). | Generated definition |
mysql.float8_shl_hexlit(double precision, mysql.hexlit) → bigint | Implements << (left shift). | Generated definition |
mysql.float8_shr_hexlit(double precision, mysql.hexlit) → bigint | Implements >> (right shift). | Generated definition |
mysql.float8_xor_hexlit(double precision, mysql.hexlit) → bigint | Implements ^# (bitwise xor). | Generated definition |
H
I
N
T
| Signature | Purpose | Source definition |
|---|---|---|
mysql.text_and_hexlit(text, mysql.hexlit) → bigint | Implements & (bitwise and). | Generated definition |
mysql.text_and_text(text, text) → boolean | Implements && (logical and). | SQL |
mysql.text_or_anycompatiblenonarray(text, anycompatiblenonarray) → boolean | Implements || (logical or). | SQL |
mysql.text_or_anynoarray(text, anynonarray) → boolean | Evaluate OR after operand coercion. | SQL |
mysql.text_or_hexlit(text, mysql.hexlit) → bigint | Implements | (bitwise or). | Generated definition |
mysql.text_or_text(text, text) → boolean | Implements || (logical or). | SQL |
mysql.text_shl_hexlit(text, mysql.hexlit) → bigint | Implements << (left shift). | Generated definition |
mysql.text_shr_hexlit(text, mysql.hexlit) → bigint | Implements >> (right shift). | Generated definition |
mysql.text_xor_hexlit(text, mysql.hexlit) → bigint | Implements ^# (bitwise xor). | Generated definition |
V
| Signature | Purpose | Source definition |
|---|---|---|
mysql.varbit_and_hexlit(bit varying, mysql.hexlit) → bigint | Implements & (bitwise and). | Generated definition |
mysql.varbit_or_hexlit(bit varying, mysql.hexlit) → bigint | Implements | (bitwise or). | Generated definition |
mysql.varbit_shl_hexlit(bit varying, mysql.hexlit) → bigint | Implements << (left shift). | Generated definition |
mysql.varbit_shr_hexlit(bit varying, mysql.hexlit) → bigint | Implements >> (right shift). | Generated definition |
mysql.varbit_xor_hexlit(bit varying, mysql.hexlit) → bigint | Implements ^# (bitwise xor). | Generated definition |
5.2.2.5.10 - Pattern and JSON operator functions
Internal routines for LIKE, regular expressions and JSON field access.
A
| Signature | Purpose | Source definition |
|---|---|---|
mysql.anycompatiblelikebytea(anycompatible, bytea) → boolean | Implements ~~ (like pattern match). | SQL · C |
mysql.anycompatiblenlikebytea(anycompatible, bytea) → boolean | Implements !~~ (negated like match). | SQL · C |
mysql.anycompatiblenregexpbinbytea(anycompatible, bytea) → boolean | Implements !~ (negated case-sensitive regular expression match). | SQL · C |
mysql.anycompatiblenregexpbytea(anycompatible, bytea) → boolean | Implements !~* (negated case-insensitive regular expression match). | SQL · C |
mysql.anycompatibleregexpbinbytea(anycompatible, bytea) → boolean | Implements ~ (case-sensitive regular expression match). | SQL · C |
mysql.anycompatibleregexpbytea(anycompatible, bytea) → boolean | Implements ~* (case-insensitive regular expression match). | SQL · C |
B
H
| Signature | Purpose | Source definition |
|---|---|---|
mysql.hexlit_like(mysql.hexlit, mysql.hexlit) → boolean | Implements ~~ (like pattern match). | Generated definition |
mysql.hexlit_like_bytea(mysql.hexlit, bytea) → boolean | Implements ~~ (like pattern match). | Generated definition |
mysql.hexlit_like_text(mysql.hexlit, text) → boolean | Implements ~~ (like pattern match). | Generated definition |
mysql.hexlit_nlike(mysql.hexlit, mysql.hexlit) → boolean | Implements !~~ (negated like match). | Generated definition |
mysql.hexlit_nlike_bytea(mysql.hexlit, bytea) → boolean | Implements !~~ (negated like match). | Generated definition |
mysql.hexlit_nlike_text(mysql.hexlit, text) → boolean | Implements !~~ (negated like match). | Generated definition |
J
| Signature | Purpose | Source definition |
|---|---|---|
mysql.json_object_field(from_json json, field_name text) → json | Implements -> (extract a json field by name). | SQL |
P
| Signature | Purpose | Source definition |
|---|---|---|
mysql.prefix_like(character, text) → boolean | Implements | SQL · C |
mysql.prefix_like(text, text) → boolean | Implements | SQL · C |
mysql.prefix_not_like(character, text) → boolean | Implements ! | SQL · C |
mysql.prefix_not_like(text, text) → boolean | Implements ! | SQL · C |
R
| Signature | Purpose | Source definition |
|---|---|---|
mysql.regular_expr(bigint, text) → boolean | Implements ~* (case-insensitive regular expression match). | SQL |
mysql.regular_expr_not(bigint, text) → boolean | Implements !~* (negated case-insensitive regular expression match). | SQL |
T
| Signature | Purpose | Source definition |
|---|---|---|
mysql.text_like_bigint(text, bigint) → boolean | Implements ~~ (like pattern match). | SQL |
mysql.text_like_hexlit(text, mysql.hexlit) → boolean | Implements ~~ (like pattern match). | Generated definition |
mysql.text_nlike_hexlit(text, mysql.hexlit) → boolean | Implements !~~ (negated like match). | Generated definition |
mysql.text_not_like_bigint(text, bigint) → boolean | Implements !~~ (negated like match). | SQL |
5.2.2.5.11 - String and number helpers
Internal routines used by string searches, validation and rounding.
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.ceil_for_mysql(text) → bigint | Round a number parsed from text up to an integer. | SQL · C |
mysql.check_set(text, text) → boolean | Check a value against a SET definition. | SQL · C |
F
| Signature | Purpose | Source definition |
|---|---|---|
mysql.floor_for_mysql(text) → bigint | Round a number parsed from text down to an integer. | SQL · C |
I
| Signature | Purpose | Source definition |
|---|---|---|
mysql.is_numeric(text) → boolean | Validate the numeric representation. | SQL |
mysql.is_valid_binary(text) → boolean | Validate the numeric representation. | SQL · C |
mysql.is_valid_hex(text) → boolean | Validate the numeric representation. | SQL · C |
T
| Signature | Purpose | Source definition |
|---|---|---|
mysql.text_instr(text, text) → integer | Find a substring for LOCATE or INSTR. | SQL · C |
mysql.text_locate2(text, text) → integer | Find a substring for LOCATE or INSTR. | SQL · C |
mysql.text_locate3(text, text, bigint) → integer | Find a substring for LOCATE or INSTR. | SQL · C |
5.2.2.5.12 - Temporal conversion helpers
Internal routines for date normalization, week modes and numeric date arithmetic.
_
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.convert_to_time_format(text) → interval | Normalize date/time input for conversion to interval. | SQL |
mysql.curdate_add(integer) → integer | Apply integer arithmetic to today’s YYYYMMDD value. | SQL |
mysql.curdate_sub(integer) → integer | Apply integer arithmetic to today’s YYYYMMDD value. | SQL |
N
| Signature | Purpose | Source definition |
|---|---|---|
mysql.numeric_timestamp(numeric) → timestamp without time zone | Normalize date/time input for conversion to timestamp without time zone. | SQL |
Function names in r4
Installation snapshot (0d51adc) | r4 source (1e631f9) |
|---|---|
mysql._convert_format_to_halo_for_number_datetime | mysql._normalize_numeric_datetime |
mysql._convert_format_to_halo_for_string_datetime | mysql._normalize_datetime_text |
mysql._convert_format_to_halo_for_string_number_datetime | mysql._normalize_compact_datetime_text |
mysql._convert_format_to_halo_for_string_string_datetime | mysql._normalize_delimited_datetime_text |
5.2.2.5.13 - Binary and string storage helpers
Internal routines for type I/O, binary expression evaluation and string results.
A
B
| Signature | Purpose | Source definition |
|---|---|---|
mysql.binary_n_in(cstring, oid, integer) → mysql.binary_n | Read the text format of a binary value. | Generated definition · C |
mysql.binary_n_out(mysql.binary_n) → cstring | Write the text format of a binary value. | Generated definition |
mysql.binary_n_recv(internal, oid, integer) → mysql.binary_n | Receive the PostgreSQL binary representation. | Generated definition · C |
mysql.binary_n_send(mysql.binary_n) → bytea | Send the PostgreSQL binary representation. | Generated definition |
mysql.binary_n_typmodin(cstring[]) → integer | Parse the declared length modifier. | Generated definition · C |
mysql.binary_n_typmodout(integer) → cstring | Format the length modifier. | Generated definition · C |
mysql.binary_truth("any") → boolean | Evaluate the truth value of a binary or string operand. | SQL · C |
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.cast_char("any", integer) → text | Convert an expression to the requested character representation. | SQL · C |
mysql.concat_one("any") → text | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | SQL · C |
mysql.concat_one(bytea) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition · C |
mysql.concat_one(character) → text | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | SQL · C |
mysql.concat_one(mysql.binary_n) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition · C |
mysql.concat_one(mysql.hexlit) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition · C |
mysql.concat_one(mysql.varbinary_n) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition · C |
mysql.concat_one(text) → text | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition · C |
mysql.concat_pair(bytea, bytea) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition |
mysql.concat_pair(bytea, text) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition |
mysql.concat_pair(text, bytea) → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition |
mysql.concat_pair(text, text) → text | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | Generated definition |
mysql.concat_ws_bytes(VARIADIC "any") → bytea | Combine string operands for CONCAT or CONCAT_WS while preserving binary results. | SQL · C |
mysql.convert_using("any", text) → text | Convert an expression to the requested character representation. | SQL · C |
E
| Signature | Purpose | Source definition |
|---|---|---|
mysql.elt_index("any") → integer | Convert the selector for ELT into a position. | SQL · C |
H
| Signature | Purpose | Source definition |
|---|---|---|
mysql.hexlit_cmp_support(internal) → internal | Provide planner support for comparisons with a hex literal. | SQL · C |
mysql.hexlit_in(cstring) → mysql.hexlit | Read the text format of a binary value. | SQL |
mysql.hexlit_out(mysql.hexlit) → cstring | Write the text format of a binary value. | SQL |
mysql.hexlit_recv(internal) → mysql.hexlit | Receive the PostgreSQL binary representation. | SQL |
mysql.hexlit_send(mysql.hexlit) → bytea | Send the PostgreSQL binary representation. | SQL |
M
| Signature | Purpose | Source definition |
|---|---|---|
mysql.mys_uint64_bitnot(numeric) → numeric | Evaluate a MySQL unsigned 64-bit bitwise expression. | SQL · C |
mysql.mys_uint64_bitop(numeric, numeric, "char") → bigint | Evaluate a MySQL unsigned 64-bit bitwise expression. | SQL · C |
R
| Signature | Purpose | Source definition |
|---|---|---|
mysql.raw_bytes("any") → bytea | Extract the underlying bytes of the value. | SQL · C |
S
| Signature | Purpose | Source definition |
|---|---|---|
mysql.string_result(anyelement, "any") → anyelement | Produce the string result of a rewritten expression. | SQL · C |
V
| Signature | Purpose | Source definition |
|---|---|---|
mysql.varbinary_n_in(cstring, oid, integer) → mysql.varbinary_n | Read the text format of a binary value. | Generated definition · C |
mysql.varbinary_n_out(mysql.varbinary_n) → cstring | Write the text format of a binary value. | Generated definition |
mysql.varbinary_n_recv(internal, oid, integer) → mysql.varbinary_n | Receive the PostgreSQL binary representation. | Generated definition · C |
mysql.varbinary_n_send(mysql.varbinary_n) → bytea | Send the PostgreSQL binary representation. | Generated definition |
mysql.varbinary_n_typmodin(cstring[]) → integer | Parse the declared length modifier. | Generated definition · C |
mysql.varbinary_n_typmodout(integer) → cstring | Format the length modifier. | Generated definition · C |
5.2.2.5.14 - Aggregate support functions
Internal transition and final functions invoked while computing an aggregate.
B
| Signature | Purpose | Source definition |
|---|---|---|
mysql.bit_and_varbit(bigint, bit varying) → bigint | Accumulate the next input into the aggregate state. | SQL |
mysql.bit_and_varbit_final(bigint) → bigint | Finalize the aggregate state. | SQL |
mysql.bit_or_varbit(bigint, bit varying) → bigint | Accumulate the next input into the aggregate state. | SQL |
mysql.bit_or_varbit_final(bigint) → bigint | Finalize the aggregate state. | SQL |
mysql.bit_xor_varbit(bigint, bit varying) → bigint | Accumulate the next input into the aggregate state. | SQL |
mysql.bit_xor_varbit_final(bigint) → bigint | Finalize the aggregate state. | SQL |
D
| Signature | Purpose | Source definition |
|---|---|---|
mysql.dummy_min_finalfunc_for_bytea(bytea) → bytea | Finalize the aggregate state. | SQL |
mysql.dummy_min_sfunc_for_bytea(bytea, bytea) → bytea | Accumulate the next input into the aggregate state. | SQL |
S
| Signature | Purpose | Source definition |
|---|---|---|
mysql.sum_bool(bigint, boolean) → bigint | Accumulate the next input into the aggregate state. | SQL |
mysql.sum_text(numeric, text) → numeric | Accumulate the next input into the aggregate state. | SQL |
mysql.sum_text_final(numeric) → numeric | Finalize the aggregate state. | SQL |
T
| Signature | Purpose | Source definition |
|---|---|---|
mysql.text_avg_accum(internal, text) → internal | Accumulate the next input into the aggregate state. | SQL · C |
5.2.2.5.15 - Index support functions
Internal functions for index access, key comparison, hashing and operator-class registration.
B
| Signature | Purpose | Source definition |
|---|---|---|
mysql.binary_n_cmp(mysql.binary_n, mysql.binary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.binary_n_cmp_bytea(mysql.binary_n, bytea) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.binary_n_cmp_varbinary_n(mysql.binary_n, mysql.varbinary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.binary_n_hash(mysql.binary_n) → integer | Hash the binary key for a hash index. | Generated definition |
mysql.binary_n_hash_extended(mysql.binary_n, bigint) → bigint | Hash the binary key for a hash index. | Generated definition |
mysql.bytea_cmp_binary_n(bytea, mysql.binary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.bytea_cmp_varbinary_n(bytea, mysql.varbinary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
H
| Signature | Purpose | Source definition |
|---|---|---|
mysql.hexlit_cmp(mysql.hexlit, mysql.hexlit) → integer | Compare binary keys in B-tree order. | SQL |
mysql.hexlit_hash(mysql.hexlit) → integer | Hash the binary key for a hash index. | SQL |
mysql.hexlit_hash_extended(mysql.hexlit, bigint) → bigint | Hash the binary key for a hash index. | SQL |
P
| Signature | Purpose | Source definition |
|---|---|---|
mysql.prefix_1042_cmp(character, character) → integer | Compare two keys for a mysql_prefix index. | Generated definition · C |
mysql.prefix_17_cmp(bytea, bytea) → integer | Compare two keys for a mysql_prefix index. | Generated definition · C |
mysql.prefix_25_cmp(text, text) → integer | Compare two keys for a mysql_prefix index. | Generated definition · C |
mysql.prefix_53875699983efc79eeb9e023e66605f5_cmp(mysql.binary_n, mysql.binary_n) → integer | Compare two keys for a mysql_prefix index. | Generated definition · C |
mysql.prefix_b8aba7e65857eaf6a91ca737fb14b87b_cmp(mysql.varbinary_n, mysql.varbinary_n) → integer | Compare two keys for a mysql_prefix index. | Generated definition · C |
mysql.prefix_handler(internal) → index_am_handler | Supply the mysql_prefix access method callbacks. | SQL · C |
mysql.prefix_options(internal) → void | Declare index operator-class options for prefix keys. | SQL · C |
R
| Signature | Purpose | Source definition |
|---|---|---|
mysql.register_prefix_binary(t regtype) → void | Register prefix-index support for a type. EXECUTE is restricted. | SQL |
mysql.register_prefix_type(t regtype, string_storage boolean) → void | Register prefix-index support for a type. EXECUTE is restricted. | SQL |
V
| Signature | Purpose | Source definition |
|---|---|---|
mysql.varbinary_n_cmp(mysql.varbinary_n, mysql.varbinary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.varbinary_n_cmp_binary_n(mysql.varbinary_n, mysql.binary_n) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.varbinary_n_cmp_bytea(mysql.varbinary_n, bytea) → integer | Compare binary keys in B-tree order. | Generated definition |
mysql.varbinary_n_hash(mysql.varbinary_n) → integer | Hash the binary key for a hash index. | Generated definition |
mysql.varbinary_n_hash_extended(mysql.varbinary_n, bigint) → bigint | Hash the binary key for a hash index. | Generated definition |
5.2.2.5.16 - Session state and variable helpers
Internal interfaces behind SET, SHOW, user variables and authentication cache management.
C
| Signature | Purpose | Source definition |
|---|---|---|
mysql.clear_user_variables() → void | Clear the session’s user variables. | SQL · C |
F
| Signature | Purpose | Source definition |
|---|---|---|
mysql.flush_auth_cache() → bigint | Clear the fast-authentication cache. EXECUTE is restricted. | SQL · C |
G
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_system_global_variable(text) → text | Read a global @@ variable. | SQL |
mysql.get_system_session_variable(text) → text | Read a session @@ variable. | SQL |
mysql.get_system_variable(text, boolean) → text | Resolve a system variable for its requested scope. | SQL · C |
mysql.get_user_var(variable_name character varying) → bytea | Read a MySQL @user variable. | SQL · C |
mysql.getenv(text) → text | Read a server environment variable for installation. EXECUTE is restricted. | SQL · C |
S
5.2.2.5.17 - DDL and write helpers
Internal routines invoked by column expressions, sequences and row triggers.
auto_increment_advance
| Signature | Purpose | Source definition |
|---|---|---|
mysql.auto_increment_advance() → trigger | Advance the sequence after an explicit AUTO_INCREMENT value. | SQL · C |
column_default
| Signature | Purpose | Source definition |
|---|---|---|
mysql.column_default(oid, integer) → text | Read a column’s default expression. | SQL · C |
generated_column
| Signature | Purpose | Source definition |
|---|---|---|
mysql.generated_column(text, anyelement) → anyelement | Carry a generated-column value through a rewritten expression. | SQL |
generated_numeric
| Signature | Purpose | Source definition |
|---|---|---|
mysql.generated_numeric(numeric, integer) → numeric | Apply the declared type modifier to a generated value. | SQL · C |
generated_value
| Signature | Purpose | Source definition |
|---|---|---|
mysql.generated_value(anyelement) → anyelement | Carry a generated-column value through a rewritten expression. | SQL |
generated_varchar
| Signature | Purpose | Source definition |
|---|---|---|
mysql.generated_varchar(text, integer, boolean) → text | Apply the declared type modifier to a generated value. | SQL · C |
lenient_float8
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lenient_float8(text) → double precision | Coerce a value for a non-strict INSERT or UPDATE. | SQL · C |
lenient_int
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lenient_int(text, bigint, bigint) → bigint | Coerce a value for a non-strict INSERT or UPDATE. | SQL · C |
lenient_numeric
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lenient_numeric(text, integer) → numeric | Coerce a value for a non-strict INSERT or UPDATE. | SQL · C |
lenient_varchar
| Signature | Purpose | Source definition |
|---|---|---|
mysql.lenient_varchar(text, integer) → text | Coerce a value for a non-strict INSERT or UPDATE. | SQL · C |
on_update_current_timestamp
| Signature | Purpose | Source definition |
|---|---|---|
mysql.on_update_current_timestamp() → trigger | Update timestamp columns from a row trigger. | SQL · C |
part_list_columns
| Signature | Purpose | Source definition |
|---|---|---|
mysql.part_list_columns(VARIADIC "any") → text | Build a list-partition column key. | SQL · C |
pending_fk_definitions
| Signature | Purpose | Source definition |
|---|---|---|
mysql.pending_fk_definitions(oid) → SETOF text | Format deferred foreign key definitions for a child relation. | SQL |
pending_fk_guard
| Signature | Purpose | Source definition |
|---|---|---|
mysql.pending_fk_guard() → trigger | Run the trigger for a pending foreign key. | SQL · C |
setval
| Signature | Purpose | Source definition |
|---|---|---|
mysql.setval(regclass, bigint, boolean) → bigint | Set a sequence value and its called flag. | SQL · C |
5.2.2.5.18 - SHOW and metadata helpers
Internal routines that format catalog values and construct result sets for MySQL clients.
amend_def_val
| Signature | Purpose | Source definition |
|---|---|---|
mysql.amend_def_val(text) → text | Format a PostgreSQL default expression for MySQL metadata. | SQL |
amend_def_val_for_internal
| Signature | Purpose | Source definition |
|---|---|---|
mysql.amend_def_val_for_internal(text) → text | Format a PostgreSQL default expression for MySQL metadata. | SQL |
column_domain
| Signature | Purpose | Source definition |
|---|---|---|
mysql.column_domain(oid, integer) → oid | Find the declared domain for a column. | SQL |
column_extra
| Signature | Purpose | Source definition |
|---|---|---|
mysql.column_extra(oid, integer) → text | Build the Extra field in column metadata. | SQL · C |
column_generation
| Signature | Purpose | Source definition |
|---|---|---|
mysql.column_generation(oid, integer) → text | Read the generation expression for a column. | SQL · C |
decimal_column_type
| Signature | Purpose | Source definition |
|---|---|---|
mysql.decimal_column_type(integer) → text | Decode DECIMAL precision and scale from a type modifier. | SQL · C |
decimal_ps
| Signature | Purpose | Source definition |
|---|---|---|
mysql.decimal_ps(integer) → integer[] | Decode DECIMAL precision and scale from a type modifier. | SQL |
get_column_extra
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_column_extra(text) → text | Build the Extra field in column metadata. | SQL |
get_column_key
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_column_key(oid, text) → text | Classify the index key for a column. | SQL |
mysql.get_column_key(text, text, text) → text | Classify the index key for a column. | SQL |
get_func_def
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_func_def(funcname text, procowner text, prorettype oid, proargtypes oidvector, proargnames text[], prosrc text) → text | Reconstruct a routine definition from its catalog fields. | SQL |
get_funcs_procs_parameters
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_funcs_procs_parameters() → SETOF record | List routine parameters for metadata clients. | SQL |
get_mysql_proc_arg_mode
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_mysql_proc_arg_mode(text) → text | Translate a PostgreSQL argument mode into a MySQL mode. | SQL |
get_mysql_type_name
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_mysql_type_name(oid) → text | Map a catalog type to its MySQL display name. | SQL |
get_proc_def
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_proc_def(funcname text, proallargtypes oid[], proargmodes "char"[], proargnames text[], prosrc text) → text | Reconstruct a routine definition from its catalog fields. | SQL |
mysql.get_proc_def(procname text, procowner text, proargtypes oidvector, proallargtypes oid[], proargmodes "char"[], proargnames text[], prosrc text) → text | Reconstruct a routine definition from its catalog fields. | SQL |
get_seq_in_index
| Signature | Purpose | Source definition |
|---|---|---|
mysql.get_seq_in_index(text, int2vector) → smallint | Find a column’s ordinal position in an index. | SQL |
index_key_name
| Signature | Purpose | Source definition |
|---|---|---|
mysql.index_key_name(oid) → text | Expose the MySQL index name or its key parts for SHOW INDEX. | SQL · C |
index_key_parts
| Signature | Purpose | Source definition |
|---|---|---|
mysql.index_key_parts(oid, OUT seq integer, OUT column_name text, OUT sub_part integer) → SETOF record | Expose the MySQL index name or its key parts for SHOW INDEX. | SQL · C |
show_create_function
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_function(text, text) → SETOF record | Construct the definition displayed by SHOW CREATE. | SQL |
show_create_procedure
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_procedure(text, text) → SETOF record | Construct the definition displayed by SHOW CREATE. | SQL |
show_create_table
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_table(text, text) → text | Construct the definition displayed by SHOW CREATE. | SQL |
show_create_table_impl
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_table_impl(oid, oid, text, text) → text | Construct the definition displayed by SHOW CREATE. | SQL |
show_create_trigger
show_create_view
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_view(text, text) → text | Construct the definition displayed by SHOW CREATE. | SQL |
show_create_view_impl
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_create_view_impl(text, text) → text | Construct the definition displayed by SHOW CREATE. | SQL · C |
show_diagnostics
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_diagnostics(boolean) → TABLE("Level" text, "Code" integer, "Message" text) | Return the session diagnostics used by SHOW WARNINGS or SHOW ERRORS. | SQL · C |
show_table_columns
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_table_columns(text, text) → SETOF record | Build the rows for SHOW COLUMNS. | SQL |
show_table_full_columns
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_table_full_columns(text, text) → SETOF record | Build the rows for SHOW COLUMNS. | SQL |
show_table_indexs
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_table_indexs(text, text) → SETOF record | Build the rows for SHOW INDEX. | SQL |
show_table_indexs_for_8
| Signature | Purpose | Source definition |
|---|---|---|
mysql.show_table_indexs_for_8(text, text) → SETOF record | Build the rows for SHOW INDEX. | SQL |
5.2.2.6 - Aggregates
SQL aggregates, their input types and the result produced for a group.
| Signature | Purpose | Source definition |
|---|---|---|
mysql.avg(text) → numeric | Average numeric values read from text. | SQL |
mysql.bit_and(bit varying) → bigint | Combine inputs with bitwise AND. | SQL |
mysql.bit_or(bit varying) → bigint | Combine inputs with bitwise OR. | SQL |
mysql.bit_xor(bit varying) → bigint | Combine inputs with bitwise XOR. | SQL |
mysql.dummy_min_for_bytea(bytea) → bytea | Internal aggregate that retains the input passed to its transition function. | SQL |
mysql.sum(boolean) → bigint | Sum the converted inputs. | SQL |
mysql.sum(text) → numeric | Sum the converted inputs. | SQL |
5.2.2.7 - Operators
Match the symbol and both operand types. NONE in the left slot denotes a unary prefix operator.
The spelling is the PostgreSQL catalog symbol. For example, MySQL LIKE resolves to a pattern operator such as ~~.
Arithmetic
Bitwise and logical
Comparison
Pattern matching and JSON
5.2.2.8 - Metadata views
Query the MySQL name through the dialect or the PostgreSQL name from psql. SHOW helpers and the pending foreign key view are identified by their purpose.
mys_informa_schema
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
mys_informa_schema.columns | information_schema.columns | Column order, data types, defaults, keys and generated expressions. | SQL |
mys_informa_schema.empty_global_variables | information_schema.empty_global_variables | Global system variable names and values for SHOW GLOBAL VARIABLES. | SQL |
mys_informa_schema.empty_session_variables | information_schema.empty_session_variables | Session system variable names and values for SHOW VARIABLES. | SQL |
mys_informa_schema.functions | information_schema.functions | Routine names and attributes for SHOW FUNCTION or PROCEDURE STATUS. | SQL |
mys_informa_schema.indexs | information_schema.indexs | Index columns and constraint keys in the shape expected by SHOW. | SQL |
mys_informa_schema.key_column_usage | information_schema.key_column_usage | Columns participating in keys, including referenced foreign-key columns. | SQL |
mys_informa_schema.parameters | information_schema.parameters | Positional and named routine parameters with their SQL types. | SQL |
mys_informa_schema.partitions | information_schema.partitions | Partition names, partitioning methods and catalog estimates. | SQL |
mys_informa_schema.procedures | information_schema.procedures | Routine names and attributes for SHOW FUNCTION or PROCEDURE STATUS. | SQL |
mys_informa_schema.referential_constraints | information_schema.referential_constraints | Foreign keys, referenced tables and referential actions. | SQL |
mys_informa_schema.routines | information_schema.routines | Procedure and function metadata derived from pg_proc. | SQL |
mys_informa_schema.schemata | information_schema.schemata | Database names derived from PostgreSQL namespaces. | SQL |
mys_informa_schema.statistics | information_schema.statistics | One row per index key part, including its ordinal and prefix length. | SQL |
mys_informa_schema.table_constraints | information_schema.table_constraints | Constraint names and kinds for each table. | SQL |
mys_informa_schema.tables | information_schema.tables | Table and view names and their MySQL table types. | SQL |
mys_informa_schema.triggers | information_schema.triggers | Trigger names, event timing and action metadata. | SQL |
mys_informa_schema.views | information_schema.views | View names and MySQL-compatible view attributes. | SQL |
mysql
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
mysql.dual | mysql.dual | Single dummy row for expressions queried FROM DUAL. | SQL |
mysql.pending_foreign_keys | mysql.pending_foreign_keys | Deferred foreign-key definitions awaiting their referenced tables. | SQL |
mysql.proc | mysql.proc | Procedure and function metadata derived from pg_proc. | SQL |
5.2.2.9 - Metadata tables
These physical tables provide compatibility metadata. Seed counts describe a fresh install. Performance Schema tables start empty.
Column names below are examples of the fields available. Seed links open the statements for that table.
mys_informa_schema
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
mys_informa_schema.administrable_role_authorizations | information_schema.administrable_role_authorizations | Role grants and their enabled or grantable status. Empty on installation. Fields include user, host, grantee. | SQL |
mys_informa_schema.applicable_roles | information_schema.applicable_roles | Role grants and their enabled or grantable status. Empty on installation. Fields include user, host, grantee. | SQL |
mys_informa_schema.base_variables | information_schema.base_variables | Definitions, scope and default values for MySQL system variables. 198 seed rows. Fields include variable_name, def_value, conf_value. | SQL · Seeds |
mys_informa_schema.character_sets | information_schema.character_sets | Character set names, descriptions and default collations. 41 seed rows. Fields include character_set_name, default_collate_name, description. | SQL · Seeds |
mys_informa_schema.charsets | information_schema.charsets | Character set names, descriptions and default collations. 1 seed rows. Fields include charset, description, default collation. | SQL · Seeds |
mys_informa_schema.check_constraints | information_schema.check_constraints | Check constraint names and predicates. Empty on installation. Fields include constraint_catalog, constraint_schema, constraint_name. | SQL |
mys_informa_schema.collation_character_set_applicability | information_schema.collation_character_set_applicability | Character set associated with each collation. 286 seed rows. Fields include collation_name, character_set_name. | SQL · Seeds |
mys_informa_schema.collations | information_schema.collations | Collation names, identifiers and character sets. 286 seed rows. Fields include collation_name, character_set_name, id. | SQL · Seeds |
mys_informa_schema.column_privileges | information_schema.column_privileges | Compatibility fields for column privileges. Empty on installation. Fields include grantee, table_catalog, table_schema. | SQL |
mys_informa_schema.column_statistics | information_schema.column_statistics | Compatibility fields for column statistics. Empty on installation. Fields include schema_name, table_name, column_name. | SQL |
mys_informa_schema.columns_extensions | information_schema.columns_extensions | Extended metadata fields for the named catalog objects. 3,576 seed rows. Fields include table_catalog, table_schema, table_name. | SQL · Seeds |
mys_informa_schema.enabled_roles | information_schema.enabled_roles | Role grants and their enabled or grantable status. Empty on installation. Fields include role_name, role_host, is_default. | SQL |
mys_informa_schema.engines | information_schema.engines | Storage engine names and reported compatibility capabilities. 9 seed rows. Fields include engine, support, comment. | SQL · Seeds |
mys_informa_schema.events | information_schema.events | Compatibility fields for events. Empty on installation. Fields include event_catalog, event_schema, event_name. | SQL |
mys_informa_schema.files | information_schema.files | Compatibility fields for files. Empty on installation. Fields include file_id, file_name, file_type. | SQL |
mys_informa_schema.innodb_buffer_page | information_schema.innodb_buffer_page | InnoDB metadata for buffer page. Empty on installation. Fields include pool_id, block_id, space. | SQL |
mys_informa_schema.innodb_buffer_page_lru | information_schema.innodb_buffer_page_lru | InnoDB metadata for buffer page lru. Empty on installation. Fields include pool_id, lru_position, space. | SQL |
mys_informa_schema.innodb_buffer_pool_stats | information_schema.innodb_buffer_pool_stats | InnoDB metadata for buffer pool stats. Empty on installation. Fields include pool_id, pool_size, free_buffers. | SQL |
mys_informa_schema.innodb_cached_indexes | information_schema.innodb_cached_indexes | InnoDB metadata for cached indexes. Empty on installation. Fields include space_id, index_id, n_cached_pages. | SQL |
mys_informa_schema.innodb_cmp | information_schema.innodb_cmp | InnoDB metadata for cmp. Empty on installation. Fields include page_size, compress_ops, compress_ops_ok. | SQL |
mys_informa_schema.innodb_cmp_per_index | information_schema.innodb_cmp_per_index | InnoDB metadata for cmp per index. Empty on installation. Fields include database_name, table_name, index_name. | SQL |
mys_informa_schema.innodb_cmp_per_index_reset | information_schema.innodb_cmp_per_index_reset | InnoDB metadata for cmp per index reset. Empty on installation. Fields include database_name, table_name, index_name. | SQL |
mys_informa_schema.innodb_cmp_reset | information_schema.innodb_cmp_reset | InnoDB metadata for cmp reset. Empty on installation. Fields include page_size, compress_ops, compress_ops_ok. | SQL |
mys_informa_schema.innodb_cmpmem | information_schema.innodb_cmpmem | InnoDB metadata for cmpmem. Empty on installation. Fields include page_size, buffer_pool_instance, pages_used. | SQL |
mys_informa_schema.innodb_cmpmem_reset | information_schema.innodb_cmpmem_reset | InnoDB metadata for cmpmem reset. Empty on installation. Fields include page_size, buffer_pool_instance, pages_used. | SQL |
mys_informa_schema.innodb_columns | information_schema.innodb_columns | InnoDB metadata for columns. Empty on installation. Fields include table_id, name, pos. | SQL |
mys_informa_schema.innodb_datafiles | information_schema.innodb_datafiles | InnoDB metadata for datafiles. Empty on installation. Fields include space, path. | SQL |
mys_informa_schema.innodb_fields | information_schema.innodb_fields | InnoDB metadata for fields. Empty on installation. Fields include index_id, name, pos. | SQL |
mys_informa_schema.innodb_foreign | information_schema.innodb_foreign | InnoDB metadata for foreign. Empty on installation. Fields include id, for_name, ref_name. | SQL |
mys_informa_schema.innodb_foreign_cols | information_schema.innodb_foreign_cols | InnoDB metadata for foreign cols. Empty on installation. Fields include id, for_col_name, ref_col_name. | SQL |
mys_informa_schema.innodb_ft_being_deleted | information_schema.innodb_ft_being_deleted | InnoDB metadata for ft being deleted. Empty on installation. Fields include doc_id. | SQL |
mys_informa_schema.innodb_ft_config | information_schema.innodb_ft_config | InnoDB metadata for ft config. Empty on installation. Fields include key_, value_. | SQL |
mys_informa_schema.innodb_ft_default_stopword | information_schema.innodb_ft_default_stopword | InnoDB metadata for ft default stopword. Empty on installation. Fields include value. | SQL |
mys_informa_schema.innodb_ft_deleted | information_schema.innodb_ft_deleted | InnoDB metadata for ft deleted. Empty on installation. Fields include doc_id. | SQL |
mys_informa_schema.innodb_ft_index_cache | information_schema.innodb_ft_index_cache | InnoDB metadata for ft index cache. Empty on installation. Fields include word, first_doc_id, last_doc_id. | SQL |
mys_informa_schema.innodb_ft_index_table | information_schema.innodb_ft_index_table | InnoDB metadata for ft index table. Empty on installation. Fields include word, first_doc_id, last_doc_id. | SQL |
mys_informa_schema.innodb_indexes | information_schema.innodb_indexes | InnoDB metadata for indexes. Empty on installation. Fields include index_id, name, table_id. | SQL |
mys_informa_schema.innodb_metrics | information_schema.innodb_metrics | InnoDB metadata for metrics. Empty on installation. Fields include name, subsystem, count. | SQL |
mys_informa_schema.innodb_session_temp_tablespaces | information_schema.innodb_session_temp_tablespaces | InnoDB metadata for session temp tablespaces. Empty on installation. Fields include id, space, path. | SQL |
mys_informa_schema.innodb_tables | information_schema.innodb_tables | InnoDB metadata for tables. Empty on installation. Fields include table_id, name, flag. | SQL |
mys_informa_schema.innodb_tablespaces | information_schema.innodb_tablespaces | InnoDB metadata for tablespaces. Empty on installation. Fields include space, name, flag. | SQL |
mys_informa_schema.innodb_tablespaces_brief | information_schema.innodb_tablespaces_brief | InnoDB metadata for tablespaces brief. Empty on installation. Fields include space, name, path. | SQL |
mys_informa_schema.innodb_tablestats | information_schema.innodb_tablestats | InnoDB metadata for tablestats. Empty on installation. Fields include table_id, name, stats_initialized. | SQL |
mys_informa_schema.innodb_temp_table_info | information_schema.innodb_temp_table_info | InnoDB metadata for temp table info. Empty on installation. Fields include table_id, name, n_cols. | SQL |
mys_informa_schema.innodb_virtual | information_schema.innodb_virtual | InnoDB metadata for virtual. Empty on installation. Fields include table_id, pos, base_pos. | SQL |
mys_informa_schema.keywords | information_schema.keywords | MySQL keywords and reserved-word flags. 747 seed rows. Fields include word, reserved. | SQL · Seeds |
mys_informa_schema.optimizer_trace | information_schema.optimizer_trace | Compatibility fields for optimizer trace. Empty on installation. Fields include query, trace, missing_bytes_beyond_max_mem_size. | SQL |
mys_informa_schema.plugins | information_schema.plugins | Compatibility fields for plugins. Empty on installation. Fields include name, status, type. | SQL |
mys_informa_schema.processlist | information_schema.processlist | Session and statement fields expected by process-list queries. Empty on installation. Fields include id, user, host. | SQL |
mys_informa_schema.profiling | information_schema.profiling | Compatibility fields for profiling. Empty on installation. Fields include query_id, seq, state. | SQL |
mys_informa_schema.resource_groups | information_schema.resource_groups | Compatibility fields for resource groups. Empty on installation. Fields include resource_group_name, resource_group_type, resource_group_enabled. | SQL |
mys_informa_schema.role_column_grants | information_schema.role_column_grants | Compatibility fields for role column grants. Empty on installation. Fields include grantor, grantor_host, grantee. | SQL |
mys_informa_schema.role_routine_grants | information_schema.role_routine_grants | Compatibility fields for role routine grants. Empty on installation. Fields include grantor, grantor_host, grantee. | SQL |
mys_informa_schema.role_table_grants | information_schema.role_table_grants | Compatibility fields for role table grants. Empty on installation. Fields include grantor, grantor_host, grantee. | SQL |
mys_informa_schema.schema_privileges | information_schema.schema_privileges | Compatibility fields for schema privileges. Empty on installation. Fields include grantee, table_catalog, table_schema. | SQL |
mys_informa_schema.st_geometry_columns | information_schema.st_geometry_columns | Compatibility fields for st geometry columns. Empty on installation. Fields include table_catalog, table_schema, table_name. | SQL |
mys_informa_schema.st_spatial_reference_systems | information_schema.st_spatial_reference_systems | Spatial reference system definitions. The supplied SRS seed statements are commented out. | SQL |
mys_informa_schema.st_units_of_measure | information_schema.st_units_of_measure | Compatibility fields for st units of measure. Empty on installation. Fields include unit_name, unit_type, conversion_factor. | SQL |
mys_informa_schema.table_constraints_extensions | information_schema.table_constraints_extensions | Extended metadata fields for the named catalog objects. Empty on installation. Fields include constraint_catalog, constraint_schema, constraint_name. | SQL |
mys_informa_schema.table_privileges | information_schema.table_privileges | Compatibility fields for table privileges. Empty on installation. Fields include grantee, table_catalog, table_schema. | SQL |
mys_informa_schema.tables_extensions | information_schema.tables_extensions | Extended metadata fields for the named catalog objects. Empty on installation. Fields include table_catalog, table_schema, table_name. | SQL |
mys_informa_schema.tablespaces | information_schema.tablespaces | Compatibility fields for tablespaces. Empty on installation. Fields include tablespace_name, engine, tablespace_type. | SQL |
mys_informa_schema.tablespaces_extensions | information_schema.tablespaces_extensions | Extended metadata fields for the named catalog objects. Empty on installation. Fields include tablespace_name, engine_attribute. | SQL |
mys_informa_schema.user_attributes | information_schema.user_attributes | Compatibility fields for user attributes. Empty on installation. Fields include user, host, attribute. | SQL |
mys_informa_schema.user_privileges | information_schema.user_privileges | Compatibility fields for user privileges. Empty on installation. Fields include grantee, table_catalog, privilege_type. | SQL |
mys_informa_schema.view_routine_usage | information_schema.view_routine_usage | Compatibility fields for view routine usage. Empty on installation. Fields include table_catalog, table_schema, table_name. | SQL |
mys_informa_schema.view_table_usage | information_schema.view_table_usage | Compatibility fields for view table usage. Empty on installation. Fields include view_catalog, view_schema, view_name. | SQL |
mys_sys
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
mys_sys.innodb_lock_waits | sys.innodb_lock_waits | Lock request and blocker details. Empty on installation. Fields include wait_started, wait_age, wait_age_secs. | SQL |
mysql
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
mysql."user" | mysql.user | Account, authentication and privilege fields for mysql.user queries. Empty on installation. Fields include host, user, select_priv. | SQL |
performance_schema
| PostgreSQL object | MySQL name | Purpose | Source definition |
|---|---|---|---|
performance_schema.accounts | performance_schema.accounts | Connection counters grouped by account, host or user. Empty on installation. Fields include user, host, current_connections. | SQL |
performance_schema.binary_log_transaction_compression_stats | performance_schema.binary_log_transaction_compression_stats | Compatibility fields for binary log transaction compression stats. Empty on installation. Fields include log_type, compression_type, transaction_counter. | SQL |
performance_schema.cond_instances | performance_schema.cond_instances | Compatibility fields for cond instances. Empty on installation. Fields include name, object_instance_begin. | SQL |
performance_schema.data_lock_waits | performance_schema.data_lock_waits | Lock request and blocker details. Empty on installation. Fields include engine, requesting_engine_lock_id, requesting_engine_transaction_id. | SQL |
performance_schema.data_locks | performance_schema.data_locks | Lock identities, owners and lock modes. Empty on installation. Fields include engine, engine_lock_id, engine_transaction_id. | SQL |
performance_schema.error_log | performance_schema.error_log | Compatibility fields for error log. Empty on installation. Fields include logged, thread_id, prio. | SQL |
performance_schema.events_errors_summary_by_account_by_error | performance_schema.events_errors_summary_by_account_by_error | Events errors summary by account by error. Empty on installation. Fields include user, host, error_number. | SQL |
performance_schema.events_errors_summary_by_host_by_error | performance_schema.events_errors_summary_by_host_by_error | Events errors summary by host by error. Empty on installation. Fields include host, error_number, error_name. | SQL |
performance_schema.events_errors_summary_by_thread_by_error | performance_schema.events_errors_summary_by_thread_by_error | Events errors summary by thread by error. Empty on installation. Fields include thread_id, error_number, error_name. | SQL |
performance_schema.events_errors_summary_by_user_by_error | performance_schema.events_errors_summary_by_user_by_error | Events errors summary by user by error. Empty on installation. Fields include user, error_number, error_name. | SQL |
performance_schema.events_errors_summary_global_by_error | performance_schema.events_errors_summary_global_by_error | Events errors summary global by error. Empty on installation. Fields include error_number, error_name, sql_state. | SQL |
performance_schema.events_stages_current | performance_schema.events_stages_current | Events stages current. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_stages_history | performance_schema.events_stages_history | Events stages history. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_stages_history_long | performance_schema.events_stages_history_long | Events stages history long. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_stages_summary_by_account_by_event_name | performance_schema.events_stages_summary_by_account_by_event_name | Events stages summary by account by event name. Empty on installation. Fields include user, host, event_name. | SQL |
performance_schema.events_stages_summary_by_host_by_event_name | performance_schema.events_stages_summary_by_host_by_event_name | Events stages summary by host by event name. Empty on installation. Fields include host, event_name, count_star. | SQL |
performance_schema.events_stages_summary_by_thread_by_event_name | performance_schema.events_stages_summary_by_thread_by_event_name | Events stages summary by thread by event name. Empty on installation. Fields include thread_id, event_name, count_star. | SQL |
performance_schema.events_stages_summary_by_user_by_event_name | performance_schema.events_stages_summary_by_user_by_event_name | Events stages summary by user by event name. Empty on installation. Fields include user, event_name, count_star. | SQL |
performance_schema.events_stages_summary_global_by_event_name | performance_schema.events_stages_summary_global_by_event_name | Events stages summary global by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.events_statements_current | performance_schema.events_statements_current | Events statements current. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_statements_histogram_by_digest | performance_schema.events_statements_histogram_by_digest | Events statements histogram by digest. Empty on installation. Fields include schema_name, digest, bucket_number. | SQL |
performance_schema.events_statements_histogram_global | performance_schema.events_statements_histogram_global | Events statements histogram global. Empty on installation. Fields include bucket_number, bucket_timer_low, bucket_timer_high. | SQL |
performance_schema.events_statements_history | performance_schema.events_statements_history | Events statements history. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_statements_history_long | performance_schema.events_statements_history_long | Events statements history long. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_statements_summary_by_account_by_event_name | performance_schema.events_statements_summary_by_account_by_event_name | Events statements summary by account by event name. Empty on installation. Fields include user, host, event_name. | SQL |
performance_schema.events_statements_summary_by_digest | performance_schema.events_statements_summary_by_digest | Events statements summary by digest. Empty on installation. Fields include schema_name, digest, digest_text. | SQL |
performance_schema.events_statements_summary_by_host_by_event_name | performance_schema.events_statements_summary_by_host_by_event_name | Events statements summary by host by event name. Empty on installation. Fields include host, event_name, count_star. | SQL |
performance_schema.events_statements_summary_by_program | performance_schema.events_statements_summary_by_program | Events statements summary by program. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.events_statements_summary_by_thread_by_event_name | performance_schema.events_statements_summary_by_thread_by_event_name | Events statements summary by thread by event name. Empty on installation. Fields include thread_id, event_name, count_star. | SQL |
performance_schema.events_statements_summary_by_user_by_event_name | performance_schema.events_statements_summary_by_user_by_event_name | Events statements summary by user by event name. Empty on installation. Fields include user, event_name, count_star. | SQL |
performance_schema.events_statements_summary_global_by_event_name | performance_schema.events_statements_summary_global_by_event_name | Events statements summary global by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.events_transactions_current | performance_schema.events_transactions_current | Events transactions current. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_transactions_history | performance_schema.events_transactions_history | Events transactions history. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_transactions_history_long | performance_schema.events_transactions_history_long | Events transactions history long. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_transactions_summary_by_account_by_event_name | performance_schema.events_transactions_summary_by_account_by_event_name | Events transactions summary by account by event name. Empty on installation. Fields include user, host, event_name. | SQL |
performance_schema.events_transactions_summary_by_host_by_event_name | performance_schema.events_transactions_summary_by_host_by_event_name | Events transactions summary by host by event name. Empty on installation. Fields include host, event_name, count_star. | SQL |
performance_schema.events_transactions_summary_by_thread_by_event_name | performance_schema.events_transactions_summary_by_thread_by_event_name | Events transactions summary by thread by event name. Empty on installation. Fields include thread_id, event_name, count_star. | SQL |
performance_schema.events_transactions_summary_by_user_by_event_name | performance_schema.events_transactions_summary_by_user_by_event_name | Events transactions summary by user by event name. Empty on installation. Fields include user, event_name, count_star. | SQL |
performance_schema.events_transactions_summary_global_by_event_name | performance_schema.events_transactions_summary_global_by_event_name | Events transactions summary global by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.events_waits_current | performance_schema.events_waits_current | Events waits current. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_waits_history | performance_schema.events_waits_history | Events waits history. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_waits_history_long | performance_schema.events_waits_history_long | Events waits history long. Empty on installation. Fields include thread_id, event_id, end_event_id. | SQL |
performance_schema.events_waits_summary_by_account_by_event_name | performance_schema.events_waits_summary_by_account_by_event_name | Events waits summary by account by event name. Empty on installation. Fields include user, host, event_name. | SQL |
performance_schema.events_waits_summary_by_host_by_event_name | performance_schema.events_waits_summary_by_host_by_event_name | Events waits summary by host by event name. Empty on installation. Fields include host, event_name, count_star. | SQL |
performance_schema.events_waits_summary_by_instance | performance_schema.events_waits_summary_by_instance | Events waits summary by instance. Empty on installation. Fields include event_name, object_instance_begin, count_star. | SQL |
performance_schema.events_waits_summary_by_thread_by_event_name | performance_schema.events_waits_summary_by_thread_by_event_name | Events waits summary by thread by event name. Empty on installation. Fields include thread_id, event_name, count_star. | SQL |
performance_schema.events_waits_summary_by_user_by_event_name | performance_schema.events_waits_summary_by_user_by_event_name | Events waits summary by user by event name. Empty on installation. Fields include user, event_name, count_star. | SQL |
performance_schema.events_waits_summary_global_by_event_name | performance_schema.events_waits_summary_global_by_event_name | Events waits summary global by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.file_instances | performance_schema.file_instances | Compatibility fields for file instances. Empty on installation. Fields include file_name, event_name, open_count. | SQL |
performance_schema.file_summary_by_event_name | performance_schema.file_summary_by_event_name | Compatibility fields for file summary by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.file_summary_by_instance | performance_schema.file_summary_by_instance | Compatibility fields for file summary by instance. Empty on installation. Fields include file_name, event_name, object_instance_begin. | SQL |
performance_schema.global_status | performance_schema.global_status | Compatibility fields for global status. Empty on installation. Fields include variable_name, variable_value. | SQL |
performance_schema.global_variables | performance_schema.global_variables | Compatibility fields for global variables. Empty on installation. Fields include variable_name, variable_value. | SQL |
performance_schema.host_cache | performance_schema.host_cache | Compatibility fields for host cache. Empty on installation. Fields include ip, host, host_validated. | SQL |
performance_schema.hosts | performance_schema.hosts | Connection counters grouped by account, host or user. Empty on installation. Fields include host, current_connections, total_connections. | SQL |
performance_schema.innodb_redo_log_files | performance_schema.innodb_redo_log_files | InnoDB metadata for redo log files. Empty on installation. Fields include file_id, file_name, start_lsn. | SQL |
performance_schema.keyring_component_status | performance_schema.keyring_component_status | Compatibility fields for keyring component status. Empty on installation. Fields include status_key, status_value. | SQL |
performance_schema.keyring_keys | performance_schema.keyring_keys | Compatibility fields for keyring keys. Empty on installation. Fields include key_id, key_owner, backend_key_id. | SQL |
performance_schema.log_status | performance_schema.log_status | Compatibility fields for log status. Empty on installation. Fields include server_uuid, local, replication. | SQL |
performance_schema.memory_summary_by_account_by_event_name | performance_schema.memory_summary_by_account_by_event_name | Compatibility fields for memory summary by account by event name. Empty on installation. Fields include user, host, event_name. | SQL |
performance_schema.memory_summary_by_host_by_event_name | performance_schema.memory_summary_by_host_by_event_name | Compatibility fields for memory summary by host by event name. Empty on installation. Fields include host, event_name, count_alloc. | SQL |
performance_schema.memory_summary_by_thread_by_event_name | performance_schema.memory_summary_by_thread_by_event_name | Compatibility fields for memory summary by thread by event name. Empty on installation. Fields include thread_id, event_name, count_alloc. | SQL |
performance_schema.memory_summary_by_user_by_event_name | performance_schema.memory_summary_by_user_by_event_name | Compatibility fields for memory summary by user by event name. Empty on installation. Fields include user, event_name, count_alloc. | SQL |
performance_schema.memory_summary_global_by_event_name | performance_schema.memory_summary_global_by_event_name | Compatibility fields for memory summary global by event name. Empty on installation. Fields include event_name, count_alloc, count_free. | SQL |
performance_schema.metadata_locks | performance_schema.metadata_locks | Lock identities, owners and lock modes. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.mutex_instances | performance_schema.mutex_instances | Compatibility fields for mutex instances. Empty on installation. Fields include name, object_instance_begin, locked_by_thread_id. | SQL |
performance_schema.objects_summary_global_by_type | performance_schema.objects_summary_global_by_type | Compatibility fields for objects summary global by type. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.performance_timers | performance_schema.performance_timers | Compatibility fields for performance timers. Empty on installation. Fields include timer_name, timer_frequency, timer_resolution. | SQL |
performance_schema.persisted_variables | performance_schema.persisted_variables | Compatibility fields for persisted variables. Empty on installation. Fields include variable_name, variable_value. | SQL |
performance_schema.prepared_statements_instances | performance_schema.prepared_statements_instances | Compatibility fields for prepared statements instances. Empty on installation. Fields include object_instance_begin, statement_id, statement_name. | SQL |
performance_schema.processlist | performance_schema.processlist | Session and statement fields expected by process-list queries. Empty on installation. Fields include id, user, host. | SQL |
performance_schema.replication_applier_configuration | performance_schema.replication_applier_configuration | MySQL replication metadata for applier configuration. Empty on installation. Fields include channel_name, desired_delay, privilege_checks_user. | SQL |
performance_schema.replication_applier_filters | performance_schema.replication_applier_filters | MySQL replication metadata for applier filters. Empty on installation. Fields include channel_name, filter_name, filter_rule. | SQL |
performance_schema.replication_applier_global_filters | performance_schema.replication_applier_global_filters | MySQL replication metadata for applier global filters. Empty on installation. Fields include filter_name, filter_rule, configured_by. | SQL |
performance_schema.replication_applier_status | performance_schema.replication_applier_status | MySQL replication metadata for applier status. Empty on installation. Fields include channel_name, service_state, remaining_delay. | SQL |
performance_schema.replication_applier_status_by_coordinator | performance_schema.replication_applier_status_by_coordinator | MySQL replication metadata for applier status by coordinator. Empty on installation. Fields include channel_name, thread_id, service_state. | SQL |
performance_schema.replication_applier_status_by_worker | performance_schema.replication_applier_status_by_worker | MySQL replication metadata for applier status by worker. Empty on installation. Fields include channel_name, worker_id, thread_id. | SQL |
performance_schema.replication_asynchronous_connection_failover | performance_schema.replication_asynchronous_connection_failover | MySQL replication metadata for asynchronous connection failover. Empty on installation. Fields include channel_name, host, port. | SQL |
performance_schema.replication_asynchronous_connection_failover_managed | performance_schema.replication_asynchronous_connection_failover_managed | MySQL replication metadata for asynchronous connection failover managed. Empty on installation. Fields include channel_name, managed_name, managed_type. | SQL |
performance_schema.replication_connection_configuration | performance_schema.replication_connection_configuration | MySQL replication metadata for connection configuration. Empty on installation. Fields include channel_name, host, port. | SQL |
performance_schema.replication_connection_status | performance_schema.replication_connection_status | MySQL replication metadata for connection status. Empty on installation. Fields include channel_name, group_name, source_uuid. | SQL |
performance_schema.replication_group_member_stats | performance_schema.replication_group_member_stats | MySQL replication metadata for group member stats. Empty on installation. Fields include channel_name, view_id, member_id. | SQL |
performance_schema.replication_group_members | performance_schema.replication_group_members | MySQL replication metadata for group members. Empty on installation. Fields include channel_name, member_id, member_host. | SQL |
performance_schema.rwlock_instances | performance_schema.rwlock_instances | Compatibility fields for rwlock instances. Empty on installation. Fields include name, object_instance_begin, write_locked_by_thread_id. | SQL |
performance_schema.session_account_connect_attrs | performance_schema.session_account_connect_attrs | Compatibility fields for session account connect attrs. Empty on installation. Fields include processlist_id, attr_name, attr_value. | SQL |
performance_schema.session_connect_attrs | performance_schema.session_connect_attrs | Compatibility fields for session connect attrs. Empty on installation. Fields include processlist_id, attr_name, attr_value. | SQL |
performance_schema.session_status | performance_schema.session_status | Compatibility fields for session status. Empty on installation. Fields include variable_name, variable_value. | SQL |
performance_schema.session_variables | performance_schema.session_variables | Compatibility fields for session variables. Empty on installation. Fields include variable_name, variable_value. | SQL |
performance_schema.setup_actors | performance_schema.setup_actors | Compatibility fields for setup actors. Empty on installation. Fields include host, user, role. | SQL |
performance_schema.setup_consumers | performance_schema.setup_consumers | Compatibility fields for setup consumers. Empty on installation. Fields include name, enabled. | SQL |
performance_schema.setup_instruments | performance_schema.setup_instruments | Compatibility fields for setup instruments. Empty on installation. Fields include name, enabled, timed. | SQL |
performance_schema.setup_objects | performance_schema.setup_objects | Compatibility fields for setup objects. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.setup_threads | performance_schema.setup_threads | Compatibility fields for setup threads. Empty on installation. Fields include name, enabled, history. | SQL |
performance_schema.socket_instances | performance_schema.socket_instances | Compatibility fields for socket instances. Empty on installation. Fields include event_name, object_instance_begin, thread_id. | SQL |
performance_schema.socket_summary_by_event_name | performance_schema.socket_summary_by_event_name | Compatibility fields for socket summary by event name. Empty on installation. Fields include event_name, count_star, sum_timer_wait. | SQL |
performance_schema.socket_summary_by_instance | performance_schema.socket_summary_by_instance | Compatibility fields for socket summary by instance. Empty on installation. Fields include event_name, object_instance_begin, count_star. | SQL |
performance_schema.status_by_account | performance_schema.status_by_account | Compatibility fields for status by account. Empty on installation. Fields include user, host, variable_name. | SQL |
performance_schema.status_by_host | performance_schema.status_by_host | Compatibility fields for status by host. Empty on installation. Fields include host, variable_name, variable_value. | SQL |
performance_schema.status_by_thread | performance_schema.status_by_thread | Compatibility fields for status by thread. Empty on installation. Fields include thread_id, variable_name, variable_value. | SQL |
performance_schema.status_by_user | performance_schema.status_by_user | Compatibility fields for status by user. Empty on installation. Fields include user, variable_name, variable_value. | SQL |
performance_schema.table_handles | performance_schema.table_handles | Compatibility fields for table handles. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.table_io_waits_summary_by_index_usage | performance_schema.table_io_waits_summary_by_index_usage | Compatibility fields for table io waits summary by index usage. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.table_io_waits_summary_by_table | performance_schema.table_io_waits_summary_by_table | Compatibility fields for table io waits summary by table. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.table_lock_waits_summary_by_table | performance_schema.table_lock_waits_summary_by_table | Compatibility fields for table lock waits summary by table. Empty on installation. Fields include object_type, object_schema, object_name. | SQL |
performance_schema.threads | performance_schema.threads | Compatibility fields for threads. Empty on installation. Fields include thread_id, name, type. | SQL |
performance_schema.tls_channel_status | performance_schema.tls_channel_status | Compatibility fields for tls channel status. Empty on installation. Fields include channel, property, value. | SQL |
performance_schema.user_defined_functions | performance_schema.user_defined_functions | Compatibility fields for user defined functions. Empty on installation. Fields include udf_name, udf_return_type, udf_type. | SQL |
performance_schema.user_variables_by_thread | performance_schema.user_variables_by_thread | Compatibility fields for user variables by thread. Empty on installation. Fields include thread_id, variable_name, variable_value. | SQL |
performance_schema.users | performance_schema.users | Connection counters grouped by account, host or user. Empty on installation. Fields include user, current_connections, total_connections. | SQL |
performance_schema.variables_by_thread | performance_schema.variables_by_thread | Compatibility fields for variables by thread. Empty on installation. Fields include thread_id, variable_name, variable_value. | SQL |
performance_schema.variables_info | performance_schema.variables_info | Compatibility fields for variables info. Empty on installation. Fields include variable_name, variable_source, variable_path. | SQL |
5.2.2.10 - Index access method, classes and families
Find the access method, the default operator class for a type and its family. Class and family names can coincide.
A class that omits FAMILY creates a family of the same name. The binary_n and varbinary_n B-tree and hash classes instead join the existing pg_catalog.bytea_ops families.
Operator classes
Operator families
Access method
| Signature | Purpose | Source definition |
|---|---|---|
mysql_prefix | Index access method for MySQL prefix keys. | SQL |
5.2.2.11 - Operator family members
Index dependencies by family, access method, strategy or support number, and operand pair. Each row names the registered operator or function.
Strategy operators
Support functions
5.2.2.12 - Table indexes
Physical indexes on the compatibility tables, including the unique indexes that enforce their primary keys.
Primary keys
Secondary indexes
5.2.2.13 - Primary keys and domain checks
Find the database-assigned constraint name, its owning table or domain and the installed expression.
Domain checks
| Signature | Purpose | Source definition |
|---|---|---|
"bigint unsigned_check" on mysql."bigint unsigned" | CHECK ((0 <= VALUE)) | SQL |
"int unsigned_check" on mysql."int unsigned" | CHECK (((0 <= VALUE) AND (VALUE <= '4294967295'::bigint))) | SQL |
"mediumint signed_check" on mysql."mediumint signed" | CHECK ((('-8388608'::integer <= VALUE) AND (VALUE <= 8388607))) | SQL |
"mediumint unsigned_check" on mysql."mediumint unsigned" | CHECK (((0 <= VALUE) AND (VALUE <= 16777215))) | SQL |
"smallint unsigned_check" on mysql."smallint unsigned" | CHECK (((0 <= VALUE) AND (VALUE <= 65535))) | SQL |
"tinyint signed_check" on mysql."tinyint signed" | CHECK ((('-128'::integer <= VALUE) AND (VALUE <= 127))) | SQL |
"tinyint unsigned_check" on mysql."tinyint unsigned" | CHECK (((0 <= VALUE) AND (VALUE <= 255))) | SQL |
"tinyint1 signed_check" on mysql."tinyint1 signed" | CHECK ((('-128'::integer <= VALUE) AND (VALUE <= 127))) | SQL |
"tinyint1 unsigned_check" on mysql."tinyint1 unsigned" | CHECK (((0 <= VALUE) AND (VALUE <= 255))) | SQL |
mediumint_check on mysql.mediumint | CHECK ((('-8388608'::integer <= VALUE) AND (VALUE <= 8388607))) | SQL |
tinyint1_check on mysql.tinyint1 | CHECK ((('-128'::integer <= VALUE) AND (VALUE <= 127))) | SQL |
tinyint_check on mysql.tinyint | CHECK ((('-128'::integer <= VALUE) AND (VALUE <= 127))) | SQL |
year__check on mysql.year_ | CHECK (((1901 <= VALUE) AND (VALUE <= 2155))) | SQL |
Primary keys
5.2.2.14 - NOT NULL in metadata schemas
Column constraints in the compatibility catalogs outside Performance Schema, ordered by the owning table’s initial.
A
| Signature | Purpose | Source definition |
|---|---|---|
administrable_role_authorizations_is_grantable_not_null on mys_informa_schema.administrable_role_authorizations | NOT NULL is_grantable | SQL |
administrable_role_authorizations_is_mandatory_not_null on mys_informa_schema.administrable_role_authorizations | NOT NULL is_mandatory | SQL |
applicable_roles_is_grantable_not_null on mys_informa_schema.applicable_roles | NOT NULL is_grantable | SQL |
applicable_roles_is_mandatory_not_null on mys_informa_schema.applicable_roles | NOT NULL is_mandatory | SQL |
B
| Signature | Purpose | Source definition |
|---|---|---|
base_variables_variable_name_not_null on mys_informa_schema.base_variables | NOT NULL variable_name (implied by the primary key) | SQL |
C
E
| Signature | Purpose | Source definition |
|---|---|---|
enabled_roles_is_mandatory_not_null on mys_informa_schema.enabled_roles | NOT NULL is_mandatory | SQL |
F
| Signature | Purpose | Source definition |
|---|---|---|
files_engine_not_null on mys_informa_schema.files | NOT NULL engine | SQL |
files_table_catalog_not_null on mys_informa_schema.files | NOT NULL table_catalog | SQL |
files_tablespace_name_not_null on mys_informa_schema.files | NOT NULL tablespace_name | SQL |
I
O
| Signature | Purpose | Source definition |
|---|---|---|
optimizer_trace_insufficient_privileges_not_null on mys_informa_schema.optimizer_trace | NOT NULL insufficient_privileges | SQL |
optimizer_trace_missing_bytes_beyond_max_mem_size_not_null on mys_informa_schema.optimizer_trace | NOT NULL missing_bytes_beyond_max_mem_size | SQL |
optimizer_trace_query_not_null on mys_informa_schema.optimizer_trace | NOT NULL query | SQL |
optimizer_trace_trace_not_null on mys_informa_schema.optimizer_trace | NOT NULL trace | SQL |
P
| Signature | Purpose | Source definition |
|---|---|---|
processlist_command_not_null on mys_informa_schema.processlist | NOT NULL command | SQL |
processlist_host_not_null on mys_informa_schema.processlist | NOT NULL host | SQL |
processlist_id_not_null on mys_informa_schema.processlist | NOT NULL id | SQL |
processlist_time_not_null on mys_informa_schema.processlist | NOT NULL "time" | SQL |
processlist_user_not_null on mys_informa_schema.processlist | NOT NULL "user" | SQL |
R
S
| Signature | Purpose | Source definition |
|---|---|---|
schema_privileges_grantee_not_null on mys_informa_schema.schema_privileges | NOT NULL grantee | SQL |
schema_privileges_is_grantable_not_null on mys_informa_schema.schema_privileges | NOT NULL is_grantable | SQL |
schema_privileges_privilege_type_not_null on mys_informa_schema.schema_privileges | NOT NULL privilege_type | SQL |
schema_privileges_table_catalog_not_null on mys_informa_schema.schema_privileges | NOT NULL table_catalog | SQL |
schema_privileges_table_schema_not_null on mys_informa_schema.schema_privileges | NOT NULL table_schema | SQL |
st_spatial_reference_systems_definition_not_null on mys_informa_schema.st_spatial_reference_systems | NOT NULL definition | SQL |
st_spatial_reference_systems_srs_id_not_null on mys_informa_schema.st_spatial_reference_systems | NOT NULL srs_id | SQL |
st_spatial_reference_systems_srs_name_not_null on mys_informa_schema.st_spatial_reference_systems | NOT NULL srs_name | SQL |
T
U
V
| Signature | Purpose | Source definition |
|---|---|---|
view_routine_usage_specific_name_not_null on mys_informa_schema.view_routine_usage | NOT NULL specific_name | SQL |
5.2.2.15 - NOT NULL in performance_schema.events_*
Catalog constraint names and column definitions for Performance Schema event tables.
E
5.2.2.16 - NOT NULL in other performance_schema tables
Catalog constraint names and column definitions for the remaining Performance Schema tables.
A
| Signature | Purpose | Source definition |
|---|---|---|
accounts_current_connections_not_null on performance_schema.accounts | NOT NULL current_connections | SQL |
accounts_total_connections_not_null on performance_schema.accounts | NOT NULL total_connections | SQL |
B
C
| Signature | Purpose | Source definition |
|---|---|---|
cond_instances_name_not_null on performance_schema.cond_instances | NOT NULL name | SQL |
cond_instances_object_instance_begin_not_null on performance_schema.cond_instances | NOT NULL object_instance_begin | SQL |
D
E
| Signature | Purpose | Source definition |
|---|---|---|
error_log_data_not_null on performance_schema.error_log | NOT NULL data | SQL |
error_log_logged_not_null on performance_schema.error_log | NOT NULL logged | SQL |
error_log_prio_not_null on performance_schema.error_log | NOT NULL prio | SQL |
F
G
| Signature | Purpose | Source definition |
|---|---|---|
global_status_variable_name_not_null on performance_schema.global_status | NOT NULL variable_name | SQL |
global_variables_variable_name_not_null on performance_schema.global_variables | NOT NULL variable_name | SQL |
H
I
| Signature | Purpose | Source definition |
|---|---|---|
innodb_redo_log_files_consumer_level_not_null on performance_schema.innodb_redo_log_files | NOT NULL consumer_level | SQL |
innodb_redo_log_files_end_lsn_not_null on performance_schema.innodb_redo_log_files | NOT NULL end_lsn | SQL |
innodb_redo_log_files_file_id_not_null on performance_schema.innodb_redo_log_files | NOT NULL file_id | SQL |
innodb_redo_log_files_file_name_not_null on performance_schema.innodb_redo_log_files | NOT NULL file_name | SQL |
innodb_redo_log_files_is_full_not_null on performance_schema.innodb_redo_log_files | NOT NULL is_full | SQL |
innodb_redo_log_files_size_in_bytes_not_null on performance_schema.innodb_redo_log_files | NOT NULL size_in_bytes | SQL |
innodb_redo_log_files_start_lsn_not_null on performance_schema.innodb_redo_log_files | NOT NULL start_lsn | SQL |
K
| Signature | Purpose | Source definition |
|---|---|---|
keyring_component_status_status_key_not_null on performance_schema.keyring_component_status | NOT NULL status_key | SQL |
keyring_component_status_status_value_not_null on performance_schema.keyring_component_status | NOT NULL status_value | SQL |
keyring_keys_key_id_not_null on performance_schema.keyring_keys | NOT NULL key_id | SQL |
L
| Signature | Purpose | Source definition |
|---|---|---|
log_status_local_not_null on performance_schema.log_status | NOT NULL local | SQL |
log_status_replication_not_null on performance_schema.log_status | NOT NULL replication | SQL |
log_status_server_uuid_not_null on performance_schema.log_status | NOT NULL server_uuid | SQL |
log_status_storage_engines_not_null on performance_schema.log_status | NOT NULL storage_engines | SQL |
M
O
| Signature | Purpose | Source definition |
|---|---|---|
objects_summary_global_by_type_avg_timer_wait_not_null on performance_schema.objects_summary_global_by_type | NOT NULL avg_timer_wait | SQL |
objects_summary_global_by_type_count_star_not_null on performance_schema.objects_summary_global_by_type | NOT NULL count_star | SQL |
objects_summary_global_by_type_max_timer_wait_not_null on performance_schema.objects_summary_global_by_type | NOT NULL max_timer_wait | SQL |
objects_summary_global_by_type_min_timer_wait_not_null on performance_schema.objects_summary_global_by_type | NOT NULL min_timer_wait | SQL |
objects_summary_global_by_type_sum_timer_wait_not_null on performance_schema.objects_summary_global_by_type | NOT NULL sum_timer_wait | SQL |
P
R
S
T
U
| Signature | Purpose | Source definition |
|---|---|---|
user_defined_functions_udf_name_not_null on performance_schema.user_defined_functions | NOT NULL udf_name | SQL |
user_defined_functions_udf_return_type_not_null on performance_schema.user_defined_functions | NOT NULL udf_return_type | SQL |
user_defined_functions_udf_type_not_null on performance_schema.user_defined_functions | NOT NULL udf_type | SQL |
users_current_connections_not_null on performance_schema.users | NOT NULL current_connections | SQL |
users_total_connections_not_null on performance_schema.users | NOT NULL total_connections | SQL |
V
| Signature | Purpose | Source definition |
|---|---|---|
variables_by_thread_thread_id_not_null on performance_schema.variables_by_thread | NOT NULL thread_id | SQL |
variables_by_thread_variable_name_not_null on performance_schema.variables_by_thread | NOT NULL variable_name | SQL |
variables_info_variable_name_not_null on performance_schema.variables_info | NOT NULL variable_name | SQL |
5.3 - SQL and type compatibility
The examples on this page use an ordinary MySQL connection to a scratch schema. The native PostgreSQL connection sees the same stored rows. Parser rules, transaction boundaries and driver result types depend on the entry point.
SQL at the two endpoints
| Task | MySQL behavior in 19.0.1 | Migration consequence |
|---|---|---|
| Create and alter tables | Backticks, inline KEY, AUTO_INCREMENT, MODIFY and CHANGE are handled by the dialect. Auto-increment uses a PostgreSQL identity sequence. | Compare the next generated value after loading explicit keys. A change to a default or generation expression deserves a write test. |
| Query and join | Backticks, LIMIT offset,count, single-target UPDATE … JOIN and selected DELETE FROM target USING … forms are implemented. | Rewrite multi-target writes and DELETE target FROM … JOIN as explicit single-target operations. Compare affected rows inside the intended transaction. |
| Update a duplicate key | ON DUPLICATE KEY UPDATE checks unique keys. REPLACE deletes conflicting rows and inserts a new row using column defaults. FK actions and triggers can run. | Use an explicit update when omitted columns or referencing rows must survive. Plain UPDATE counts matched rows, including unchanged rows. |
| Use a boolean or integer predicate | SELECT 1 WHERE 1 returns 1; inserting 1=1 into an INT column stores 1. Native psql rejects the integer predicate (SQLSTATE 42804). | Write WHERE flag <> 0 in portable SQL. Native integer/boolean conversions require explicit casts. Some extension-provided casts and types are visible database-wide. |
| Inspect or replay definitions | SHOW CREATE TABLE, SHOW COLUMNS and SHOW INDEX expose MySQL-facing definitions. information_schema, SHOW STATUS and system variables cover a subset. | Replay the DDL in a scratch schema. Compare constraints and physical storage via native catalogs. |
This example returned affected-row counts 1, 1, 2, 2 for the four writes. The final row was (1,9): the omitted column took its default on replacement.
Types, bytes and collation
| Source value or DDL | Observed result in the example database | Representation or check |
|---|---|---|
CREATE TABLE ids(k BIGINT UNSIGNED), then INSERT INTO ids VALUES(9223372036854775808) | Error 1264, row count remains zero. The target domain ranges from 0 through 9223372036854775807. | For the full uint64 range, design a DECIMAL(20,0) column with bounds and review driver decoding, key generation and FKs. |
CREATE TABLE cents(n DECIMAL), then insert 1.6 | Reading n returns 2. A bare declaration means DECIMAL(10,0). | Specify precision and scale. A native unbounded numeric can be reported as decimal(65,30) with a warning when exported. |
Insert 0x610062 into TEXT; repeat with VARBINARY(4) | Text rejects NUL with 1366. HEX(binary_column) returns 610062. BINARY(n) additionally pads with zero bytes. | Use a binary column for payloads that require arbitrary bytes. Compare HEX() and length, including trailing zeros. |
Insert '27:30:00' into TIME; evaluate CAST('0000-00-00' AS DATE) | Both return 1292. The time column represents a time of day. | Store signed durations as integer microseconds or convert explicitly to PostgreSQL interval. Map zero dates to a business-approved value or nullable field. |
CREATE TABLE e(v ENUM('a','b')) or CREATE TABLE s(v SET('a','b')) | Both fail with 1091 in a fresh database. | Use checked text, a lookup table or an explicit bitmask according to membership and ordering requirements. |
CREATE TABLE calc(i INT, twice INT AS(i*2) VIRTUAL), insert i=4 | Reading the row returns (4,8). Both VIRTUAL and STORED values are materialized on write. | Use deterministic expressions, compare stored values after loading, and budget for storage and write cost. |
Compare strings before rebuilding unique keys
Strings are stored and returned as UTF-8. SET NAMES updates session character settings; other encodings can be approximated with warning 1105. Convert legacy-encoded source bytes explicitly and check the decoded strings.
The dialect recognizes utf8_general_ci and utf8mb4_general_ci as the general-ci implementation, and utf8_bin and utf8mb4_bin as the binary implementation. Both use PAD SPACE. Other MySQL names ending in _ci map to general-ci weights; other suffixes map to binary order. Locale-specific equivalence, ordering, uniqueness and duplicate-key arbitration can change. String literals can behave differently from columns: in the C-locale example database SELECT 'a'='A' returned 0.
The warning code was 1105, the effective definition contained utf8mb4_general_ci, and the last insert returned 1062. Load candidate keys into a staging table without a unique index and group by the proposed target key, including any prefix length. Resolve collisions before creating the unique index.
Transaction boundaries and snapshots
With MySQL autocommit disabled, COMMIT and ROLLBACK delimit application work. DDL, a new BEGIN, and enabling autocommit can commit preceding writes. In a scratch schema, BEGIN; INSERT INTO counters VALUES (2,7); CREATE TABLE boundary(i INT); ROLLBACK; leaves row 2 and the new table. Separate schema changes from work the application expects to roll back. Native PostgreSQL transactions retain PostgreSQL transactional DDL and error semantics.
At the MySQL endpoint, read-uncommitted, read-committed and read-write repeatable-read use PostgreSQL statement snapshots. Read-only repeatable-read and a consistent snapshot retain a transaction snapshot. For a two-connection check, create meter(id INT PRIMARY KEY,v INT) with row (1,10). Set A to SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ. Read v in A, let B commit UPDATE meter SET v=20 WHERE id=1, then read again in A. Reset to 10 between trials.
| A starts with | First read | Second read |
|---|---|---|
START TRANSACTION READ WRITE | 10 | 20 |
START TRANSACTION READ ONLY | 10 | 10 |
START TRANSACTION WITH CONSISTENT SNAPSHOT | 10 | 10 |
For reports, request a stable snapshot explicitly. For concurrent writes, retry the whole transaction after 1213 / SQLSTATE 40001. Serializable uses PostgreSQL isolation. InnoDB gap locking is unavailable. LOCK TABLES and UNLOCK TABLES are accepted without taking table locks or committing, so quiesce writers when a migration needs exclusivity.
Indexes and foreign keys
A normal bounded full key can use a native B-tree. A true prefix key such as PRIMARY KEY(k(3)) enforces uniqueness on the prefix. In the round-trip test, inserting abcZ next to abc1 returned 1062 after restore. True prefix and oversized indexes recheck the heap, with no index-only scan or index-provided ordering. MySQL index hints are accepted and ignored. Examine the native query plan and benchmark your actual key distribution.
A table-level FOREIGN KEY(i) REFERENCES parent(i) requires a type-compatible primary or unique parent key. With only KEY(i) on the parent, creation failed (SQLSTATE 42830). Check for duplicates before adding a unique constraint. New orphan inserts under enforcement report 1452. Re-enabling checks leaves historical orphans in place; run an anti-join after a bulk load.
SET FOREIGN_KEY_CHECKS=0 is session-local. In this release, skipping a specific FK requires ownership rights on the referencing (child) table or superuser status. Otherwise the constraint and parent-side actions still apply, with a warning. SECURITY DEFINER execution keeps checks active. A pending FK created before its parent still requires proper parent access when bound. Preserve the extension’s metadata triggers in native backups.
Prepared statements
The SQL-level example below returned 42. Wire-level server preparation is a separate path. The Go and JDBC runs used binary parameters and checked result types, errors and subsequent connection use. Driver results and settings
Check the application connection
A successful CLI login establishes reachability. For supported HBA methods and TLS see authentication. For JDBC and Go parameter modes, result types, generated IDs and reuse after a database error, see tested clients.
GTID replication and stored procedures also affect the cutover plan. Known gaps and troubleshooting
5.4 - Clients and drivers
What a successful connection proves
All results below used the matching Mimus 19.0.1 full kernel and pg_mysql 1.0 on Rocky Linux 10 x86-64. A handshake identifies the advertised protocol. A simple query exercises parsing and one result set. An application test goes further by binding values, mutating rows, checking types and observing commit or rollback from another connection.
| Client | Login and query | Workload actually exercised |
|---|---|---|
MariaDB mysql 10.11.19 | TCP, certificate-verified TLS, SCRAM-backed role, schema selection, @@version | Ordinary user created a table, inserted one row and read it. Native psql read the same key and text. |
| PyMySQL 1.1.1 | Advertised version 5.7.32-log, utf8mb4, selected schema | Orders workflow: parameterized insert, lastrowid=1, three-row executemany, aggregates and Python Decimal / datetime results. Updated two rows, rolled back, then counted zero rows with the new status. Missing table reported 1146. |
Go database/sql + go-sql-driver/mysql 1.9.3 | Default connection and TLS exercised | Server-side parameters, generated ID and row count, NULL, bytes, decimal, temporal scans with parseTime=true, duplicate key 1062 and subsequent reuse. A second connection saw the write only after commit. |
| MySQL Connector/J 8.4.0 | Preferred and required TLS, a separate RSA login and cached login | useServerPrepStmts=true: prepare-time metadata, generated keys, BLOB/NULL, batch and duplicate-key handling. setAutoCommit(false), rollback, commit and re-enabling autocommit passed. |
Oracle MySQL mysqldump and mysql 5.7.32 | Authenticated and selected the fixture schema | Exported and replayed supported DDL, a view, binary/generated values, a prefix PK and foreign keys. Destination was Mimus. Restore procedure |
Connect an application
With the schema and role from the quick start, use TCP and pass the application schema as database. This Python example prompts for the password. Set MYSQL_CA to the trusted CA file or the public certificate from the loopback example.
Choose the preparation mode your application uses
PyMySQL binds %s in this example by escaping values client-side and sending text SQL. The Go driver’s default parameter path and Connector/J with useServerPrepStmts=true use the binary statement protocol. COM_STMT_PREPARE, EXECUTE, CLOSE, RESET and SEND_LONG_DATA are implemented. A single prepared statement accepts one SQL statement. Distinguish statement reset from COM_RESET_CONNECTION, which also rolls back active work and clears session state. A pool that issues COM_CHANGE_USER will need a new connection instead.
Reproduce the checks for your driver
Record the driver version, TLS mode, interpolation/server preparation, autocommit and pool reset behavior. On a disposable schema insert a value containing quotes and binary zero, read its type and bytes, check duplicate-key handling, roll back and read from a second connection. Use a binary column for the zero byte. The 19.0.1 session transaction run passed 56 checks; the named versions in the table bound the result. Other drivers, ORM schema discovery and connection pools need their own runs.
5.5 - Migration and recovery
Plan the move
Build a fresh target cluster with the matching kernel, module and SQL installation. Migrate application objects and data logically. An old OpenHalo data directory, a physical pg_upgrade from that line, and ALTER EXTENSION aux_mysql UPDATE have no supported path to this fresh pg_mysql 1.0 installation. Keep the original DDL: old catalogs may already have lost a prefix length, binary width or generated expression.
Inventory PostgreSQL roles, owners, grants and schema dependencies separately from rows. Translate application objects that refer to historical extension names or C libraries. Decide how to represent uint64, durations, zero dates, ENUM/SET, NUL and collated keys before loading. Examples and alternatives
Restore a native archive
For a same-version Mimus rehearsal, use the matching PostgreSQL 19 tools. This example runs on the quick-start cluster using its native local socket as the database administrator. It restores schema app into a new database. The role app_user already exists cluster-wide; create reviewed roles and grants on a different cluster before restoring. Include external dependencies separately when selecting a single schema.
Keep security labels and metadata triggers for MySQL definitions, including pending foreign keys. Preserve owners and reviewed privileges. Use native psql for inspection of restore_check; the MySQL listener continues to enter its configured database. To check restored MySQL behavior on another target, set that isolated instance’s mysql.database to the restored database and reconnect.
Restore a MySQL SQL dump
The 19.0.1 round trip used Oracle MySQL 5.7.32 tools. Run mysqldump --version before exporting. Tools shipped under the same command name can differ: MariaDB 10.5’s dump client can include generated column values that cannot be inserted. Stop source writes and DDL for this rehearsal, or arrange a separately verified consistent snapshot. The example uses TCP and interactive passwords. Supply the TLS identity options and CA for your endpoints.
These two commands copy only the quick-start table. Its only trigger is maintained by pg_mysql for auto-increment. With the default trigger export, Oracle 5.7.32 exited with status 2 after writing the row, leaving a partial file. With --skip-triggers, export exited 0, table DDL recreated the identity behavior, and the first new insert after restore received ID 2. Check the exit status before replay. For tables with business triggers, use the native archive or separately translate, restore and exercise every trigger. For the schema-level test below, trigger export stayed at its default.
Use a fresh target instance, initialize the extension and create the empty app schema for its owner. The dump account needs read and view-definition privileges on its objects, the restore account must be able to create and populate them. Replay through the MySQL port to preserve quoting, executable comments and session variables. In the fixture, both archive paths preserved binary bytes, generated values, the view and prefix primary key. The tests checked new-orphan rejection, historical orphans, binding a missing parent, and cascading deletes after restore. Restoring this dump on an independent Oracle MySQL server was outside this run.
Verify encrypted tables
Before using ENCRYPTION='Y', preload both pg_tde and pg_mysql, install both in the target PostgreSQL database and configure its key provider and principal key. The MySQL clause selects the table access method. A displayed ENGINE=InnoDB is compatible spelling. Check the PostgreSQL access method and encryption flag to identify the actual storage. A logical dump contains readable data and requires protection of its own. Prepare keys on the restore destination and check physical encryption after loading. PG TDE setup and key management
In mysql, the definition included ENCRYPTION='Y' and the row read back as 7. In native psql -d postgres, the following returned notes | heap | f, sealed | tde_heap | t, sealed_copy | tde_heap | t, and sealed_pkey | btree | t. The primary index still reports its index access method; check the encryption flag separately.
The full-kernel two-node test also read a MySQL write via TDS and a TDS write via MySQL, with encrypted tables and primary indexes on both nodes. Explicit ENCRYPTION='N' requests heap and is subject to the database encryption policy. Rehearse encrypted recovery with your actual key provider; the logical round-trip fixture above used ordinary tables.
Cut over and roll back
- Rehearse on a separate target. Compare row counts and key ranges,
HEXof binary values, collated duplicates, orphan counts, generated values, next identity value, ownership and application grants. Test a commit and a rollback over the actual driver. - Quiesce source writes, drain open transactions, take the final consistent export and repeat the comparisons. MySQL GTID replication is unavailable (
@@gtid_mode='OFF', both GTID sets empty). A PostgreSQL WAL position cannot resume a MySQL GTID stream. - Switch application connections and keep the source and backup intact. Before the first target write, rollback can route clients to the source. After any target commits, stop writes and reconcile those transactions before reopening the source.
5.6 - Limits and troubleshooting
Connection problems
| Symptom | What to check | Action |
|---|---|---|
mysql looks for a socket file, or gets a protocol error | The MySQL listener is TCP-only. Port 5432 normally speaks PostgreSQL. | Use --protocol=TCP -h 127.0.0.1 -P 3306 or substitute the configured address and port. |
| Connection refused after a configuration change | Via psql, check SHOW shared_preload_libraries and pg_settings.pending_restart. In the server log look for MySQL protocol listening on port or a socket bind warning. | Restart after changing the preloads, addresses or port. Check port conflicts, mysql.listener_on and whether mysql.port=0. |
| Login fails before any SQL | Check the first matching HBA line using the PostgreSQL database name, role, client IP and TLS mode. Check the role has LOGIN, a current password and the required verifier. | Correct the matching rule, reload HBA, reconnect and verify the certificate. For cold-cache SHA-2 login use TLS or a client configured for RSA exchange. |
| Ordinary role is told to install the extension | In psql check SHOW mysql.database. Connect to that database and query pg_extension there. | As a superuser run CREATE EXTENSION pg_mysql in the target. Grant the application access to its schema. |
| Login works but tables are missing | Compare MySQL SELECT DATABASE() with native SELECT current_database() and the table’s schema. | Use USE app in MySQL and a schema-qualified name such as app.notes in the native target database. |
| Module missing or server refuses to start after removing a preload | Check the selected installation’s pg_config --pkglibdir, the preload list and the startup log. A cluster can record mysql in mimus_required_features once it has installed MySQL objects. | Restore the matching kernel, module and preload. To close the port while keeping the required callbacks, restart with mysql.listener_on=off. Kernel checks |
Unexpected results or failed restore
| Observation | Check or remedy |
|---|---|
| 1264 on a large positive ID, 1366 on text, 1292 on a date or time | Compare the source range, raw bytes or temporal value. Convert explicitly before replay. Type examples |
| Unique-key conflicts differ or ordering changed | Run SHOW WARNINGS immediately after DDL, then SHOW CREATE TABLE. Compare the effective collation, key prefix and candidate duplicates. For a comparator version warning, inventory dependent indexes and partition keys before rebuilding and checking them. Collation example |
| A foreign-key violation persists after disabling checks | Check referenced-key uniqueness and the owner of each referencing table. Re-enabling checks does not repair old rows. FK behavior |
| A dump contains rows, but the client exited nonzero | Treat the dump as incomplete. Inspect generated columns, trigger definitions and the exact client version. Oracle 5.7.32 returned 2 on the quick-start identity table with default trigger export. Rehearsed alternatives |
pgcmp installation conflicts over the bit to bytea cast | Install pgcmp and pg_mysql in separate PostgreSQL databases. |
Limits to account for before cutover
Stored procedures through the MySQL dialect, MySQL Unix sockets, KILL [QUERY], COM_CHANGE_USER and MySQL GTID replication are unavailable. Applications requiring these interfaces need changes before cutover. For consistent reporting or exclusive maintenance, use the tested transaction behavior.
Workloads using other drivers or pool reset policies, MySQL 8-specific metadata and collation tailoring, arbitrary stored DDL, or their own triggers need application-level verification. An advertised version string, an ORM login and a single successful query each leave those paths open. The published examples also leave production key-provider recovery and the performance of large prefix-key collision groups to the operator’s rehearsal. Driver coverage · Restore coverage
5.7 - Protocol, dialect and origins
From TCP connection to table
Patch 300 imports the OpenHalo server hooks. At startup the preloaded extension registers a TCP listener. On connection, a PostgreSQL backend exchanges a MySQL handshake, chooses the native database configured in mysql.database and authenticates the PostgreSQL role. It checks for the extension in that database before accepting application SQL. The database name sent by the client selects a schema inside it. 300/301 kernel patches
Parsing and execution
The extension implements the MySQL grammar, rewrites supported DDL and DML, implements compatibility types and functions, and encodes results in MySQL packets. PostgreSQL plans and executes the query and stores its rows. Patch 301 integrates dialect-specific coercions, managed collation callbacks, foreign-key checks and startup requirements. A native client uses the PostgreSQL protocol and parser against the same catalogs. SQL behavior at each endpoint
Names in the native database
The example MySQL database app maps to schema app. The extension installs its own schemas too: mysql for compatibility objects, mys_informa_schema for information-schema compatibility, performance_schema and mys_sys. Export application objects separately so the target installer can create the extension-owned objects.
Identify this build
| Component | 19.0.1-r4 identity |
|---|---|
| Native kernel | pgsty/mimus at 0d8a551aa121, tree 07fbb73680de. This integrates the nine patches on PostgreSQL REL_19_0. |
| OpenHalo kernel input | pgsty/openhalo at a7e6d509db7f for the upstream part of 300. 301 carries the Mimus adaptations. |
| Standalone extension | pgsty/pg_mysql at 1e631f9802c5, tree 53dd9be3e87b. Build this commit directly with the matching kernel’s pg_config. pg_extension.extversion and pg_get_loaded_modules() report 1.0. |
| MySQL protocol | The handshake, VERSION() and @@version return mysql.compat_version, which defaults to 5.7.32-log. @@version_comment returns mimus. |
Origins and license
The grammar, original SQL definitions and compatibility routines descend from Halo Tech’s PostgreSQL 14 work. PGSTY ported the work to PostgreSQL 18/19 and extracted the standalone pg_mysql from OpenHalo’s aux_mysql. Ruohang Feng maintains the extension at PGSTY PTE. LTD. Earlier cross-kernel experiments belong to the OpenHalo 18 porting history. OpenHalo source · History of the earlier port
The standalone extension carries GPL-3.0-or-later and retains the original Halo Tech Co., Ltd. and openHalo.org notices, copyright 2019–2026. The parser retains Jet C.X. ZHANG’s credit. The source also credits PGSTY PTE. LTD. (2026), the PostgreSQL Global Development Group (1996–2026) and the Regents of the University of California (1994). PostgreSQL-derived portions and keyword tools retain the PostgreSQL License. The distributed LICENSE, COPYRIGHT and 3party-legal-notices contain the full notices. Original Halo Tech copyright notice
Other kernels
The examples here require Mimus 19.0.1’s matching server callbacks and module. The old experiments with IvorySQL and Babelfish used different kernels and extension identities. For SQL Server access on this Mimus kernel, use its paired Babelfish extensions. SQL Server manual · Encrypted table access methods
6 - SQL Server
Mimus 19.0.1 implements SQL Server compatibility with Babelfish for PostgreSQL. SQL Server clients connect to a PostgreSQL backend over Tabular Data Stream (TDS, default TCP port 1433) and submit T-SQL. The DBA uses a native PostgreSQL connection (default 5432) to initialize Babelfish, inspect the physical tables and back up the cluster.
Start with one table
On Rocky Linux 10.3 x86-64, FreeTDS 1.5.18 logged in to master, inserted two rows and read back a sum of 42. A PostgreSQL connection saw the same rows in wire.master_dbo (database and schema). Deploy TDS on its own Mimus instance if the application also uses MySQL. Follow installation and initialization and your first TDS connection to repeat the check.
| What you need to decide | Where to look |
|---|---|
| Which logical database, schema and login should an application use? | Database, schema and role mapping |
| Will my driver, stored procedures and transactions work? | T-SQL and client compatibility |
| How do I move data, back it up and verify recovery? | Migration and operations |
| How do I create an encrypted table over TDS and verify its indexes and large values? | Create encrypted permanent tables over TDS |
| My procedure uses both encrypted and temporary tables. What can reach disk in plaintext? | Temporary tables, table variables and plaintext on disk |
| How do I diagnose a failed login, import or restore? | Known limits and troubleshooting |
What the version identifies
Mimus is based on PostgreSQL REL_19_0. Patch 400 imports the Babelfish kernel changes. Patch 401 ports them to PG19 and integrates the protocol handlers. The frozen nine-patch baseline has kernel tree e94b1957f077 and Babelfish extension tree 7ae1f519a130. The earlier connection and source-build examples in this manual used kernel tree 98c4dca860f0. The encrypted-table and temporary-object guides use candidate image a3b80a5a99a1 with additional patches. Check the kernel and extension trees together when identifying a build. Candidate build manifest
Upstream credit
Babelfish for PostgreSQL comes from Amazon Web Services and the Babelfish and PostgreSQL contributors. Its extensions are available under Apache-2.0 or the PostgreSQL License. The monetary type derives from EDB / 2ndQuadrant’s fixeddecimal. The modified PostgreSQL kernel carries the PostgreSQL License. Upstream extensions and notices · Upstream kernel
For additional T-SQL and migration reference, consult the PG.CENTER Babelfish manual.
6.1 - Install and initialize
Check the installation
Use a Linux installation of the matching Mimus kernel and extensions. The PostgreSQL 19 version string alone cannot identify the patched ABI. If building from source, compile the complete kernel with ICU, OpenSSL, libxml2 and libuuid support, install its contrib/uuid-ossp, then build the four Babelfish modules against that installation’s pg_config and its matching PG_SRC. The T-SQL parser uses Java, CMake and the ANTLR 4.13.2 C++ runtime. The isolated upstream port and the Mimus build use different TDS interfaces. Upstream build dependencies
| Extension | SQL version | What it installs or provides |
|---|---|---|
babelfishpg_common | 7.0.0 | SQL Server types, casts and collations in sys. Its control file declares no extension dependencies, but its monetary functions load the money shared library. |
babelfishpg_tsql | 7.0.0 | T-SQL parser, procedural language, functions, system catalogs and initialization. Requires babelfishpg_common and uuid-ossp. |
babelfishpg_tds | 1.0.0 | TDS listener, login and packets. Preload the library at startup, then create the SQL extension in the target database. Requires babelfishpg_tsql. |
babelfishpg_money | 1.1.0 | Standalone fixed-decimal monetary extension. The tested installation creates it explicitly, outside the TDS dependency chain. |
Start an empty instance
These commands assume a fresh, isolated Linux host or container with ports 5432 and 1433 available. In the shell, run as the OS account postgres. Put the Mimus bin directory first in PATH. Keep this shell for the rest of the guide so PGHOST selects the private Unix socket. The final command should report server started.
Configure the target through psql
Connect to the PostgreSQL endpoint as cluster superuser postgres. In the listing below, the first line opens interactive psql. Run the SQL and backslash commands at its prompt. Enter a new password twice at \password and keep it for the TDS login.
Expect ALTER SYSTEM, CREATE ROLE, CREATE DATABASE and ALTER DATABASE. The bbf_admin login owns the physical database and becomes the initial T-SQL administrator. The example ran with rolsuper = false. Give applications their own logins and database users. The preload list here is for an empty instance. On a configured cluster, retain its existing required libraries when adding babelfishpg_tds.
As the OS account postgres, put this entry before the general host rules in $PGDATA/pg_hba.conf. The database field is the physical database wire. This password-only, loopback rule is for the local exercise. For a remote client use TLS with certificate validation.
Restart this instance as its OS owner. Restart loads the TDS library and binds the ports. A reload alone cannot apply either change. A fresh connection to wire also picks up its database-level migration mode. Choose the mode before initialization. Mapping in each mode
Initialize the physical database once
In the new psql session as PG superuser postgres in wire, run the following commands. The three settings should read babelfishpg_tds, wire and single-db. The installation setting applies only to this session. CASCADE installs the three declared dependencies. The final query should list the four versions above plus uuid-ossp 1.1.
CALL creates cluster roles and the built-in logical databases master, tempdb and msdb. Its argument must name the physical database owner. Once it succeeds, connect using bbf_admin on the TDS port. First TDS connection · Upstream initialization procedure
Build from paired source checkouts
The two tree checks here reproduce the earlier connection example. For the TDS encryption guides, use the paired sources with the kernel, Babelfish and pg_tde increments. Identify the four-change candidate
If the server and modules are already installed, start at the empty instance. Otherwise run this in a build-user shell with writable, clean checkouts of the indicated trees and a fresh install prefix. Replace all three paths. Install the development dependencies above plus GNU make, a C/C++17 toolchain, Bison, Flex and the ANTLR runtime under /usr/local first. The tree checks exit silently on a match. At the end, the prefix contains the server, PGXS and extension files. Make that prefix and the runtime libraries accessible to the server OS account.
6.2 - First TDS connection
Log in and write two rows
After initialization, run this in the local client shell. FreeTDS tsql prompts for bbf_admin’s password. -H and -p select the TCP endpoint. -D master selects a logical database at login. The 1> prompt means the client accepts a new batch.
Enter the following at the tsql prompt in the fresh example database. GO on its own line sends the batch. exit returns to the shell. Expect master, followed by n = 2 and total = 42. Use an application database for real tables. Here master makes the example reproducible immediately after initialization.
From the same shell as the OS account postgres, check the rows through native psql. Expect wire | 2 | 42. The TDS session wrote to dbo in logical master. PostgreSQL sees the table in physical schema master_dbo.
Address, authentication and client settings
| Parameter | Behavior in this build |
|---|---|
| Server address and port | The TDS bind code reads PostgreSQL listen_addresses. Although babelfishpg_tds.listen_addresses is registered, setting it alone does not restrict this listener. babelfishpg_tds.port defaults to 1433. Restart for a binding change. |
| Database and user | HBA matches the physical babelfishpg_tsql.database_name, source address and login. The driver sends the logical database (JDBC databaseName). HBA uses the first matching rule. Reload changes and reconnect. Check both IPv4 and IPv6 when using hostnames. |
| Password login | The password and md5 HBA branches verify the password from LOGIN7 against the PG role’s stored verifier, including SCRAM verifiers. A scram-sha-256 HBA method is rejected. trust skips verification. Use TLS for network password logins. |
| Integrated login | The gss path needs a GSS-enabled build and working Kerberos credentials. NTLMSSP is rejected. SSPI as an HBA method, peer, ident, LDAP, PAM, BSD and certificate login are unsupported in the TDS handler. OAuth login returns an authentication error. The exercised login used a password. |
| Wire version and packets | The server default babelfishpg_tds.tds_default_protocol_version = DEFAULT follows the client. The configured choices run through TDS 7.4. The walkthrough uses 7.4. Default packet size is 4096 bytes. A nonzero client request must be 512–32767 bytes and sizes are rounded down to a multiple of four. The server answers the MARS option with zero. Use separate connections for overlapping active results. |
Upstream TDS listener · Login and PRELOGIN handling · TDS settings
Verify TLS on the actual session
Use an OpenSSL-enabled Mimus build. As the server OS owner, install the server certificate and private key, readable by PostgreSQL with the usual private-key permissions. The certificate must cover the hostname the client uses. For this example it covers localhost. Configure the server in postgresql.conf as follows.
The TDS minimum and maximum default to TLSv1 and TLSv1.2. TLS 1.3 is outside the TDS version selector. The TLS and encryption parameters are registered for reload, but the extension builds its TLS context at server startup. Restart after configuring the certificate, key or protocol bounds and establish a new session. With server SSL active, tds_ssl_encrypt = on requires full-session encryption in PRELOGIN. With the default off, a client can request full encryption, login-only encryption or no encryption according to its capabilities. The switch alone cannot supply a missing TLS context.
Replace the local exercise’s HBA line with hostssl wire bbf_admin 127.0.0.1/32 password for this IPv4-only endpoint. For remote operation, scope it to the actual client address, bind the service to the intended interface and exclude plaintext fallback rules for that login. On the client, put this profile in freetds.conf and substitute the path to the issuing CA.
Connect as bbf_admin. In the example the server is bound to 127.0.0.1. The client reaches it as localhost and checks that hostname against its certificate.
At the tsql prompt run this query. The verified FreeTDS 1.5.18 session returned 1 | TLSv1.2. With Microsoft JDBC the corresponding client settings for full encryption and certificate validation are encrypt=true and trustServerCertificate=false, with a trusted issuing CA and matching hostname. The JDBC bulk-write test used a separate loopback configuration.
6.3 - Databases, schemas and roles
Choose the mapping before initialization
One PostgreSQL cluster hosts one initialized Babelfish physical database, selected by babelfishpg_tsql.database_name. All TDS connections enter that database. The login packet and T-SQL USE select a logical database inside it. Thus the HBA entry and psql -d name wire, while the driver names master or a user database such as sales.
| At the TDS endpoint | Native PG schema in single-db | Native PG schema in multi-db |
|---|---|---|
master.dbo | master_dbo | master_dbo |
tempdb.dbo / msdb.dbo | tempdb_dbo / msdb_dbo | tempdb_dbo / msdb_dbo |
sales.dbo | dbo | sales_dbo |
sales.billing | billing | sales_billing |
single-db admits one user database in addition to the built-ins. Choose multi-db when several user databases need separate namespaces in one physical database. Each mode above was initialized in a fresh instance. FreeTDS created sales.dbo.orders and read one row in both. Changing the parameter after initialization would leave existing names and metadata in the old layout. To change layouts, provision a fresh target and migrate the application objects and data.
Look up a name from PostgreSQL
At the TDS endpoint, dbo.mimus_probe is a two-part name relative to the current database. master.dbo.mimus_probe specifies all three parts. At the native endpoint, connect to wire and qualify the physical schema. Shared schemas have special rules (for example, T-SQL INFORMATION_SCHEMA maps to information_schema_tsql). Long physical identifiers can be shortened with a hash. Read the mapping catalog when writing native reports or grants. Upstream schema and user mapping
In native psql, connected as postgres to the initialized wire, this query returns master | dbo | master_dbo. Change the filter to inspect a user schema.
Separate logins from database users
A server login authenticates the connection. A logical database user supplies the identity for grants in that database. Use the TDS endpoint for CREATE LOGIN, CREATE USER … FOR LOGIN, role membership, and ALTER LOGIN or DROP LOGIN. Grant the application’s database user access to the specific schema and objects it needs. Use sys.server_principals and sys.database_principals to inspect the two scopes. Use native PG tools for native roles.
The initializer checks the physical owner and reserves cluster-wide roles, including sysadmin, bbf_role_admin and the built-in databases’ guest roles. On an earlier integrated PG19 build with this same TDS extension, native superusers could be managed before and after initialization, in both the initialized physical database and the ordinary postgres database. A real TDS login remained protected against a native DROP ROLE in both databases. Mimus distinguishes actual guest-role membership from the implicit privileges of a PG superuser. Create a separate PG database for an unrelated application if needed. The roles still belong to the cluster. Upstream ownership catalogs
6.4 - T-SQL and client compatibility
Which client operation was tested?
| Client or API | Observed result | What to check for an application |
|---|---|---|
FreeTDS 1.5.18 tsql, TDS 7.4 | On the matching Rocky x86-64 build, password login, logical database selection, table DDL, two-row DML, a procedure call and TLS 1.2 worked. | Run the actual result sets and parameter types through the driver used in production. |
Microsoft JDBC 8.2.2.jre8 SQLServerBulkCopy | On a preceding integrated PG19 build with the same Babelfish extension tree, two integers reached an encrypted table. PG read 2 and 40. The bulk test used databaseName=master;encrypt=false on loopback. | Check server-side row counts and values. Re-test with the deployed JDBC version, TLS settings and real column types. |
FreeTDS 1.3.17 freebcp | On the standalone PG19 port and upstream beta, the utility reported two rows copied. The server rejected the bulk packet and stored zero. | Reconcile counts on the target. Use the exercised JDBC bulk path or parameterized inserts after testing them with the application. |
sqlcmd, SSMS, .NET SqlClient, ODBC and Python drivers | Upstream documents SQL Server clients. There is no complete application or driver-suite result for these tools on this Mimus build. | Check prepared RPCs, output parameters, result-set metadata, connection pooling and reset, cancellation and reconnect with the exact client version. |
Procedures and batches
In FreeTDS tsql as bbf_admin in master, after the two-row example, submit the definition and invocation as separate batches. The integer parameter 1 returned amount = 40 and return status 0. This exercises a T-SQL call sent as a SQL batch. Driver RPC calls, output parameters and multiple results take additional client paths.
For procedures using temporary objects, inventory each @table and #temp, including those in nested procedures. Compare success, error and rollback paths with the source application. Use a separate batch for each procedure definition and let the client consume GO. Drivers executing SQL strings generally need the caller to split batches.
The default escape hatches for index clustering and storage options are ignore. A migrated PRIMARY KEY CLUSTERED or filegroup clause can parse without reproducing SQL Server’s physical layout. Check the resulting indexes and query plans. Procedures that rely on equivalent locking or placement need a separate design. Upstream T-SQL settings
Types, text comparison and views
| Case | Observed behavior | Migration decision |
|---|---|---|
| Fractional time | On the earlier four-component tree, the nanosecond part of CAST('2000-01-01T12:34:56.1234567' AS datetime2(7)) was 123457000. SQL Server’s type can represent 100 ns. | If the seventh digit orders events or distinguishes keys, retain the source ticks in an integer or exact numeric column. |
ISNULL in a persisted view | On an earlier integrated build, with a nullable varchar(3) column and a varchar(6) replacement, the ISNULL view column kept the first input’s type modifier. COALESCE had no length modifier. A concatenated TDS query returned abcdef/abcdef for the NULL row. SQL Server documents possible truncation to the first argument’s type. | Specify the required result width explicitly. Check the returned value and the metadata through the application driver. |
| Collations and trailing spaces | The default server collation is sql_latin1_general_cp1_ci_as. In a PG19 comparison, native text under sys.bbf_unicode_cp1_ci_as and sys.bbf_unicode_cp1_cs_as agreed with matching ICU controls. Case differed between CI and CS. Both distinguished a trailing space. T-SQL varchar equality ignored the trailing space. | Replay joins, unique keys and orderings with case, accents, composed characters and trailing spaces. Carry the intended type and collation into native queries. |
| Numeric, monetary, binary and identifier types | The extensions supply SQL Server types and conversions, including money, uniqueidentifier, datetimeoffset and sql_variant. The integer bulk-copy result covers none of their wire encodings. | Round-trip decimal scale, Unicode, raw bytes, offsets, NULLs and the base type of variant values through the intended import path. |
TOP … PERCENT views | Four earlier PG19 TDS view cases returned 5, 7, 4 and 3 rows. They covered plain selection, unions and values. | Compare your view’s ordering and ties on real rows before relying on the selected subset. |
SQL Server datetime2 · SQL Server ISNULL · Upstream Babelfish data types
Transactions and temporary objects
In the PG19 integrated heap tests, each object started with 7. An explicit transaction added 4 and rolled back. The batch-local @table retained both rows (sum 11). A local #temp, SELECT INTO #temp and a persistent table each returned 7. A new batch also ends a table variable’s scope. Code that needs data in subsequent batches should choose its object and connection lifetime accordingly. The default encrypted access method changes whether these objects can be created. T-SQL temporary-object settings and storage
In a PG19 three-protocol concurrency test at READ COMMITTED, a TDS update waited on a locked integer primary key. An in-place change committed by the lock holder yielded one updated row. A committed delete and reinsert with the same key yielded zero for the waiting TDS update, even though the replacement row existed. The result held on heap and tde_heap. Compare @@ROWCOUNT and retry logic under the SQL Server application’s actual isolation settings. The concurrency run had no SQL Server reference instance. PostgreSQL transaction isolation
6.5 - Create encrypted permanent tables over TDS
A SQL Server client can create an encrypted permanent table on Mimus with an ordinary CREATE TABLE. The DBA supplies the key and the creation default. Applications then use their usual INSERT, UPDATE and SELECT. A migration can also select encryption for a single transaction. This guide covers the 19.0.1 candidate with the four accepted changes, tested over TDS 7.4 on Debian 13 x86-64 image a3b80a5a99a1. Identify the build and patches
Prepare the key in the physical database
Start with an initialized Babelfish instance. The PG administrator uses psql to connect to physical database mimus on port 5432. The TDS client connects to logical database vault on port 1433. The example assumes deployment login lab_deploy maps to a user with permission to create tables in vault. Preload pg_tde and babelfishpg_tds, and install the pg_tde extension in public in the physical database. Instance initialization · Login and schema mapping
For a new test database, run the following on PG. First create /var/lib/mimus-keys outside PGDATA on the server, owned by the database service account with mode 0700. A database with a principal key already configured can use its existing key. Both the production and recovery systems need access to the same keys. Key providers and recovery
Create encrypted tables by default with ordinary T-SQL
If the application uses temporary tables, the PG administrator can give runtime connections the heap default and require encryption on the deployment login with tde_heap. These settings take effect on new physical connections. Recycle the affected connections in any pool.
Reconnect to vault as lab_deploy and send the following TDS batch. The first query shows the logical database and the login’s effective default. An application login granted DML privileges on the resulting table can read and write it with its own default set to heap.
Expect vault, tde_heap and a final value of paid. To require every application table to go through encrypted deployment, reserve permanent DDL privileges for the deployment login and grant the runtime login only the DML privileges it needs. A login with permission to create tables can override the AM default when enforcement is off.
For a physical database dedicated to encrypted tables, the PG administrator can apply both settings at database scope. New tables default to encryption and requests for heap are rejected. The settings apply across the logical databases mapped into that physical database. Existing plaintext tables require a separate rewrite. Use the mixed configuration above for connections that need T-SQL temporary objects. Convert an existing table · Settings for temporary objects
Select one table in a mixed database
On a deployment connection with default heap and enforcement off, create dbo.chosen in a dedicated transaction. Turn implicit transactions off, finish any open transaction, and send the complete script as one TDS batch. The same file is installed in the image at /usr/mimus-19/share/mimus/examples/tds-encrypted-table.sql. Download the tested deployment script
After BEGIN TRANSACTION, the script calls this PostgreSQL configuration function over TDS. The 'true' argument limits the setting to the transaction. Other tables created in that transaction inherit the same setting. Commit or rollback restores the connection’s previous default.
The script locates the table through sys.tables and sys.schemas. It commits once the table, primary-key index, unique index, TOAST table and TOAST index are all present and encrypted. An open transaction or implicit transactions turned on yields error 50000 at entry, leaving the caller in control of its transaction. A missing or plaintext member rolls back the deployment with error 51001. Adapt both the table name and the expected indexes when using the script for another schema.
Verify the physical storage from PG
After deployment, run this query as the PG administrator in mimus. In the example’s single-db mapping, vault.dbo maps to PG schema dbo. Substitute dbo.invoice for dbo.chosen to check the role-default example. For another mapping, look up the physical schema first. Look up a schema
Both sample tables should return five rows, all with encrypted true. The table and TOAST table use tde_heap. The three indexes use btree. During acceptance a 32,018-byte varchar(max) value in dbo.chosen occupied 17 TOAST chunks. After a restart, a new TDS connection read the same digest and committed an update visible to the next connection.
Migrate SQL Server TDE scripts
SQL Server protects its database encryption key (DEK) with a certificate or asymmetric key and enables TDE with ALTER DATABASE … SET ENCRYPTION ON. On Mimus, manage the provider and principal key through PG, check each physical relation, and configure WAL encryption separately. A TDS CREATE TABLE with WITH (ENCRYPTION=ON) or OFF fails before creating the table. SQL Server certificate and DEK commands and sys.dm_database_encryption_keys cannot manage or verify pg_tde storage. Microsoft’s TDE reference · WAL encryption on Mimus
6.6 - Temporary tables, table variables and plaintext on disk
A runtime login with heap and enforcement off can read and write encrypted permanent tables and use table variables, # tables and SELECT INTO # on the same TDS connection. The Mimus 19.0.1 candidate with the four accepted changes allows these temporary objects to reach disk in plaintext. Copying a row from an encrypted permanent table to a temporary table can put a plaintext copy in a file. Deploy encrypted permanent tables
Choose settings for the runtime login
The PG administrator can set these values for the runtime login in physical database mimus. Reconnect over TDS to logical database vault. A runtime login that already inherits heap/off needs no override. The deployment login can use tde_heap and enforcement independently.
Check the effective values on the actual TDS connection, especially when using a pool.
| Effective table AM at creation | Enforcement | All three T-SQL temporary objects |
|---|---|---|
heap | off | Creation succeeds. Temporary relations use ordinary heap storage. |
tde_heap | off or on | Creation fails with Unexpected catalog OID 2601 referenced in ENR. The Babelfish private temporary catalog cannot record the dependency on pg_am. There is no automatic fallback to heap. |
heap | on | pg_tde enforcement rejects creation of plaintext relations. |
Under the mixed configuration a login with permanent DDL privileges can create plaintext application tables. To require encryption for every permanent table, reserve permanent DDL for the encrypted deployment login and grant the runtime login only its application DML privileges. Deployment and runtime privileges
What survives a rollback?
On a fresh heap/off connection, send the table-variable example below as one batch. Insert 7, add 4 inside a transaction, then roll back. The sum is 11. The equivalent operation on each of the two other temporary objects returns 7.
| Object | Opening statements in a separate batch | Sum after rollback |
|---|---|---|
| Table variable | DECLARE @t TABLE(id int); INSERT INTO @t VALUES (7); | 11. Both rows are visible for the rest of the batch. |
| Local temporary table | CREATE TABLE #t(id int); INSERT INTO #t VALUES (7); | 7. The second insert rolled back. |
Temporary SELECT INTO | SELECT CAST(7 AS int) AS id INTO #s; | 7. The second insert rolled back. |
The release and assertion builds of the four-change candidate passed these cases. The same connection could execute the next statement after a constraint error handled with TRY/CATCH. A cursor still holding an inner # table could read its original rows after the procedure returned, while a new table with the same name held the caller’s own data. Scope and reference handling
Where temporary data reaches disk
| Destination | What a file can contain |
|---|---|
Heap relations for @t, #t and SELECT INTO #t | All three can contain plaintext row data. In a separate storage test, each object received 20,000 rows. Each of the three relation files on the mounted filesystem contained its own test value. |
| Query work files | A PG sort of an encrypted permanent table produced a 4,710,400-byte spill file containing the plaintext test value. The table’s pg_tde key does not cover this file. |
The product accepts these plaintext writes. Supporting tde_heap for the temporary relations would require protecting their access method across rollback, scope exit and final file cleanup. Executor spills such as sorts have a separate write path. These costs and the limited coverage are why temporary objects use heap in this build. pg_tde encryption limits
If the deployment must protect offline media, a tested setup placed all of PGDATA on a LUKS2 volume, used the default temporary tablespace and disabled swap for the service container. The markers were absent from the underlying volume. Readers with filesystem access could see plaintext on the unlocked mount. Cover the actual volumes for temporary relations and query spills when extra tablespaces are in use, and account for swap. This build cannot satisfy a requirement that these files themselves remain encrypted on the mounted filesystem. SQL Server automatically encrypts tempdb when a user database uses TDE, so check that expectation when migrating. Microsoft’s TDE and tempdb reference
6.7 - Migration and operations
Move a SQL Server application
- For a source supplied as a SQL Server .bak file, restore it in SQL Server first. Export the application DDL, including procedures, triggers, logins, users and grants. Inventory SQL generated by the driver as well. Babelfish Compass can flag constructs for review. Validate the flagged paths and the application’s own queries on the matching Mimus build. Babelfish migration guide
- Choose the mapping mode and collation for the target. Create the user database and its principals through TDS. Replay the DDL in dependency order. For a procedure, check the result sets, types and return status the caller consumes. Review ignored or rewritten clauses individually before accepting a successful import.
- Copy a representative batch with the intended driver. Compare counts by primary-key range, NULL counts, totals and values that can round or truncate. Check identity/sequence state for the next insert. Compare rows through TDS and native PG using the physical schema mapping.
- Rehearse cutover at a consistent point. Stop source writes or capture and apply outstanding changes. Run the application under its normal login, check transactions and reconcile both sides before redirecting writers. Retain the source and record how to reconcile any writes accepted after cutover.
Choose the instance boundary
Run TDS alongside native PostgreSQL. Give MySQL a separate instance and data directory, including when the two applications use different logical databases. Each instance shares preloads, roles and startup requirements across its databases. Connection architecture
An earlier two-node research run loaded both dialects, TDE and Spock on Rocky x86-64. FreeTDS and PyMySQL exchanged rows in a predefined encrypted table. Use that result as evidence for the tested storage and replication path. Choose each deployment’s listener independently. Database mapping · Spock replication
Back up the cluster and prove it can restart
Record the kernel tree, extension versions, shared_preload_libraries and SHOW mimus_required_features with the backup. Installing a Babelfish component records a cluster dependency. Restore with the matching kernel and babelfishpg_tds available at startup. When using TDE, preserve the original key providers and all keys needed for the backup and WAL.
On an earlier integrated PG19 build, JDBC wrote values 2 and 40 into a persistent encrypted table. VACUUM FULL rewrote its file. With plaintext WAL throughout, a streaming physical backup passed verification. With the source stopped and the original keys available, the restored instance served both rows over PG and TDS (sum 42) and PG confirmed encryption. When WAL is or may have been encrypted, use the matching Percona streaming backup tool in encrypted mode (pg_tde_basebackup -E -Fp -X stream). Recover to a separate data directory and read the committed rows through both endpoints. PG TDE manual · Percona backup and restore
Logical archives and upgrades
With the two-row example in place, run the Mimus client tools in the OS postgres shell, on the same PG socket. Use a new directory for the archive. pg_dump connects to the physical database. pg_restore -l reads the local archive. In the recorded pre-header-fix run the listing contained BABELFISHCHECKS and TABLE DATA master_dbo mimus_probe.
For a logical database selection, the Mimus tools recognize --bbf-database-name. One logical database dump omits server logins. Inventory globals, database users, their mappings and grants separately. The tested archive listing proves export. Independent restoration of a complete Babelfish logical database, including principals, ownership, procedures and correct TDS reads, still awaits acceptance on the final artifacts. Treat an archive as recoverable only after restoring and reconciling it on a separate instance. Upstream dump selection and checks
The dump embeds checks for equal PostgreSQL server_version_num and equal Babelfish migration mode on restore. A different minor version can therefore fail as well. There is no validated in-place cross-major Babelfish upgrade for this release. The bundled pg_upgrade also refuses a TDE-marked source or destination, including its precheck. For a version or layout change, build a new target, recreate compatible application DDL and principals, and move application data through a verified export/import path. Reconcile it before retiring the original. A same-PG19 binary change or a physical backup restored with its original binaries has different prerequisites.
6.8 - Known limits and troubleshooting
The PG port works, but the TDS client cannot log in
| Symptom | What to check | Action |
|---|---|---|
| Connection refused, or the client sees a protocol error immediately | psql speaks PG. tsql speaks TDS. The sockets use different ports. | In native psql as the DBA, inspect SHOW shared_preload_libraries, SHOW listen_addresses and SHOW babelfishpg_tds.port. Check the startup log for a bind failure. After changing the listener, restart and connect to the TDS port explicitly. |
unsupported TDS authentication | A broader HBA entry may select scram-sha-256. localhost can resolve to ::1 and miss an IPv4-only rule. | Inspect the server-reported database, role and source address. Match the physical database and the correct subnet with a supported HBA method. Put that rule first, reload and reconnect. |
| Login succeeds only with certificate validation disabled | The CA may be missing, or the client may use a name absent from the certificate. A stricter driver may also request an unsupported protocol version. | Install the issuing CA on the client, use the certificate hostname and verify the negotiated TLS version on the same session. Tested TLS settings |
| Initialization reports a reserved role or says the supplied login is not the owner | Initialization creates cluster roles and checks the physical database owner. The same cluster may already host an initialized Babelfish database. | Inspect the owner and existing roles in PG. Connect to the intended physical database. Use the existing mapping or start a fresh cluster when an independent mapping is needed. Preserve roles already in use. |
| The application connects but cannot find a table | The driver may have selected master, or a native query may be using a logical schema name. | Check DB_NAME() on TDS and current_database() on PG. Look up the catalog mapping and check the database user’s grants. Name lookup |
Permanent tables work, temporary objects fail
With an effective default of tde_heap, all three T-SQL temporary objects fail at creation. The 2601 in Unexpected catalog OID 2601 referenced in ENR identifies pg_am. On the actual TDS connection, check both default_table_access_method and pg_tde.enforce_encryption. Use heap/off for a runtime login that needs temporary objects and recycle its physical pool connections. All three objects then work, and their data can reach disk in plaintext. Runtime settings and rollback results
A deployment login can create encrypted permanent tables over TDS, or select tde_heap in a dedicated transaction and verify the resulting storage. The runtime login can then read and write them with ordinary T-SQL. Deploy and verify encrypted permanent tables
A session disappears during inspection or a mixed batch
Earlier assertion builds recorded a backend exit during storage inspection of a live T-SQL temporary object, including a table-variable case with default heap. Other connections were interrupted during server reinitialization. Ordinary heap DML and rollback have separate successful results. Keep storage diagnostics on persistent relations. After such a disconnect, inspect the server log and restart history, reconnect and verify the last committed transaction before replaying work.
The four-change candidate corrects statement and cursor reference release and the cleanup of a private scope still in use. Its release and assertion builds passed the transaction, error-handling and cursor cases. The historical records still lack direct evidence of the first incorrect release. Fix scope and build identity
In a separate isolated 19.0.1 FreeTDS run, an additional batch sequence involving a nullable string view and temporary objects ended with a client write error. The output did not establish the failing statement or a server crash. Check client messages and server logs together. Qualify the exact result-set shape and transaction used by the application. Covered procedure and type cases
An import reports success but rows are missing
One freebcp version counted client-side rows while the server reported a bulk-packet length error. SQL batch clients can also report success at process exit after a server error. Inspect server diagnostics, then query target counts and stable key/value totals from a new connection. Reconcile what was committed before retrying a partially applied batch. Driver versions and bulk results
A login cannot be dropped, or the restored server refuses to start
A native PG session is expected to refuse removal of a genuine Babelfish login. Manage that login through TDS. If an ordinary native superuser is misclassified, check that the deployed TDS module matches the 19.0.1 extension tree.
If startup reports a missing Babelfish requirement, restore the matching kernel, module files and preload configuration. Keep the feature marker and any TDE keys with the cluster. A logical archive rejected for a different PG version or migration mode needs a compatible target or an application-level migration. Backup and upgrade conditions