CMD: pg
The pig pg command (alias pig postgres) manages local PostgreSQL servers and databases. It wraps local primitives such as pg_ctl, psql, and vacuumdb; use pig pt for Patroni cluster operations and pig pitr for orchestrated PITR.
Command Overview
Service Control (pg_ctl wrapper):
| Command | Alias | Description | Notes |
|---|---|---|---|
pg init |
initdb, i |
Initialize data directory | Wraps initdb |
pg start |
boot, up |
Start PostgreSQL | Wraps pg_ctl start |
pg stop |
halt, down |
Stop PostgreSQL | Wraps pg_ctl stop |
pg restart |
reboot |
Restart PostgreSQL | Wraps pg_ctl restart |
pg reload |
hup |
Reload configuration | Wraps pg_ctl reload |
pg status |
st, stat |
Show service status | Shows processes & related services |
pg promote |
pro |
Promote replica to primary | Wraps pg_ctl promote |
pg role |
r |
Detect instance role | Outputs primary/replica |
Connection & Query:
| Command | Alias | Description | Notes |
|---|---|---|---|
pg psql |
sql, connect |
Connect to database | Wraps psql |
pg ps |
activity, act |
Show current connections | Queries pg_stat_activity |
pg kill |
k |
Terminate connections | Default dry-run mode |
pg clone |
Clone a single database | CREATE DATABASE ... TEMPLATE ... FILE_COPY |
Database Maintenance:
| Command | Alias | Description | Notes |
|---|---|---|---|
pg vacuum |
vac, vc |
Vacuum tables | Wraps vacuumdb |
pg analyze |
ana, az |
Analyze tables | Wraps vacuumdb –analyze-only |
pg freeze |
Freeze vacuum | Wraps vacuumdb –freeze | |
pg repack |
rp |
Online table repacking | Requires pg_repack extension |
Parameter Tuning:
| Command | Alias | Description | Notes |
|---|---|---|---|
pg tune |
tuning |
Generate PostgreSQL tuning parameters | Auto-detects hardware and supports structured output |
Instance Fork:
| Command | Alias | Description | Notes |
|---|---|---|---|
pg fork |
Shortcut for fork init |
Creates a managed fork by default, does not start it | |
pg fork init |
create |
Create a local one-off physical copy | Default /pg/data-<name> |
pg fork list |
List managed forks | Scans /pg/data-* |
|
pg fork start |
Start an existing fork | Supports managed names or unmanaged --dst-data directories |
|
pg fork stop |
Stop an existing fork | Supports shutdown mode | |
pg fork rm |
remove, delete |
Remove a fork | Running forks require --stop |
Log Tools:
| Command | Alias | Description | Notes |
|---|---|---|---|
pg log |
l |
Log management | Parent command |
pg log list |
ls |
List log files | |
pg log tail |
t, f |
Real-time log viewing | tail -f |
pg log show |
cat, c |
Output log content | |
pg log less |
vi, v |
View with less | |
pg log grep |
g, search |
Search logs |
Service Subcommand (pg svc, also pg service or pg s):
| Command | Alias | Description |
|---|---|---|
pg svc start |
boot, up |
Start postgres service |
pg svc stop |
halt, dn, down |
Stop postgres service |
pg svc restart |
reboot, rt |
Restart postgres service |
pg svc reload |
rl, hup |
Reload postgres service |
pg svc status |
st, stat |
Show service status |
Quick Start
Global Options
These options apply to all pig pg subcommands:
| Option | Short | Default | Description |
|---|---|---|---|
--version |
-v |
auto-detect | PostgreSQL major version |
--data |
-D |
/pg/data |
Data directory path |
--dbsu |
-U |
postgres |
Database superuser (or $PIG_DBSU env) |
--systemd |
-S |
false | Use systemctl instead of pg_ctl |
Version Detection Logic:
- If
-vspecified, use that version - Otherwise read from
PG_VERSIONfile in data directory - If neither available, use default PostgreSQL in PATH
Service Control Commands
pg init
Initialize PostgreSQL data directory. Wraps initdb.
- Data checksums are enabled by default unless explicitly disabled with
-K|--no-data-checksums. - Prefer the platform-independent built-in
C.UTF-8locale on PG 17+, fall back to systemC.UTF-8/C, then system default locale. - If the data directory already exists, the command refuses to run unless
-f|--forceis used. If PostgreSQL is running on that data directory, it refuses even with--forceto prevent data loss. - Extra arguments after
--are passed toinitdb, for example--waldir=/wal. Useinitdbdirectly if you need to override locale or encoding options.
Options:
| Option | Short | Default | Description |
|---|---|---|---|
--no-data-checksums |
-K |
false | Disable data checksums |
--force |
-f |
false | Force init and remove existing data (dangerous!) |
--yes |
-y |
false | Skip overwrite confirmation when used with --force |
Safety: Even with --force, command refuses to run if PostgreSQL is running.
pg start
Start PostgreSQL server.
Options:
| Option | Short | Description |
|---|---|---|
--log |
-l |
Redirect stdout/stderr to log file |
--timeout |
-t |
Wait timeout (seconds) |
--no-wait |
Don’t wait for startup completion | |
--options |
-O |
Options to pass to postgres |
If PostgreSQL is already running, the command prints the existing postmaster PID and returns successfully.
pg stop
Stop PostgreSQL server.
Options:
| Option | Short | Default | Description |
|---|---|---|---|
--mode |
-m |
fast | Shutdown mode: smart/fast/immediate |
--timeout |
-t |
60 | Wait timeout (seconds) |
--no-wait |
false | Don’t wait for shutdown completion | |
--plan |
false | Preview local pg_ctl stop plan only |
Shutdown Modes:
| Mode | Description |
|---|---|
smart |
Wait for all clients to disconnect |
fast |
Rollback active transactions, disconnect clients, clean shutdown |
immediate |
Terminate all processes immediately, requires recovery on next start |
pg restart
Restart PostgreSQL server.
Options: Same as pg stop, plus --options (-O) to pass to postgres.
pg reload
Reload PostgreSQL configuration. Sends SIGHUP signal to server.
pg status
Show PostgreSQL server status. Displays not only pg_ctl status output, but also postgres processes and Pigsty-related service status.
Output includes:
pg_ctl statusoutput (running status, PID, etc.)- PostgreSQL process list (
ps -u postgres) - Related service status:
postgres: PostgreSQL systemd servicepatroni: Patroni HA managerpgbouncer: Connection poolerpgbackrest: Backup servicevip-manager: VIP managerhaproxy: Load balancer
pg promote
Promote replica to primary.
Options:
| Option | Short | Description |
|---|---|---|
--timeout |
-t |
Wait timeout (seconds) |
--no-wait |
Don’t wait for promotion completion | |
--plan |
Preview promotion plan only | |
--yes |
-y |
Skip confirmation prompt |
pg role
Detect PostgreSQL instance role (primary or replica).
Options:
| Option | Short | Description |
|---|---|---|
--verbose |
-V |
Show detailed detection process |
Output:
primary: Current instance is primaryreplica: Current instance is replicaunknown: Cannot determine instance role
Detection Strategy (by priority):
- Process detection: Check for
walreceiver,recoveryprocesses - SQL query: Execute
pg_is_in_recovery()(requires PostgreSQL running) - Data directory check: Check for
standby.signal,recovery.signal,recovery.conffiles
Connection & Query Commands
pg psql
Connect to PostgreSQL database via psql.
Options:
| Option | Short | Description |
|---|---|---|
--command |
-c |
Execute single SQL command |
--file |
-f |
Execute SQL script file |
pg ps
Show PostgreSQL current connections. Queries pg_stat_activity view.
Options:
| Option | Short | Description |
|---|---|---|
--all |
-a |
Show all connections (including system) |
--user |
-u |
Filter by user |
--database |
-d |
Filter by database |
pg kill
Terminate PostgreSQL connections. Default is dry-run mode, requires -x to execute.
Options:
| Option | Short | Description |
|---|---|---|
--execute |
-x |
Actually execute (default is dry-run) |
--pid |
Terminate specific PID | |
--user |
-u |
Filter by user |
--database |
-d |
Filter by database |
--state |
-s |
Filter by state (idle/active/idle in transaction) |
--query |
-q |
Filter by query pattern |
--all |
-a |
Include replication connections |
--cancel |
-c |
Cancel queries instead of terminating |
--watch |
Repeat every N seconds | |
--plan |
Preview execution plan without terminating connections |
Security: --state and --query parameters are validated to accept only simple alphanumeric patterns, preventing SQL injection.
pg clone
Clone a database inside the current PostgreSQL instance. This command wraps CREATE DATABASE ... TEMPLATE ... STRATEGY FILE_COPY, terminates existing sessions on the source database before cloning, and follows the same semantics as Pigsty’s pgsql-db clone workflow.
Options:
| Option | Short | Description |
|---|---|---|
--port |
PostgreSQL port, default 5432 or $PG_PORT |
|
--conn-db |
Database used to execute CREATE DATABASE; defaults to template1 when cloning postgres |
|
--owner |
Try to change the owner of the cloned database | |
--conn-limit |
Connection limit for the new database (-1 unlimited, 0 disallow connections) |
|
--plan |
Show execution plan only | |
--yes |
-y |
Skip confirmation prompt |
Notes: On PostgreSQL 18+ with file_copy_method=clone, database cloning can use CoW semantics; otherwise it falls back to ordinary file copy. This command clones a single database and does not create a new PostgreSQL instance.
Database Maintenance Commands
pg vacuum
Vacuum database tables. Wraps vacuumdb.
Options:
| Option | Short | Description |
|---|---|---|
--all |
-a |
Process all databases |
--schema |
-n |
Specify schema |
--table |
-t |
Specify table |
--verbose |
-V |
Verbose output |
--full |
-F |
VACUUM FULL (requires exclusive lock) |
Security: --schema and --table parameters are validated for proper PostgreSQL identifier format.
pg analyze
Analyze database tables to update statistics.
Options: Same as pg vacuum (without --full).
pg freeze
Freeze vacuum database to prevent transaction ID wraparound.
Options: Same as pg analyze.
pg repack
Online table repacking. Requires pg_repack extension.
Options:
| Option | Short | Description |
|---|---|---|
--all |
-a |
Process all databases |
--schema |
-n |
Specify schema |
--table |
-t |
Specify table |
--verbose |
-V |
Verbose output |
--jobs |
-j |
Number of parallel jobs (default 1) |
--plan |
-N |
Show tables to be repacked |
Parameter Tuning Commands
pg tune
Generate a recommended set of PostgreSQL parameters based on the current PostgreSQL major version, host hardware, and workload profile. By default, it auto-detects CPU, memory, and data disk size, then prints the result as text output.
Options:
| Option | Short | Default | Description |
|---|---|---|---|
--profile |
-p |
oltp | Tuning profile: oltp / olap / tiny / crit |
--cpu |
-c |
0 | CPU cores, 0 means auto-detect |
--mem |
-m |
0 | Total memory in MB, 0 means auto-detect |
--disk |
-d |
0 | Data disk size in GB, 0 means auto-detect |
--max-conn |
-C |
0 | Override max_connections, 0 uses profile default |
--shmem-ratio |
-R |
0.25 | Fraction of memory used for shared_buffers, range 0.1 ~ 0.4 |
Profiles:
| Profile | Best for | Characteristics |
|---|---|---|
oltp |
General transactional workloads | Balanced connection count, cache, and parallelism |
olap |
Analytical workloads | More aggressive parallelism and work memory |
tiny |
Small instances | Constrained memory footprint and parallelism |
crit |
Latency-sensitive workloads | Restricts parallel gather and favors stable response time |
Notes:
- Generated parameters are automatically gated by PostgreSQL major version. For example,
io_workersis only emitted for PG 18+. - Text output can be redirected into a config snippet, while structured output is better suited for automation.
- The command currently generates recommendations only; it does not modify PostgreSQL configuration files directly.
Instance Fork
pg fork
Create a local one-off PostgreSQL physical copy for temporary analysis, troubleshooting, recovery validation, and development testing. Managed forks are written to /pg/data-<name> by default and are not registered with Pigsty, systemd, or Patroni. When --dst-data is specified explicitly, the command creates an unmanaged fork that is not enumerated by fork list.
Create Options:
| Option | Short | Default | Description |
|---|---|---|---|
--dst-data |
/pg/data-<name> |
Unmanaged target data directory | |
--dst-port |
auto-detect | Target port, probes free ports starting at 15432 | |
--src-data |
/pg/data or $PG_DATA |
Source data directory; can also be set globally with pg -D/--data |
|
--src-port |
5432 or $PG_PORT |
Source port | |
--start |
-s |
false | Start the fork after creation |
--force |
-f |
false | Overwrite an existing stopped target directory and skip confirmation |
--timeout |
-t |
60 | Startup wait timeout in seconds |
--yes |
-y |
false | Skip confirmation prompt |
--plan |
false | Show execution plan only |
Management Commands:
| Command | Common Options | Description |
|---|---|---|
pig pg fork list |
List managed forks | |
pig pg fork start <name> or --dst-data <dir> |
--dst-data, --dst-port, -t/--timeout, --plan |
Start existing fork |
pig pg fork stop <name> or --dst-data <dir> |
--dst-data, -m/--mode, -t/--timeout, --plan |
Stop existing fork |
pig pg fork rm <name> or --dst-data <dir> |
--dst-data, --stop, -m/--mode, -t/--timeout, -f/--force, -y/--yes, --plan |
Remove fork; running forks require --stop |
Behavior Notes:
- When the source instance is running, the command uses PostgreSQL low-level backup APIs to create a consistent physical copy; when the source is stopped, it can perform a cold copy.
- The command prefers CoW/reflink. If only ordinary copy is available, interactive mode warns about disk-space risk and waits for confirmation.
- To avoid deleting source data by mistake, the target directory cannot be
/,/pg, source PGDATA, or a parent/child of source PGDATA. Symlinks are resolved before checks. - After copy, runtime and replication state is cleaned from the fork and
fork.jsonis written. The new instance starts only when-s|--startis specified. - Managed forks must be managed by name. Unmanaged forks require
--dst-datawhen starting, stopping, or removing.
List Forks:
pig pg fork list scans /pg/data-* and reads fork.json. Text status only distinguishes forked and orphan; it does not check live process state.
Structured Output:
Log Commands
Log commands view PostgreSQL log files. Default log directory is /pg/log/postgres, can be changed via --log-dir.
Log Command Global Options:
| Option | Description |
|---|---|
--log-dir |
Log directory path (default: /pg/log/postgres) |
--lines / -n |
Number of lines to show, default 50 |
--follow / -f |
Follow latest log, only on parent pg log |
Permission Handling: If current user lacks permission to read log directory, command automatically retries with sudo. -o json emits JSONL log records; log snapshots do not support yaml or json-pretty.
pg log
Show the latest log snapshot; with -f, follow the latest log.
pg log list
List log files in log directory.
pg log tail
Real-time log viewing (like tail -f). Default views latest CSV log file.
Options:
| Option | Short | Default | Description |
|---|---|---|---|
--lines |
-n |
50 | Number of lines to show |
pg log show
Output log file content.
Options:
| Option | Short | Default | Description |
|---|---|---|---|
--lines |
-n |
50 | Number of lines to show |
pg log less
Open log file with less. Defaults to end of file (+G).
pg log grep
Search log file content.
Options:
| Option | Short | Description |
|---|---|---|
--ignore-case |
Ignore case | |
--context |
-C |
Show context lines |
pg svc Subcommand
pg svc (also pg service or pg s) provides systemctl-based PostgreSQL service management:
Alias Reference:
| Command | Alias |
|---|---|
pg svc start |
boot, up |
pg svc stop |
halt, dn, down |
pg svc restart |
reboot, rt |
pg svc reload |
rl, hup |
pg svc status |
st, stat |
Design Notes
Relationship with Native Tools:
pig pg is not a simple wrapper of PostgreSQL native tools, but a higher-level abstraction for common operations:
- Service control commands (init/start/stop/restart/reload/promote) call
pg_ctl statuscommand shows process and related service status beyondpg_ctl status- Connection management commands (psql/ps/kill) call
psql clonecommand uses SQL to create a database copy- Maintenance commands (vacuum/analyze/freeze) call
vacuumdb - repack command calls
pg_repack forkcommand uses PostgreSQL low-level backup APIs and local file copy to create one-off physical copies- Log commands call system tools like
tail,less,grep
For full native tool functionality, call the respective commands directly.
Security Considerations:
--state,--query,--schema,--tableparameters are validated to prevent SQL injectionpg killdefaults to dry-run mode to prevent accidentspg cloneterminates existing sessions on the source database; use it during a maintenance windowpg forkrejects dangerous target paths; ordinary-copy fallback warns about disk-space risk- Log commands auto-retry with sudo when permissions insufficient
Platform Support:
This command is designed for Linux systems. Some features depend on systemctl, and log commands depend on readable PostgreSQL log files plus common tools such as tail, less, and grep.