Tải bản đầy đủ
Appendix B. PostgreSQL Packaged Command-Line Tools

Appendix B. PostgreSQL Packaged Command-Line Tools

Tải bản đầy đủ

--version
output version information, then exit
Options controlling the output content:
-a, --data-only
dump only the data, not the schema
-b, --blobs
include large objects in dump
-c, --clean
clean (drop) database objects before recreating
-C, --create
include commands to create database in dump
-E, --encoding=ENCODING
dump the data in encoding ENCODING
-n, --schema=SCHEMA
dump the named schema(s) only
-N, --exclude-schema=SCHEMA do NOT dump the named schema(s)
-o, --oids
include OIDs in dump
-O, --no-owner
skip restoration of object ownership in
plain-text format
-s, --schema-only
dump only the schema, no data
-S, --superuser=NAME
superuser user name to use in plain-text format
-t, --table=TABLE
dump the named table(s) only
-T, --exclude-table=TABLE
do NOT dump the named table(s)
-x, --no-privileges
do not dump privileges (grant/revoke)
--binary-upgrade
for use by upgrade utilities only
--column-inserts
dump data as INSERT commands with column names
--disable-dollar-quoting
disable dollar quoting, use SQL standard quoting
--disable-triggers
disable triggers during data-only restore
--exclude-table-data=TABLE do NOT dump data for the named table(s)
--if-exists
use IF EXISTS when dropping objects
--inserts
dump data as INSERT commands, rather than COPY
--no-security-labels
do not dump security label assignments
--no-synchronized-snapshots do not use synchronized snapshots in parallel jobs
--no-tablespaces
do not dump tablespace assignments
--no-unlogged-table-data
do not dump unlogged table data
--quote-all-identifiers
quote all identifiers, even if not key words
--section=SECTION
dump named section (pre-data, data, or post-data)
--serializable-deferrable
wait until the dump can run without anomalies
--use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership
Connection options:
-d, --dbname=DBNAME
database to dump
-h, --host=HOSTNAME
database server host or socket directory
-p, --port=PORT
database server port number
-U, --username=NAME
connect as specified database user
-w, --no-password
never prompt for password
-W, --password
force password prompt (should happen automatically)
--role=ROLENAME
do SET ROLE before dump

New features introduced in PostgreSQL 9.3.
New features introduced in PostgreSQL 9.4.
New features introduced in PostgreSQL 9.2.

196

|

Appendix B: PostgreSQL Packaged Command-Line Tools

Server Backup: pg_dumpall
Use pg_dump_all to back up all databases on your server onto a single plain-text or
plain-text SQL file. The backup routine will automatically include server-level objects
such as roles and tablespaces. Example B-2 shows the pg_dumpall help output. See
“Systemwide Backup Using pg_dumpall” on page 40 for the full discussion.
Example B-2. pg_dumpall help
pg_dumpall --help
pg_dumpall extracts a PostgreSQL database cluster into an SQL script file.
Usage:
pg_dumpall [OPTION]...
General options:
-f, --file=FILENAME
--lock-wait-timeout=TIMEOUT
--help
--version

output file name
fail after waiting TIMEOUT for a table lock
show this help, then exit
output version information, then exit

Options controlling the output content:
-a, --data-only
dump only the data, not the schema
-c, --clean
clean (drop) databases before recreating
-g, --globals-only
dump only global objects, no databases
-o, --oids
include OIDs in dump
-O, --no-owner
skip restoration of object ownership
-r, --roles-only
dump only roles, no databases or tablespaces
-s, --schema-only
dump only the schema, no data
-S, --superuser=NAME
superuser user name to use in the dump
-t, --tablespaces-only
dump only tablespaces, no databases or roles
-x, --no-privileges
do not dump privileges (grant/revoke)
--binary-upgrade
for use by upgrade utilities only
--column-inserts
dump data as INSERT commands with column names
--disable-dollar-quoting
disable dollar quoting, use SQL standard quoting
--disable-triggers
disable triggers during data-only restore
--inserts
dump data as INSERT commands, rather than COPY
--no-security-labels
do not dump security label assignments
--no-tablespaces
do not dump tablespace assignments
--no-unlogged-table-data
do not dump unlogged table data
--quote-all-identifiers
quote all identifiers, even if not key words
--use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead o
ALTER OWNER commands to set ownership
Connection options:
-d, --dbname=CONNSTR
-h, --host=HOSTNAME
-l, --database=DBNAME
-p, --port=PORT
-U, --username=NAME
-w, --no-password

