How to Use the pgSchema Tool in PostgreSQL

Managing PostgreSQL schema changes manually becomes difficult as a database grows. Comparing database objects, finding differences, and applying only the necessary changes often takes a lot of work and raises the risk of mistakes. A schema migration tool helps by creating a migration plan that is based on the database state and the target schema definition.

In this article, we will explore the pgschema tool, an open-source utility for PostgreSQL schema management. We will explore how to build a pgschema from source, review its commands, export an existing PostgreSQL database schema, create migration plans in formats, and apply those changes to a different PostgreSQL database. By the time you finish, you will have a workflow for moving PostgreSQL schemas with pgschema.

Clone the repository.

git clone https://github.com/pgplex/pgschema.git

Go to the folder named pgschema.

cd pgschema

Check the contents inside this folder

ls

Result :

AGENTS.md  CLAUDE.md  cmd  CODEOWNERS  default.nix  Dockerfile  docs  flake.lock  flake.nix  go.mod  go.sum  internal  ir  LICENSE  main.go  nix  README.md  testdata  testutil

Now, build this using go like this.

go build

After the build, we can see a binary file named pgschema.

ls

Result:

AGENTS.md  CLAUDE.md  cmd  CODEOWNERS  default.nix  Dockerfile  docs  flake.lock  flake.nix  go.mod  go.sum  internal  ir  LICENSE  main.go  nix  pgschema  README.md  testdata  testutil

Check the version of this pgschema like this.

cybrosys@cybrosys:~/pgschema$ ./pgschema -v

Result:

1.14.0

We can use the help command to see all the available options we can use with the pgschema command like this.

cybrosys@cybrosys:~/pgschema$ ./pgschema --help

Result:

Declarative schema migration for Postgres
Version: 1.12.0@unknown linux/amd64 unknown
Commands:
  dump    Dump PostgreSQL schema
  plan    Generate migration plan
  apply   Apply schema migrations
Use "pgschema [command] --help" for more information about a command.
Usage:
  pgschema [command]
Available Commands:
  apply       Apply migration plan to update a database schema
  dump        Dump database schema for a specific schema
  help        Help about any command
  plan        Generate migration plan for a specific schema
Flags:
      --debug   Enable debug logging
  -h, --help    help for pgschema
Use "pgschema [command] --help" for more information about a command.

Use the dump command with the help flag to see the available options we can use.

cybrosys@cybrosys:~/pgschema$ ./pgschema dump --help

Result:

Dump and output database schema information for a specific schema. Uses the --schema flag to target a particular schema (defaults to 'public').
Usage:
  pgschema dump [flags]
Flags:
      --db string         Database name (required) (env: PGDATABASE)
      --file string       Output file path (required when --multi-file is used)
  -h, --help              help for dump
      --host string       Database server host (env: PGHOST) (default "localhost")
      --multi-file        Output schema to multiple files organized by object type
      --no-comments       Do not output object comment headers
      --password string   Database password (optional, can also use PGPASSWORD env var)
      --port int          Database server port (env: PGPORT) (default 5432)
      --qualify-schema    Always schema-qualify object identifiers in the dump, even for the target schema (does not affect same-schema type references, which the IR stores without a schema)
      --schema string     Schema name to dump (default: public) (default "public")
      --sslmode string    SSL mode for database connection (disable, allow, prefer, require, verify-ca, verify-full) (env: PGSSLMODE) (default "prefer")
      --user string       Database user name (required) (env: PGUSER)
Global Flags:
      --debug   Enable debug logging

Use the plan command with the help flag to see the available options we can use.

cybrosys@cybrosys:~/pgschema$ ./pgschema plan --help

Result:

Generate a migration plan to apply a desired schema state to a target database schema. Compares the desired state (from --file) with the current state of a specific schema (specified by --schema, defaults to 'public').
Usage:
  pgschema plan [flags]
