0% found this document useful (0 votes)
42 views

Postgress-Config Files and Commands

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Postgress-Config Files and Commands

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CONTENTS

Configuration Files ......................................................................................................................................................... 2


1. postgresql.conf ....................................................................................................................................................... 2
Important configuration: ....................................................................................................................................... 2
2. pg_hba.conf (Host-Based Authentication File) ...................................................................................................... 7
Important configuration: ....................................................................................................................................... 7
3. pg_ident.conf (User Identity Mapping).................................................................................................................. 7
Important configuration: ....................................................................................................................................... 8
Commands List ............................................................................................................................................................... 8
General command in psql: ......................................................................................................................................... 8
Help command in PSQL .............................................................................................................................................. 9
Query Buffer Commands............................................................................................................................................ 9
Input/Output commands ........................................................................................................................................... 9
Conditional Commands: ........................................................................................................................................... 10
Informational commands ......................................................................................................................................... 10
Large Objects Commands ........................................................................................................................................ 13
Formatting Commands ............................................................................................................................................ 13
Connections Commands .......................................................................................................................................... 14
operating system Commands .................................................................................................................................. 14
Variable commands.................................................................................................................................................. 15
CONFIGURATION FILES

1. POSTGRESQL.CONF

Purpose: The main configuration file for PostgreSQL, controlling server behavior and database settings.

Location: By default, located in the PostgreSQL data directory, typically specified during installation.

Contents:

General parameters for database operations, including memory management, logging, query optimization, and
replication settings.

Configurable categories include File Locations, Resource Usage, Query Tuning, Write-Ahead Logging (WAL),
Replication, Autovacuum, Client Connection Defaults, and more.

Description from file:

• This file is read on server startup and when the server receives a SIGHUP signal.
• If you edit the file on a running system, you have to SIGHUP the server for the changes to take effect, run
"pg_ctl reload –D path/to/data directory", or execute "SELECT pg_reload_conf()".
• Some parameters, which are marked below, require a server shutdown and restart to take effect.
• Any parameter can also be given as a command-line option to the server, e.g., "postgres -c
log_connections=on".
• Some parameters can be changed at run time with the "SET" SQL command.

Key Usage: The settings here influence the overall performance and functionality of the database. Adjustments can
be made to optimize resource usage, configure connections, manage authentication, and tune queries.

IMPORTANT CONFIGURATION:
1. File Locations:

Parameters that define the storage locations for PostgreSQL’s data, logs, and other key files.

Parameter Default Value Description


data_directory Environment set Path to the PostgreSQL data directory.
hba_file pg_hba.conf Path to the host-based authentication (HBA) file.
ident_file pg_ident.conf Path to the file mapping OS usernames to database usernames.
external_pid_file None Path to store the server’s process ID file for easier management.
2. Connections and Authentication

Configures client connections, authentication methods, and connection limits.

Parameter Default Value Description


listen_addresses Localhost or “*” IP addresses that PostgreSQL listens to for connections.
port 5432 Port number PostgreSQL listens on.
max_connections 100 Maximum concurrent connections.
authentication_timeout 1min Timeout for client authentication.
ssl off Enables SSL connections for secure communication.
password_encryption scram-sha-256 Specifies method for storing encrypted passwords.

3. Resource Usage (except WAL)

Defines how memory, CPU, and disk resources are allocated for optimal performance.

Parameter Default Value Description


shared_buffers 128MB Amount of memory used for shared data across connections.
work_mem 4MB Memory allocated per query operation, like sorting.
maintenance_work_mem 64MB Memory used for maintenance operations (e.g., VACUUM, indexing).
effective_cache_size 4GB Estimate of available OS cache memory for the planner.
temp_buffers 8MB Memory allocated for temporary tables for each session.
max_files_per_process 1000 Maximum open files per process; helps manage resource limits on
the OS level.

4. Write-Ahead Log (WAL)

Parameters that manage PostgreSQL’s WAL for data durability and crash recovery.

Parameter Default Value Description


wal_level replica Sets level of information in WAL for backup and replication.
wal_buffers -1 (auto- Memory for WAL records; tuning improves write-heavy workload
tuned) performance.
checkpoint_timeout 5min Time between automatic checkpoints.
max_wal_size 1GB Maximum total size of WAL files before a checkpoint is forced.
min_wal_size 80MB Minimum size of WAL files retained.
5. Replication

Manages replication settings to create high availability and standby environments.

Parameter Default Value Description