connect using connection string
database server host or socket directory
alternative default database
database server port number
connect as specified database user
never prompt for password

Server Backup: pg_dumpall

|

197

-W, --password
--role=ROLENAME

force password prompt (should happen automatically)
do SET ROLE before dump

If -f/--file is not used, then the SQL script will be written to the standard
output.

New in PostgreSQL 9.3

Database Restore: pg_restore
Use pg_restore to restore backup files in tar, custom, or directory formats created using
pg_dump. Example B-3 shows the pg_restore help output. See “Restore” on page 40 for
more examples.
Example B-3. pg_restore help
pg_restore --help
pg_restore restores a PostgreSQL database from an archive created by pg_dump.
Usage:
pg_restore [OPTION]... [FILE]
General options:
-d, --dbname=NAME
-f, --file=FILENAME
-F, --format=c|d|t
-l, --list
-v, --verbose
-V, --version
-?, --help

connect to database name
output file name
backup file format (should be automatic)
print summarized TOC of the archive
verbose mode
output version information, then exit
show this help, then exit

Options controlling the restore:
-a, --data-only
restore only the data, no schema
-c, --clean
clean (drop) database objects before recreating
-C, --create
create the target database
-e, --exit-on-error
exit on error, default is to continue
-I, --index=NAME
restore named index
-j, --jobs=NUM
use this many parallel jobs to restore
-L, --use-list=FILENAME
use table of contents from this file for
selecting/ordering output
-n, --schema=NAME
restore only objects in this schema
-O, --no-owner
skip restoration of object ownership
-P, --function=NAME(args)
restore named function
-s, --schema-only
restore only the schema, no data
-S, --superuser=NAME
superuser user name to use for disabling triggers
-t, --table=NAME
restore named table(s)
-T, --trigger=NAME
restore named trigger
-x, --no-privileges
skip restoration of access privileges (grant/revoke)
-1, --single-transaction
restore as a single transaction
--disable-triggers
disable triggers during data-only restore
--no-data-for-failed-tables do not restore data of tables that could not be

198

|

Appendix B: PostgreSQL Packaged Command-Line Tools

--no-security-labels
--no-tablespaces
--section=SECTION

created
do not restore security labels
do not restore tablespace assignments
restore named section (pre-data, data, or post-data)

--use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership
Connection options:
-h, --host=HOSTNAME
-p, --port=PORT
-U, --username=NAME
-w, --no-password
-W, --password
--role=ROLENAME

database server host or socket directory
database server port number
connect as specified database user
never prompt for password
force password prompt (should happen automatically)
do SET ROLE before restore

New features introduced in PostgreSQL 9.2.

psql Interactive Commands
Example B-4 lists commands available in psql when you launch an interactive session.
For examples of usage, see “Environment Variables” on page 45 and “Interactive versus
Noninteractive psql” on page 46.
Example B-4. Getting list of interactive psql commands
\?
General
\copyright
show PostgreSQL usage and distribution terms
\g [FILE] or ;
execute query (and send results to file or |pipe)
\gset [PREFIX]
execute query and store results in psql variables
\h [NAME]
help on syntax of SQL commands, * for all commands
\q
quit psql
\watch [SEC]
execute query every SEC seconds
Query Buffer
\e [FILE] [LINE]
edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\p
show the contents of the query buffer
\r
reset (clear) the query buffer
\w FILE
write query buffer to file
Input/Output
\copy ...
perform SQL COPY with data stream to the client host
\echo [STRING]
write string to standard output
\i FILE
execute commands from file
\ir FILE
as \i, but relative to location of current script
\o [FILE]
send all query results to file or |pipe
\qecho [STRING]
write string to query output stream (see \o)
Informational
(options: S = show system objects, + = additional detail)

psql Interactive Commands

|

199