Flags:
      --db string              Database name (required) (env: PGDATABASE)
      --file string            Path to desired state SQL schema file (required)
  -h, --help                   help for plan
      --host string            Database server host (env: PGHOST) (default "localhost")
      --no-color               Disable colored output
      --output-human string    Output human-readable format to stdout or file path
      --output-json string     Output JSON format to stdout or file path
      --output-sql string      Output SQL format to stdout or file path
      --password string        Database password (optional, can also use PGPASSWORD env var)
      --plan-db string         Plan database name (env: PGSCHEMA_PLAN_DB)
      --plan-host string       Plan database host (env: PGSCHEMA_PLAN_HOST). If provided, uses external database instead of embedded postgres
      --plan-password string   Plan database password (env: PGSCHEMA_PLAN_PASSWORD)
      --plan-port int          Plan database port (env: PGSCHEMA_PLAN_PORT) (default 5432)
      --plan-sslmode string    Plan database SSL mode (env: PGSCHEMA_PLAN_SSLMODE) (default "prefer")
      --plan-user string       Plan database user (env: PGSCHEMA_PLAN_USER)
      --port int               Database server port (env: PGPORT) (default 5432)
      --schema string          Schema name (default "public")
      --sslmode string         SSL mode for database connection (disable, allow, prefer, require, verify-ca, verify-full) (env: PGSSLMODE) (default "prefer")
      --user string            Database user name (required) (env: PGUSER)
Global Flags:
      --debug   Enable debug logging

Use the apply command with the help flag to see the available options we can use.

cybrosys@cybrosys:~/pgschema$ ./pgschema apply --help

Result:

Apply a migration plan to update a database schema. Either provide a desired state file (--file) to generate and apply a plan, or provide a pre-generated plan file (--plan) to execute directly.
Usage:
  pgschema apply [flags]
Flags:
      --application-name string   Application name for database connection (visible in pg_stat_activity) (env: PGAPPNAME) (default "pgschema")
      --auto-approve              Apply changes without prompting for approval
      --db string                 Database name (required) (env: PGDATABASE)
      --file string               Path to desired state SQL schema file
  -h, --help                      help for apply
      --host string               Database server host (env: PGHOST) (default "localhost")
      --lock-timeout string       Maximum time to wait for database locks (e.g., 30s, 5m, 1h)
      --no-color                  Disable colored output
      --password string           Database password (optional, can also use PGPASSWORD env var)
      --plan string               Path to plan JSON file
      --plan-db string            Plan database name (env: PGSCHEMA_PLAN_DB)
      --plan-host string          Plan database host (env: PGSCHEMA_PLAN_HOST). If provided, uses external database instead of embedded postgres for validating desired state schema
      --plan-password string      Plan database password (env: PGSCHEMA_PLAN_PASSWORD)
      --plan-port int             Plan database port (env: PGSCHEMA_PLAN_PORT) (default 5432)
      --plan-sslmode string       Plan database SSL mode (env: PGSCHEMA_PLAN_SSLMODE) (default "prefer")
      --plan-user string          Plan database user (env: PGSCHEMA_PLAN_USER)
      --port int                  Database server port (env: PGPORT) (default 5432)
      --schema string             Schema name (default "public")
      --sslmode string            SSL mode for database connection (disable, allow, prefer, require, verify-ca, verify-full) (env: PGSSLMODE) (default "prefer")
      --user string               Database user name (required) (env: PGUSER)
Global Flags:
      --debug   Enable debug logging

Now, let’s use the pgschema tool.

Check the clusters.

cybrosys@cybrosys:~$ pg_lsclusters 

Result:

Ver Cluster Port Status Owner    Data directory               Log file
18  main    5432 online postgres /var/lib/postgresql/18/main  /var/log/postgresql/postgresql-18-main.log
18  main2   5435 online postgres /var/lib/postgresql/18/main2 /var/log/postgresql/postgresql-18-main2.log

We already have an odoo_17 database on port 5432.

Create a database named odoo_17 on port 5435.

create database odoo_17;

Create a folder to store the current backup and also a space for storing the migration plan.

mkdir -p ~/schemas/odoo_17_to_5435

Go to that folder.

cd ~/schemas/odoo_17_to_5435

Now, we have to use the binary file named pgschema to take a backup.

~/pgschema/pgschema dump --host /var/run/postgresql --port 5432 --user cybrosys --db odoo_17 > odoo_17.sql

  • --host = Here, we specify the host as unix socket directory
  • --port = Specifies the postgres running port.
  • --user = Specifies the user name
  • --db odoo_17 = Specifies the name of the database we are going to take backup of in.sql format

Now, check the contents inside the folder, and you can see the file named odoo_17.sql

cybrosys@cybrosys:~/schemas/odoo_17_to_5435$ ls

Result:

Odoo_17.sql

Check the size of the .sql file to ensure that the backup was executed correctly

cybrosys@cybrosys:~/schemas/odoo_17_to_5435$ ls -lh odoo_17.sql 

Result:

-rw-rw-r-- 1 cybrosys cybrosys 1.2M Nov  7 13:58 odoo_17.sql