max_wal_senders 10 Maximum number of replication sender processes.
synchronous_commit on Forces transactions to wait for WAL write confirmation.
hot_standby off Enables read-only queries on standby servers.
max_standby_streaming_delay 30s Delay tolerance for read queries on standby.
synchronous_standby_names '' Defines standby servers that must acknowledge receipt of
WAL.

6. Query Tuning

Parameters that guide the query planner and executor to optimize performance.

Parameter Default Value Description


effective_cache_size 4GB Guides query planner on available memory; larger values can improve
performance.
random_page_cost 4.0 Cost factor for non-sequential page access in disk storage.
seq_page_cost 1.0 Cost factor for sequential disk scans.
cpu_tuple_cost 0.01 Cost of processing a row in a query.
join_collapse_limit 8 Limits number of tables planner joins together automatically.

7. Reporting and Logging

Configures logging to monitor and troubleshoot PostgreSQL operations.

Parameter Default Value Description


log_destination stderr Destination for log output (stderr, csvlog, syslog).
logging_collector off Enables log file generation.
log_directory pg_log Directory for log storage.
log_filename postgresql-%Y-%m- Filename format for log files.
%d_%H%M%S.log
log_min_duration_statement -1 (disabled) Logs SQL statements exceeding the set time in ms.
log_statement none Logs each SQL statement type (none, ddl, mod, all).
8. Statistics

Tracks query and usage statistics, crucial for performance tuning.

Parameter Default Value Description


track_activities on Enables tracking of active sessions.
track_counts on Collects database statistics for performance analysis.
track_io_timing off Enables IO timing statistics, useful for tuning queries.
stats_temp_directory pg_stat_tmp Directory for temporary statistics files.

9. Autovacuum

Automates database maintenance tasks like table vacuuming and analyzing.

Parameter Default Value Description


autovacuum on Enables autovacuum feature.
autovacuum_max_workers 3 Maximum number of autovacuum processes.
autovacuum_naptime 1min Delay between autovacuum cycles.
autovacuum_vacuum_scale_factor 0.2 Fraction of table size to trigger autovacuum.
autovacuum_analyze_scale_factor 0.1 Fraction of table size to trigger auto-analyze.

10. Client Connection Defaults

Sets default configurations for client connections, including timeouts and locales.

Parameter Default Value Description


application_name '' Name of the client application, visible in
pg_stat_activity.
search_path "$user", public Schema search path.
statement_timeout 0 (disabled) Time limit for executing a query.
idle_in_transaction_session_timeout 0 Terminates idle transactions after specified time.
client_encoding SQL_ASCII Sets default client encoding.
11. Lock Management

Manages table and row-level locking behavior to control concurrency.

Parameter Default Value Description


deadlock_timeout 1s Timeout to detect deadlocks.

max_locks_per_transaction 64 Maximum locks per transaction.

lock_timeout 0 (disabled) Sets max wait time for acquiring a lock.

12. Version and Platform Compatibility

Ensures compatibility with previous PostgreSQL versions and different platforms.

Parameter Default Value Description


default_transaction_isolation read Sets default transaction isolation level.
committed
timezone UTC Sets the server’s time zone.
integer_datetimes on Controls use of integer or floating-point storage for
timestamps.

13. Error Handling

Defines handling and logging of errors within the database.

Parameter Default Value Description


log_error_verbosity default Sets detail level for error messages (terse, default, verbose).
client_min_messages notice Minimum message level sent to the client.
log_min_messages warning Minimum message level logged.

14. Config File Includes and Customized Options

Extends configuration using additional files or custom-defined parameters.

Parameter Default Value Description


include '' Path to an additional configuration file for modular configs.
include_dir '' Directory containing additional config files.
custom_variable_classes '' Allows defining custom parameter namespaces.
2. PG_HBA.CONF (HOST -BASED AUTHENTICATION FILE)

Purpose: Controls client authentication by defining who can connect to PostgreSQL, from which hosts, and what
authentication methods are required.

Location: Also found in the PostgreSQL data directory.

Contents:

Contains rules for host-based authentication, using parameters like type (local, host, hostssl), database, user,
address, and method.

Configures access control for both local and remote connections, specifying whether users must authenticate using
methods like password, SCRAM-SHA-256, or trust.

IMPORTANT CONFIGURATION:
1. Authentication Records

This file controls: which hosts are allowed to connect, how clients are authenticated, which PostgreSQL user names
they can use, which databases they can access.

Type Database User Address Method Description


local all all - trust Allow all local connections without a
password.
host mydb specific_user 192.168.1.0/24 md5 Require password for specific_user
connecting to mydb over TCP/IP.
host all admin_user 192.168.2.0/24 scram-sha- Require SCRAM-SHA-256 authentication
256 for admin_user from this subnet.
hostssl all all 203.0.113.0/24 md5 Require md5 authentication for all users
over SSL from specified IP.

