Database definition: export and load

A .pgdef file is a deterministic export of a database's schema definition (no data). Loading it against a database diffs it with that database's catalogs and generates the DDL script that brings the database to the file.

What it is good for

Schema migration between environments, cloning a schema into an empty database, keeping the schema in version control (stable order, clean diffs), and comparing two states. For data, use pg_dump or export a result.

Exporting a definition

With the tree cursor on a database row: File → Export database definition… (also in the F2 menu); name a .pgdef file.

The .pgdef file

Pretty-printed JSON:

{
  "format": 1,
  "schemas": [
    {
      "name": "sales",
      "tables": [
        {
          "name": "customer",
          "columns": [
            {
              "name": "customerid",
              "type": "integer",
              "not_null": true
            },
            {
              "name": "createdby",
              "type": "text",
              "not_null": true,
              "default": "CURRENT_USER"
            }
          ],
          "constraints": [
            {
              "name": "PK_Customer_CustomerID",
              "kind": "primary_key",
              "definition": "PRIMARY KEY (customerid)"
            }
          ]
        }
      ]
    }
  ]
}

What is in the file — and what is not

IncludedDetails
ExtensionsName and schema; member objects are not listed.
Schemas
TypesEnum, composite, domain, range.
SequencesAll parameters and OWNED BY.
TablesColumns (type, NOT NULL, default, identity with its sequence options, generated); constraints; indexes that do not back a constraint; triggers; rules; policies; partition key and partitions with bounds; INHERITS parents; storage parameters.
Views, materialized viewsQuery, options; indexes of materialized views.
Functions, proceduresIdentity arguments, argument types, number of defaults, result type, pg_get_functiondef() text.
CommentsOn all of the above.
Owners and privilegesOwner and ACL (from aclexplode(); a NULL ACL as acldefault()) of every schema, type, sequence, table, view, materialized view and function; column privileges; CONNECT / TEMPORARY / CREATE on the database; pg_default_acl. The owner's own privileges are not listed.
RolesOnly those the database needs: owners, grantees, policy and default-privilege roles, and the roles they are members of. LOGIN, INHERIT, CREATEDB, CREATEROLE, REPLICATION, BYPASSRLS, SUPERUSER, connection limit, VALID UNTIL, memberships, comment — from pg_roles; never a password. No pg_* roles.
Not includedConsequence
TablespacesCluster-wide.
Foreign data wrappers and foreign tables, publications, subscriptions, event triggers, casts, operators, aggregates, collations, full-text search objectsNot covered yet; create them by hand.

Loading a definition

With the tree cursor on the target database: File → Load database definition… (also in the F2 menu); pick the file. pgtc reads the target's catalogs as an export does, diffs the two models and opens the script in a new query tab on the target. Nothing is executed by the load. An empty diff opens no tab (The schema of adventureworks already matches the definition file.).

A sync script in a query tab
A sync script: two columns, a table with index and foreign key, a changed view.

Reading the script

-- Sync script generated by pgtc: brings this database to the structure of the
-- definition file. Objects that exist only in the database are kept.
-- Review it before running.

DROP VIEW sales.vcustomeroverview;

ALTER TABLE sales.customer ADD COLUMN note text;
ALTER TABLE sales.customer ADD COLUMN createdby text NOT NULL DEFAULT CURRENT_USER;

CREATE TABLE sales.customernote (
    customernoteid bigint GENERATED ALWAYS AS IDENTITY NOT NULL,
    customerid integer NOT NULL,
    note text NOT NULL,
    CONSTRAINT customernote_pkey PRIMARY KEY (customernoteid)
);

CREATE VIEW sales.vcustomeroverview AS
SELECT c.customerid, c.territoryid, count(n.*) AS notes FROM sales.customer c LEFT JOIN ...;

CREATE INDEX ix_customernote_customerid ON sales.customernote USING btree (customerid);

ALTER TABLE sales.customernote ADD CONSTRAINT customernote_customerid_fkey
    FOREIGN KEY (customerid) REFERENCES sales.customer(customerid);

