Skip to content
Disable Constraints During a Bulk Load

Disable Constraints During a Bulk Load

Load data that foreign-key checks would reject or that triggers should not process, for example tables loaded in the wrong order or a one-off data repair. You switch the session into replica mode, load, switch back, then check the data yourself.

To move a whole database, use the managed migration job instead: you do not need to switch replica mode yourself.

Before You Start

Triggers and foreign-key checks are skipped in a session where session_replication_role is set to replica. In standard PostgreSQL only a superuser can change that parameter. How you change it on Managed PostgreSQL depends on the version and the role:

PostgreSQL versionRoleHow to switch replica mode
16 and lateravnadminSET session_replication_role, as shown below
16 and laterAny other roleThe aiven_extras function
15Every role, avnadmin includedThe aiven_extras function

The setting applies to the current session only:

  • It disappears when the connection closes. Run the load and both SET statements on the same connection. A script that opens a new connection per statement, or a client that reconnects after an error, loses the setting.
  • Do not run the load through a connection pool in transaction or statement mode: consecutive statements can run on different server connections, so the setting does not apply to the load. Connect to the PostgreSQL port of the service, or use a pool in session mode.
  • Other sessions still run with triggers and checks enabled. Run the load when nothing else writes to the tables involved.

Switch the Session into Replica Mode

As avnadmin, on PostgreSQL 16 and later:

SET session_replication_role = 'replica';

Do the work that needs the checks skipped, then switch back:

SET session_replication_role = 'origin';

Check the current value at any time:

SHOW session_replication_role;

Worked Example

Loading order_items before its parent table orders normally fails on the foreign key. Run the whole sequence in one psql session, mixing SQL statements and the \copy meta-command:

BEGIN;

SET session_replication_role = 'replica';

\copy order_items FROM 'order_items.csv' WITH (FORMAT csv, HEADER)
\copy orders      FROM 'orders.csv'      WITH (FORMAT csv, HEADER)

SET session_replication_role = 'origin';

COMMIT;

On PostgreSQL 15, or as another role, replace the two SET statements with the aiven_extras function calls shown below.

\copy reads the file on the machine that runs psql. The server-side COPY ... FROM 'path' reads files on the database node, which you have no access to on a managed service.

Check and Re-Validate the Data

Warning

Switching back to origin does not check the rows loaded in replica mode: PostgreSQL still treats the constraint as valid. Child rows that reference a missing parent stay in the table until you find them.

For each foreign key you bypassed, count the orphaned rows:

SELECT count(*) AS orphaned_order_items
FROM order_items oi
LEFT JOIN orders o ON o.id = oi.order_id
WHERE o.id IS NULL;

Fix or delete the rows this query returns before applications use the table.

To have the database check the rows, recreate the constraint as NOT VALID, then validate it:

ALTER TABLE order_items DROP CONSTRAINT order_items_order_id_fkey;

ALTER TABLE order_items
  ADD CONSTRAINT order_items_order_id_fkey
  FOREIGN KEY (order_id) REFERENCES orders (id) NOT VALID;

ALTER TABLE order_items VALIDATE CONSTRAINT order_items_order_id_fkey;

VALIDATE CONSTRAINT fails on the first orphaned row, for example with Key (order_id)=(99) is not present in table "orders". Adding the constraint as NOT VALID is immediate, and the validation scans the table without blocking writes, unlike a plain ADD CONSTRAINT on a large table. On a large table, plan for the time the scan takes.

Also rebuild the data your triggers would have maintained for the loaded rows, such as audit and history tables, cached counts and search vectors.

Use aiven_extras on PostgreSQL 15 or for Other Roles

The aiven_extras extension provides a function that changes session_replication_role on behalf of roles that cannot SET it.

As avnadmin, install the extension in the database, once:

CREATE EXTENSION aiven_extras;

Then allow the role to use the function:

GRANT USAGE ON SCHEMA aiven_extras TO ROLE_NAME;
GRANT EXECUTE ON FUNCTION aiven_extras.session_replication_role(text) TO ROLE_NAME;

Parameters:

  • ROLE_NAME: the role that runs the load.

That role can now switch its session:

SELECT aiven_extras.session_replication_role('replica');

and back:

SELECT aiven_extras.session_replication_role('origin');

The same session rules apply as with SET.

What Replica Mode Skips

Skipped in replica mode:

  • Ordinary triggers, including BEFORE and AFTER triggers on INSERT, UPDATE and DELETE. Audit rows, denormalized counters and updated_at columns maintained by triggers are not written for the loaded rows.
  • Foreign-key checks, which PostgreSQL implements as internal triggers. A row that references a missing parent is accepted.
  • Rewrite rules, so writes against a rule-based view do not go where the rule would send them.

Still enforced in replica mode:

  • NOT NULL constraints.
  • CHECK constraints.
  • PRIMARY KEY and UNIQUE constraints, which are enforced by indexes.
  • EXCLUDE constraints.
  • Data types, including domain checks.

A trigger enabled with ALTER TABLE ... ENABLE REPLICA TRIGGER keeps firing in replica mode. Use this for a trigger that must run during the load.

Troubleshooting

SymptomCauseFix
permission denied to set parameter "session_replication_role"The service runs PostgreSQL 15, or the role is not avnadmin.Use the aiven_extras function.
The load still fails on a foreign key, or triggers still fireThe load ran on another connection than the SET, for example through a pool in transaction mode or after a reconnect.Run the SET and the load in one session, on the PostgreSQL port or a session pool.

Related Pages

Last updated on