\d[S+]
list tables, views, and sequences
\d[S+] NAME
describe table, view, sequence, or index
\da[S] [PATTERN]
list aggregates
\db[+] [PATTERN]
list tablespaces
\dc[S] [PATTERN]
list conversions
\dC
[PATTERN]
list casts
\dd[S] [PATTERN]
show comments on objects
\ddp
[PATTERN]
list default privileges
\dD[S] [PATTERN]
list domains
\det[+] [PATTERN]
list foreign tables
\des[+] [PATTERN]
list foreign servers
\deu[+] [PATTERN]
list user mappings
\dew[+] [PATTERN]
list foreign-data wrappers
\df[antw][S+] [PATRN] list [only agg/normal/trigger/window] functions
\dF[+] [PATTERN]
list text search configurations
\dFd[+] [PATTERN]
list text search dictionaries
\dFp[+] [PATTERN]
list text search parsers
\dFt[+] [PATTERN]
list text search templates
\dg[+] [PATTERN]
list roles
\di[S+] [PATTERN]
list indexes
\dl
list large objects, same as \lo_list
\dL[S+] [PATTERN]
list procedural languages
\dm[S+] [PATTERN]
list materialized views
\dn[S+] [PATTERN]
list schemas
\do[S] [PATTERN]
list operators
\dO[S+] [PATTERN]
list collations
\dp
[PATTERN]
list table, view, and sequence access privileges
\drds [PATRN1 [PATRN2]] list per-database role settings
\ds[S+] [PATTERN]
list sequences
\dt[S+] [PATTERN]
list tables
\dT[S+] [PATTERN]
list data types
\du[+] [PATTERN]
list roles
\dv[S+] [PATTERN]
list views
\dE[S+] [PATTERN]
list foreign tables
\dx[+] [PATTERN]
list extensions
\dy
[PATTERN]
list event triggers
\l[+]
list databases
\sf[+] FUNCNAME
show a function's definition
\z
[PATTERN]
same as \dp
Formatting
\a
toggle between unaligned and aligned output mode
\C [STRING]
set table title, or unset if none
\f [STRING]
show or set field separator for unaligned query output
\H
toggle HTML output mode (currently off)
\pset NAME [VALUE]
set table output option
(NAME := {format|border|expanded|fieldsep|fieldsep_zero
| footer|null|
numericlocale|recordsep|tuples_only|title|tableattr|pager})
\t [on|off]
show only rows (currently off)
\T [STRING]
set HTML tag attributes, or unset if none
\x [on|off]
toggle expanded output (currently off)
Connection

200

|

Appendix B: PostgreSQL Packaged Command-Line Tools

\c[onnect] [DBNAME|- USER|- HOST|- PORT|-]
connect to new database (currently "postgres")
\encoding [ENCODING]
show or set client encoding
\password [USERNAME]
securely change the password for a user
\conninfo
display information about current connection
Operating System
\cd [DIR]
change the current working directory
\setenv NAME [VALUE]
set or unset environment variable
\timing [on|off]
toggle timing of commands (currently off)
\! [COMMAND]
execute command in shell or start interactive shell

New features introduced in PostgreSQL 9.3.
New features introduced in PostgreSQL 9.2.
New feature introduced in PostgreSQL 9.4. You can use \pset without any
arguments and it will output all the options you can set and what the current
values are set to.

psql Noninteractive Commands
Example B-5 shows the noninteractive commands help screen. Examples of their usage
are covered in “Interactive versus Noninteractive psql” on page 46.
Example B-5. psql basic help screen
psql --help
psql is the PostgreSQL interactive terminal.
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND
run only single command (SQL or internal) and exit
-d, --dbname=DBNAME
database name to connect to
-f, --file=FILENAME
execute commands from file, then exit
-l, --list
list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
-X, --no-psqlrc
do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute command file as a single transaction
--help
show this help, then exit
--version
output version information, then exit
Input and output options:
-a, --echo-all
echo all input from script
-e, --echo-queries
echo commands sent to server
-E, --echo-hidden
display queries that internal commands generate

psql Noninteractive Commands

|

201

-L,
-n,
-o,
-q,
-s,
-S,

--log-file=FILENAME
--no-readline
--output=FILENAME
--quiet
--single-step
--single-line

send session log to file
disable enhanced command-line editing (readline)
send query results to file (or |pipe)
run quietly (no messages, only query output)
single-step mode (confirm each query)
single-line mode (end of line terminates SQL command)

Output format options:
-A, --no-align
unaligned table output mode
-F, --field-separator=STRING
set field separator (default: "|")
-H, --html
HTML table output mode
-P, --pset=VAR[=ARG]
set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
set record separator (default: newline)
-t, --tuples-only
print rows only
-T, --table-attr=TEXT
set HTML table tag attributes (e.g., width, border)
-x, --expanded
turn on expanded table output
-z, --field-separator-zero
set field separator to zero byte
-0, --record-separator-zero
set record separator to zero byte
Connection options:
-h, --host=HOSTNAME
database server host or socket directory
-p, --port=PORT
database server port (default: "5432")
-U, --username=USERNAME database user name
-w, --no-password
never prompt for password
-W, --password
force password prompt (should happen automatically)
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.