2. Include Records

This file allows the inclusion of external files or directories holding more records

Directive Value Description


include 'pg_hba_custom.conf' Includes additional configuration from the specified file.
include_dir 'pg_hba.d' Includes all configuration files from the specified directory.

Key Usage: This file is crucial for database security, allowing administrators to control access by restricting IP
addresses and enforcing authentication methods.

3. PG_IDENT.CONF (USER IDENTITY MAPPING)


Purpose: Maps operating system user names to PostgreSQL database roles, allowing user authentication based on
identity mappings.

Location: Typically located alongside the pg_hba.conf and postgresql.conf files.

Contents:

Contains mappings with columns specifying map name, system user, and PostgreSQL user.

Enables PostgreSQL users to log in as different roles without needing a matching operating system username.

IMPORTANT CONFIGURATION:
Key Usage: Useful in environments where OS user names differ from PostgreSQL roles, or where different systems
need access to the database without direct role naming requirements.

COMMANDS LIST

GENERAL COMMAND IN PSQL:


Command Description Example
\bind Set query parameters. \bind date='2024-10-25'
[PARAM]...
\copyright Show PostgreSQL usage and \copyright
distribution terms.
\crosstabview Execute query and display SELECT department, gender,
[COLUMNS] COUNT(*) FROM employees GROUP BY
result in crosstab format. 1, 2; \crosstabview department
gender
\errverbose Show most recent error \errverbose
message with maximum
verbosity.
\g [(OPTIONS)] Execute query, optionally SELECT * FROM customers; \g
[FILE] output.txt
sending result to file or pipe;
\g alone is equivalent to a
semicolon.
\gdesc Describe result of query SELECT * FROM employees; \gdesc
without executing it.
\gexec Execute query, then execute `SELECT 'SELECT * FROM '
each value in its result.
\gset [PREFIX] Execute query and store result SELECT COUNT(*) AS total FROM
in psql variables. employees; \gset my_ (retrieves
result as :my_total)
\gx [(OPTIONS)] As \g, but forces expanded SELECT * FROM orders; \gx
[FILE]
output mode.
\q Quit psql. \q
\watch Execute query every SEC SELECT COUNT(*) FROM orders;
[[i=]SEC] [c=N] \watch 5
seconds, up to N times.
HELP COMMAND IN PSQL
Command Description Example
\? Show help on backslash commands. \? (lists all backslash commands)
[commands]
\? options Show help on psql command-line \? options
options.
\? Show help on special variables \? variables
variables
available in psql.
\h [NAME] Show help on syntax of SQL \h SELECT (shows syntax for SELECT)
commands, or * for all commands. or \h * (lists all SQL commands)

QUERY BUFFER COMMANDS


Command Description Example
\e [FILE] Edit the query buffer or a specified \e myquery.sql (opens
[LINE]
file in the external editor. myquery.sql in editor)
\ef [FUNCNAME Edit the definition of a function in \ef my_function (opens
[LINE]]
the external editor. my_function in editor)
\ev [VIEWNAME Edit the definition of a view in the \ev my_view (opens my_view in
[LINE]]
external editor. editor)
\p Display the contents of the current \p (shows query buffer content)
query buffer.
\r Clear the current query buffer. \r (empties query buffer)
\w FILE Write the contents of the query \w output.sql (saves buffer
buffer to a specified file. content to output.sql)
INPUT/OUTPUT COMMANDS
Command Description Example
\copy ... Perform SQL COPY operation with a \copy my_table TO
'output.csv' CSV HEADER;
data stream to or from the client host.
\echo [-n] Write a string to standard output; use \echo -n "Hello, PostgreSQL!"
[STRING]
-n to suppress the newline.
\i FILE Execute commands from a specified \i script.sql
file.
\ir FILE Similar to \i, but relative to the \ir ../another_script.sql
current script’s location.
\o [FILE] Redirect all query results to a \o results.txt
specified file or pipe.
\qecho [-n] Write a string to the output stream \qecho -n "Saving output to
[STRING] file..."
defined by \o; -n suppresses the
newline.
\warn [-n] Write a string to standard error; -n \warn "This is a warning!"
[STRING]
suppresses the newline.
CONDITIONAL COMMANDS:
Command Description Example
\if EXPR Starts a conditional block, executing \if :my_var > 10
commands if the expression is true. Execute block if my_var is
greater than 10.
\elif Provides an alternative condition within the \elif :my_var == 5
EXPR Execute block if my_var equals
conditional block if the initial \if was false.
5.
\else Specifies the final alternative in the \else
conditional block if none of the previous This block executes if none of
conditions match. the above conditions were true.
\endif Ends the conditional block. \endif
Marks the end of the
conditional structure.

INFORMATIONAL COMMANDS
Command Description Example
\d[S+] Lists tables, views, and \d+
sequences. Displays all tables, views,
and sequences with extra
detail.
\d[S+] NAME Describes a specific table, view, \d+ employees
sequence, or index. Shows detailed information
about the employees table.
\da[S] [PATTERN] Lists aggregate functions. \da+
Lists all aggregates with
extra detail.
\dA[+] [PATTERN] Lists access methods. \dA
Displays available access
methods.
\dAc[+] [AMPTRN Lists operator classes. \dAc+
[TYPEPTRN]] Lists operator classes with
additional details.
\dAf[+] [AMPTRN Lists operator families. \dAf
[TYPEPTRN]] Lists all operator families.
\dAo[+] [AMPTRN Lists operators of operator \dAo
[OPFPTRN]] Shows operators in operator
families.
families.
\dAp[+] [AMPTRN Lists support functions of \dAp
[OPFPTRN]] Displays support functions
operator families.
of operator families.
\db[+] [PATTERN] Lists tablespaces. \db+
Shows tablespaces with
additional details.
\dc[S+] [PATTERN] Lists conversions. \dc
Displays conversions.
\dconfig[+] [PATTERN] Lists configuration parameters. \dconfig+
Displays configuration
parameters with details.
\dC[+] [PATTERN] Lists casts. \dC
Shows all available casts.
\dd[S] [PATTERN] Shows object descriptions not \dd
displayed elsewhere. Lists object descriptions.
\dD[S+] [PATTERN] Lists domains. \dD+
Lists domains with
additional information.
\ddp [PATTERN] Lists default privileges. \ddp
Shows default privileges.
\dE[S+] [PATTERN] Lists foreign tables. \dE
Displays foreign tables.
\des[+] [PATTERN] Lists foreign servers. \des+
Displays foreign servers
with details.
\det[+] [PATTERN] Lists foreign tables. \det
Shows foreign tables.
\deu[+] [PATTERN] Lists user mappings. \deu+
Displays user mappings with
additional details.
\dew[+] [PATTERN] Lists foreign-data wrappers. \dew
Lists foreign-data wrappers.
\df[anptw][S+] Lists functions filtered by type: \df+
[FUNCPTRN [TYPEPTRN Lists functions with detailed
...]]
aggregate, normal, procedure,
trigger, or window. descriptions.
\dF[+] [PATTERN] Lists text search configurations. \dF
Displays text search
configurations.
\dFd[+] [PATTERN] Lists text search dictionaries. \dFd
Lists available text search
dictionaries.
\dFp[+] [PATTERN] Lists text search parsers. \dFp
Displays text search parsers.
\dFt[+] [PATTERN] Lists text search templates. \dFt
Shows text search templates.
\dg[S+] [PATTERN] Lists roles. \dg
Lists all roles.
\di[S+] [PATTERN] Lists indexes. \di+
Shows all indexes with
details.
\dl[+] Lists large objects, same as \dl+
\lo_list. Displays large objects with
additional information.
\dL[S+] [PATTERN] Lists procedural languages. \dL
Shows procedural
languages.
\dm[S+] [PATTERN] Lists materialized views. \dm
Displays materialized views.
\dn[S+] [PATTERN] Lists schemas. \dn+
Shows schemas with
additional details.
\do[S+] [OPPTRN Lists operators. \do
[TYPEPTRN Displays operators.
[TYPEPTRN]]]
\dO[S+] [PATTERN] Lists collations. \dO+
Lists collations with extra
detail.
\dp[S] [PATTERN] Lists access privileges for tables, \dp
views, and sequences. Shows access privileges for
specified relations.
\dP[itn+] [PATTERN] Lists partitioned relations (tables \dP+
or indexes). Displays partitioned
relations.
\drds [ROLEPTRN Lists per-database role settings. \drds
[DBPTRN]] Shows role settings per
database.
\drg[S] [PATTERN] Lists role grants. \drg
Displays role grants.
\dRp[+] [PATTERN] Lists replication publications. \dRp
Shows replication
publications.
\dRs[+] [PATTERN] Lists replication subscriptions. \dRs+
Displays replication
subscriptions.
\ds[S+] [PATTERN] Lists sequences. \ds
Lists all sequences.
\dt[S+] [PATTERN] Lists tables. \dt+
Shows tables with additional
details.
\dT[S+] [PATTERN] Lists data types. \dT+
Displays all data types with
details.
\du[S+] [PATTERN] Lists roles. \du
Lists roles.
\dv[S+] [PATTERN] Lists views. \dv+
Shows views with additional
information.
\dx[+] [PATTERN] Lists extensions. \dx+
Displays extensions.
\dX [PATTERN] Lists extended statistics. \dX
Lists extended statistics.
\dy[+] [PATTERN] Lists event triggers. \dy+
Shows event triggers.
\l[+] [PATTERN] Lists databases. \l+
Displays databases with
additional information.
\sf[+] FUNCNAME Shows a function’s definition. \sf+ my_function
Displays the definition of
my_function with
additional details.
\sv[+] VIEWNAME Shows a view’s definition. \sv+ my_view
Displays the definition of
my_view with details.
\z[S] [PATTERN] Same as \dp; lists access \z+
privileges. Shows access privileges with
additional details.

LARGE OBJECTS COMMANDS


Command Description Example
\lo_export LOBOID Writes (exports) a large object to a \lo_export 12345
FILE '/path/to/file'
specified file.
Exports large object with ID
12345.
\lo_import FILE Reads (imports) a file as a large \lo_import '/path/to/file'
[COMMENT] 'Sample Comment'
object, with an optional comment.
Imports a file as a large object
with a comment.
\lo_list[+] Lists large objects, with + for \lo_list+
additional details. Displays large objects with extra
detail.
\lo_unlink LOBOID Deletes a specified large object. \lo_unlink 12345
Deletes the large object with ID
12345.

FORMATTING COMMANDS
Command Description Example
\a Toggles between unaligned (plain \a
text) and aligned (table format) Switches between unaligned and
output mode. aligned output.
\C [STRING] Sets a title for the table output or \C "Sales Report"
unsets it if none is provided. Sets the title "Sales Report" for the
output.
\f [STRING] Sets or shows the field separator for \f ','
unaligned output. Sets comma as the field separator in
unaligned output.
\H Toggles HTML output mode on or \H
off. Switches to HTML output format.
\pset [NAME Sets table output options like border, \pset border 2
[VALUE]] Sets a thicker border around the
format, and title.
table.
`\t [on off]` Toggles visibility of row-only
output, hiding or showing column
headers.
\T [STRING] Sets HTML <table> tag attributes, \T 'class="myTable"'
such as class or style, or unsets them Adds a CSS class to the HTML table.
if none are provided.
`\x [on off auto]`
CONNECTIONS COMMANDS
Command Description Example
`\c[onnect] conninfo}` Connects to a new database or
{[DBNAME] [USER] changes connection
[HOST] [PORT] parameters. Use - to skip
parameters.
\conninfo Displays information about the \conninfo
current database connection, Shows current connection
including database name, user, details.
host, and port.
\encoding Displays or sets the client encoding \encoding UTF8
[ENCODING] Sets client encoding to UTF-8.
for character data, like UTF-8 or
LATIN1.
\password Securely prompts to change the \password user123
[USERNAME] Prompts to change the
password for the specified user.
password for "user123"
securely.
OPERATING SYSTEM COMMANDS
Command Description Example
\cd [DIR] Changes the current working \cd /home/user/documents
directory to the specified directory Changes directory to documents.
DIR.
\getenv Fetches the value of an \getenv mypath PATH
PSQLVAR Sets mypath to the system PATH.
environment variable ENVVAR and
ENVVAR
stores it in a psql variable PSQLVAR.
\setenv NAME Sets or unsets an environment \setenv GREETING Hello
[VALUE] Sets GREETING to "Hello".
variable NAME with an optional
value VALUE.
`\timing [on off]` Toggles the timing of SQL commands,
showing execution time in the output.
\! [COMMAND] Executes a shell command from \! ls -la
within psql or starts an interactive Lists files in the current directory.
shell if no command is given.
VARIABLE COMMANDS
Command Description Example
\prompt Prompts the user with the specified TEXT to \prompt 'Enter your
[TEXT] NAME name: ' USERNAME
set the internal variable NAME.
Prompts for username.
\set [NAME Sets the internal variable NAME to VALUE. If no \set DBNAME
[VALUE]] my_database
parameters are provided, it lists all variables.
Sets the DBNAME
variable.
\set
Lists all internal variables.
\unset NAME Unsets (deletes) the specified internal variable \unset DBNAME
NAME. Removes the DBNAME
variable.

You might also like