Now, create the migration plan using the pgschema with the dump command.

~/pgschema/pgschema plan --host localhost --port 5435 --user postgres --db odoo_17 \
  --file odoo_17.sql --output-human plan.txt --output-json plan.json --output-sql plan.sql

Here, we create the migration plan in three formats.

  • plan.txt
  • plan.json
  • plan.sql

Now, check the size of these files to ensure that everything is good.

cybrosys@cybrosys:~/schemas/odoo_17_to_5435$ ls -lh

Result:

total 5.7M
-rw-rw-r-- 1 cybrosys cybrosys 1.2M Nov  7 13:58 odoo_17.sql
-rw-r--r-- 1 cybrosys cybrosys 2.3M Nov  7 13:59 plan.json
-rw-r--r-- 1 cybrosys cybrosys 987K Nov  7 13:59 plan.sql
-rw-r--r-- 1 cybrosys cybrosys 1.3M Nov  7 13:59 plan.txt

Now, open the plan.json file.

How to Use the pgSchema Tool in PostgreSQL-cybrosys

Here, we can see the complete metadata of the migration plan in json format.

Now, open the plan.sql file.

How to Use the pgSchema Tool in PostgreSQL-cybrosys

Open the plan.txt file also.

How to Use the pgSchema Tool in PostgreSQL-cybrosys

Check the size of the newly created database on port 5435 and ensure that it is empty.

odoo_17=# \l+

Result:

                                                                                  List of databases
   Name    |  Owner   | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules |   Access privileges   |  Size   | Tablespace |                Description                 
-----------+----------+----------+-----------------+---------+-------+--------+-----------+-----------------------+---------+------------+--------------------------------------------
 odoo_17   | postgres | UTF8     | libc            | en_IN   | en_IN |        |           |                       | 7790 kB | pg_default | 
 postgres  | postgres | UTF8     | libc            | en_IN   | en_IN |        |           |                       | 7670 kB | pg_default | default administrative connection database
 template0 | postgres | UTF8     | libc            | en_IN   | en_IN |        |           | =c/postgres          +| 7513 kB | pg_default | unmodifiable empty database
           |          |          |                 |         |       |        |           | postgres=CTc/postgres |         |            | 
 template1 | postgres | UTF8     | libc            | en_IN   | en_IN |        |           | =c/postgres          +| 7742 kB | pg_default | default template for new databases
           |          |          |                 |         |       |        |           | postgres=CTc/postgres |         |            | 
(4 rows)

Now, apply the migration plan to the postgres on port 5435

~/pgschema/pgschema apply --host localhost --port 5435 --user postgres --db odoo_17 \
  --plan plan.json --auto-approve

Here, we use the plan that is in json format for the execution of the migration plan.

Now, check the size of the odoo_17 database on port 5435.

odoo_17=# \l+

Result:

                                                                                  List of databases
   Name    |  Owner   | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules |   Access privileges   |  Size   | Tablespace |                Description                 
-----------+----------+----------+-----------------+---------+-------+--------+-----------+-----------------------+---------+------------+--------------------------------------------
 odoo_17   | postgres | UTF8     | libc            | en_IN   | en_IN |        |           |                       | 37 MB   | pg_default | 
 postgres  | postgres | UTF8     | libc            | en_IN   | en_IN |        |           |                       | 7670 kB | pg_default | default administrative connection database
 template0 | postgres | UTF8     | libc            | en_IN   | en_IN |        |           | =c/postgres          +| 7513 kB | pg_default | unmodifiable empty database
           |          |          |                 |         |       |        |           | postgres=CTc/postgres |         |            | 
 template1 | postgres | UTF8     | libc            | en_IN   | en_IN |        |           | =c/postgres          +| 7742 kB | pg_default | default template for new databases
           |          |          |                 |         |       |        |           | postgres=CTc/postgres |         |            | 
(4 rows)

Now, the migration is successfully completed, and we can see the size of the odoo database.

The pgschema tool provides a structured approach to managing postgresql schema changes. Instead of manually comparing database objects and writing migration scripts, it allows you to export an existing schema, generate a detailed migration plan, review the proposed changes, and apply them to a target database. The availability of migration plans in human-readable, SQL, and JSON formats also makes the process easier to validate before execution.

This article demonstrated how to use pgschema from start to finish, covering installation, schema export, migration plan generation, and execution against a target PostgreSQL database. With these steps, you can review schema changes before applying them and keep database structures consistent across multiple environments.

WhatsApp