These items are new features introduced in PostgreSQL 9.2.

202

|

Appendix B: PostgreSQL Packaged Command-Line Tools

Index

Symbols
#> operator, 98
#>> operator, 98
&& (overlap) operator, 96, 112
-> operator, 98
->> operator, 98
: (colon), 49
<@ (contained) operator, 96, 101
= (equality) operator, 101
? (key exists) operator, 101
@> (contains) operator, 96, 101
|| (concatenation) operator, 82, 91
~ (similar to) operator, 84

A
Adminer tool, 3
administration tools, 1–4
adminpack extension, 61
aggregates
FILTER clause and, 131–132
PL/V8 and, 158
window functions, 132–136
ALTER DATABASE command, 29, 42
ALTER DEFAULT PRIVILEGES command, 31
ALTER SEQUENCE command, 80
ALTER SYSTEM command, 17, 20
ALTER TABLE command, 42, 111
ALTER TABLESPACE command, 42, 170

ALTER TYPE command, 110
archive_command configuration directive, 182
array function, 90
arrays
about, 90
creating, 90
JSON starting number, 99
referencing elements in, 91
slicing and splicing, 91
splitting strings into, 82
unnesting to rows, 92
array_agg function, 91, 99
array_to_json function, 99
array_upper function, 91
asynchronous transactions, 180
authentication methods, 21–23
autocommit commands, 49

B
B-Tree indexes, 113, 115
B-Tree-GIN indexes, 114
B-Tree-GiST indexes, 114
back-referencing, 83
backup and restore
pgAdmin tool, 67–69
pg_dump tool, 38–39, 67, 68, 195–196
pg_dumpall tool, 38, 40, 68, 197
pg_restore tool, 40–42, 67, 198
basic CTEs, 136

We’d like to hear your suggestions for improving our indexes. Send email to index@oreilly.com.

203

batch jobs, pgAgent and, 73
BETWEEN operator, 88
Big SQL technology, 15
bigserial data type, 80
bitmap index scan, 117
btree_gin extension, 36
btree_gist extension, 36, 112
btrim function, 82

C
caching, 171
canonical form, 93
cascading replication, 180, 181
CASE expression, 176
case sensitivity, 126
casts, 8, 126
catalogs, 5
\cd command, 61
char data type, 81
characters and strings
about, 81
pattern matching and, 83–84
regular expressions and, 83–84
splitting strings, 82
string functions, 82
check constraints, 111
colon (:), 49
columns view, 5
command-line tools
fetching output from, 53
packaged, 195–202
retrieving prior commands, 50
common table expressions (CTEs)
about, 136
basic, 136
recursive, 138
writable, 137
composite data types, 103, 128–129
concatenation operator, 82, 91
configuration files, 17–23, 61
\connect command, 48
connections
managing, 23–24
to servers, 58
constraints
about, 107, 110
check, 111
exclusion, 112
foreign key, 110
204

|

Index

unique, 111
constructor range functions, 95
contained (<@) operator, 96, 101
contains (@>) operator, 96, 101
continuous range types, 93
contribs (see extensions)
Coordinated Universal Time (UTC), 85
\copy command, 52–54, 64
CREATE DATABASE command, 26, 30, 41
CREATE EXTENSION command, xi, 7, 35, 61
CREATE GROUP command, 25
CREATE MATERIALIZED VIEW command,
123
CREATE PRODCEDURAL LANGUAGE com‐
mand, 7
CREATE ROLE command, 25, 25, 30
CREATE SCHEMA command, 29
CREATE SEQUENCE command, 80
CREATE TABLE command, 97
CREATE TABLESPACE command, 42
CREATE TYPE command, 109
CREATE UNIQUE INDEX command, 123
CREATE USER command, 25
CREATEDB rights, 27
crontab command, 73
CTEs (common table expressions)
about, 136
basic, 136
recursive, 138
writable, 137
custom data types
building, 104
building operators and functions for, 105
tables as, 103

D
daemons (services)
about, 4
pgAgent tool and, 73
data definition language (DDL), 8
data types
about, 7, 79
arrays, 90–93
characters and strings, 81–84
custom and composite, 103–106
json, 96–101
jsonb, 96, 99–101
numerics, 79–81
range types, 93–96