Roles, owners and privileges

The script starts with the roles and ends with owners and privileges, each section under its own heading:

SituationWhat the script does
A role of the file is not in the target's clusterCREATE ROLE with its attributes, then the missing memberships (GRANT role TO role). A LOGIN role gets no password: a -- NOTE: says to set one. SUPERUSER is never written; a note says so.
The role exists with other attributesLeft as it is (roles are cluster-wide); a -- NOTE: names the attributes.
An object's owner differsALTER … OWNER TO. A sequence owned by a column follows its table. An object the script creates counts as owned by the role that read the target, so a clone run by that role needs no owner statements.
A privilege of the file is missingGRANT (columns: GRANT p (col)); default privileges: ALTER DEFAULT PRIVILEGES FOR ROLE … GRANT; the database's own: a DO block with current_database().
A privilege exists only in the targetNever revoked: a -- NOTE: for each, to REVOKE by hand if it is not wanted.

Run the script as a superuser, or as a role with CREATEROLE that is a member of each new owner role (PostgreSQL 16+: ALTER … OWNER TO needs that); otherwise the server stops it with its error.

The rules of a load

A load creates and alters. It never drops an object that exists only in the database.

SituationWhat the script does
Object only in the fileCREATE.
Object only in the databaseNothing.
A column is missing; its type, default or NOT NULL differsADD COLUMN / ALTER COLUMN … TYPE … USING column::type (a default is dropped before and set after), SET / DROP DEFAULT, SET / DROP NOT NULL.
A property of an existing object is absent in the file (a default, a comment)Removed: DROP DEFAULT, COMMENT ON … IS NULL. Properties follow the file; only whole objects and parts are kept.
An enum lacks labels; a composite type lacks or has different attributesALTER TYPE … ADD VALUE IF NOT EXISTS, at the start of the script — a label cannot be used in the transaction that adds it: when the script fails with unsafe use of new value, run these statements on their own first; ADD ATTRIBUTE / ALTER ATTRIBUTE … TYPE.
A view or materialized view differsDROP and CREATE — together with every view that depends on it, also one that exists only in the database (created again as it is there, with its indexes, triggers and rules). Their owners and privileges come from the file.
A function differsCREATE OR REPLACE; DROP and CREATE when the result type, a parameter's name or mode differs or a default is gone. The views that use it are replaced with it; table parts that use it (default, generated column, constraint, index, trigger, rule, policy) are dropped before and created again after — the tables and rows stay. Functions are matched by name and argument types.
A table inherits (INHERITS)Created with INHERITS; an existing table gets ALTER TABLE … INHERIT.
An identity column's sequence options differ; a column becomes an identityALTER COLUMN … SET …; ADD GENERATED … AS IDENTITY and a setval after the rows that are there.
A constraint, index, trigger, rule or policy differsDROP and CREATE.
A generated column's expression differsDROP COLUMN and ADD COLUMN.
A column is ordinary on one side, generated on the otherA -- NOTE:; no statement (replacing it would drop its values).
A table's partition key differsThe table is re-created, keeping the rows — see below.
No ALTER can apply the difference (a domain's base type)A -- NOTE: comment only.

Re-created tables

Only when the partition key differs. The script:

  1. copies the table with its rows into _TableCopy_<name> in the same schema;
  2. drops the table (partitions go with it) and creates it and its partitions as in the file, plus the columns and parts that exist only in the database;
  3. loads the rows back with INSERT … OVERRIDING SYSTEM VALUE, advances identity sequences with setval() and restores OWNED BY;
  4. ends with a commented-out -- DROP TABLE sales."_TableCopy_orders"; per copy. The script never drops the copies.

What a load cannot know

Running the script

It is sent as one request and runs as one transaction (see Scripts): a failing statement rolls everything back. To inspect before committing, turn off Query → Auto commit first.

Example: from development to test

  1. On the development server's adventureworks: File → Export database definition….
  2. On the test server's adventureworks: File → Load database definition…, pick the file.
  3. Review the script, F5. Objects that exist only in test are kept.