temporals, 84–90
xml, 101–103
database administration
backup and restore, 38–42, 68–69, 195–199
common mistakes, 43–44
configuration files, 17–23
creating assets, 62
database creation, 26
extensions and, 32–38
managing connections, 23–24
managing disk storage, 42
privileges and, 29–32, 62–64
roles and, 24–26
services and, 4
database drivers, 14
database objects, 4–9
date data type, 85
daterange data type, 94
datetime operators and functions, 88
date_part function, 89
daylight saving time (DST), 84
dblink extension, 37
DDL (data definition language), 8
Debian platform, 192
default privileges, 31
DELETE USING command, 128
delimiters, 53, 65
discrete range types, 93
DISTINCT ON clause, 125
DO command, 130
Document Type Definition (DTD), 101
DROP MATERIALIZED VIEW command, 124
DST (daylight saving time), 84
DTD (Document Type Definition), 101
Dunstan Andrew, 158

E
effective_cache_size network setting, 20
enable_nestloop setting, 167
enable_seqscan setting, 167
end-of-life (EOL) support, 9
EnterpriseDB, 191–192
environment variables, 45
EOL (end-of-life) support, 9
equality (=) operator, 101
exclusion constraints, 112
EXPLAIN ANALYZE command, 161
EXPLAIN ANALYZE VERBOSE command, 49
EXPLAIN command, 161

exporting data
pgAdmin and, 65–66
psql and, 52–53
extensions
about, 6, 32–33
classic, 37
common, 36–38
downloading, 34
getting information about, 33
installing, 32–36
popular, 36
upgrading to new model, 35

F
FDWs (foreign data wrappers)
about, 6, 179, 184
querying flat files, 185–187
querying foreign servers, 187
querying nonconventional data sources, 188
Fedora platform, 191
file_fdw wrapper, 185
FILTER clause, 131–132, 177
filtered indexes, 116
flat files, querying, 185–187
foreign data wrappers (FDWs)
about, 6, 179, 184
querying flat files, 185–187
querying foreign servers, 187
querying nonconventional data sources, 188
foreign key constraints, 110
foreign servers, querying, 187
foreign tables, 6
forking, 15
FreeBSD platform, 192
functional indexes, 116
functions
about, 7, 79
anatomy of, 143–147
building for custom data types, 105
datetime, 88
PL/CoffeeScript, 155–159
PL/LiveScript, 155–159
PL/plSQL, 152–153
PL/Python, 153–155
PL/V8, 155–159
returning, 127
string, 82
window, 132–136
writing in SQL, 148–151
Index

|

205

fuzzystrmatch extension, 37

G
Generalized Inverted Index (GIN) indexes, 113
Generalized Search Tree (GiST) indexes, 113
generate_series function, 89, 127
geocoding, pgScript and, 70
GIN (Generalized Inverted Index) indexes, 113
GiST (Generalized Search Tree) indexes, 113
GRANT command, 26, 30
Grant Wizard, 63
graphical explain plan, 72
group login roles, 24
group roles
about, 24
creating, 25–26
inheriting rights from, 26

H
hash indexes, 114
hstore extension, 37, 129
HTML format, 54–56, 65

I
\i command, 61
ident authentication method, 22
ILIKE operator, 37, 126
importing data
pgAdmin and, 64
psql and, 52–54
indexes
about, 107, 112
bitmap index scan, 117
determining usefulness of, 168–169
filtered, 116
functional, 116
multicolumn, 117
operator classes and, 114–116
partial, 116
troubleshooting, 116
information_schema catalog, 5, 60
inheriting
rights from group roles, 26
tables, 108, 127
INSERT command, 97
INSTEAD OF triggers, 119, 121
int4range data type, 94

206

| Index

int8range data type, 94
interval data type, 84–85

J
Java language, 14
JavaScript language, 96
job scheduling, 73–76
joins, lateral, 139–141
json data type
about, 96
inserting data, 97
outputting data, 99
queries and, 97–99
jsonb data type, 96, 99–101
jsonb_array_element function, 99
jsonb_array_length function, 101
jsonb_each function, 100
jsonb_extract_path_text function, 100
jsonb_object_field function, 99
json_agg function, 99
json_array_elements function, 97
json_array_length function, 98, 101
json_each function, 100
json_extract_path function, 97, 98
json_extract_path_text function, 97, 100

K
key exists (?) operator, 101

L
LAG function, 135
LATERAL keyword, 139–141
LEAD function, 135
LibreOffice office suite, 14
LIKE operator, 37, 115, 126
LIMIT clause, 125
Linux platform
crontab command, 73
installing PostgreSQL, 191
psql tool and, 47
listen_addresses network setting, 19
lists of objects, 51
login roles, 24–25
lpad function, 82
ltrim function, 82
Lubaczewski, Hubert, 54, 165