postgresql12 客户端命令浅析

这里写自定义目录标题

  • potgresql12 客户端命令参数浅析
    • pg_archivecleanup
    • pg_config
    • pg_dumpall
    • pg_dump
    • pg_restore
    • pg_basebackup
    • pg_resetwal
    • pg_test_fsync
    • pg_controldata
    • pg_recvlogical
    • pg_isready
    • pg_test_timing
    • pgbench
    • pg_rewind
    • pg_upgrade
    • vacuumdb
    • dropdb
    • pg_waldump
    • vacuumlo
    • dropuser
    • ecpg
    • pg_checksums
    • pg_standby
    • postmaster
    • clusterdb
    • initdb
    • oid2name
    • reindexdb

potgresql12 客户端命令参数浅析

本篇文章主要是介绍postgresql 12在shell命令行下一些命令的使用介绍。

pg_archivecleanup

pg_archivecleanup
Options:
-d generate debug output (verbose mode) 打印详细删除归档文件信息
-n dry run, show the names of the files that would be removed 打印要被删除的归档,但只打印,不删除
-V, --version output version information, then exit 打印pg的版本信息
-x EXT clean up files if they have this extension 清理添加了压缩参数的归档
-?, --help show this help, then exit

-d参数示例
pg_archivecleanup -d /rh/pg7666/pg_archlog/ 000000010000000100000077
pg_archivecleanup: keeping WAL file “/rh/pg7666/pg_archlog//000000010000000100000077” and later
pg_archivecleanup: removing file “/rh/pg7666/pg_archlog//000000010000000000000001”

-n参数示例
pg_archivecleanup -n /rh/pg7666/pg_archlog/ 000000010000000100000079
/rh/pg7666/pg_archlog//000000010000000100000077
/rh/pg7666/pg_archlog//000000010000000100000078
ll |grep 000000010000000100000077
-rw------- 1 postgres dba 16777216 Sep 8 00:00 000000010000000100000077
-rw------- 1 postgres dba 292 Sep 8 00:00 000000010000000100000077.00000028.backup

-V参数示例
pg_archivecleanup -V /rh/pg7666/pg_archlog/ 000000010000000100000079
pg_archivecleanup (PostgreSQL) 10.6

pg_config

pg_config [OPTION]…

Options:
–bindir show location of user executables 打印pg可执行文件的所在路径
–docdir show location of documentation files 打印帮助文档所在路径
–htmldir show location of HTML documentation files 打印html格式文件所在路径
–includedir show location of C header files of the client 打印include路径
interfaces
–pkgincludedir show location of other C header files 同上
–includedir-server show location of C header files for the server 打印include server路径
–libdir show location of object code libraries 打印lib路径
–pkglibdir show location of dynamically loadable modules 同上
–localedir show location of locale support files 打印local下的支持文件
–mandir show location of manual pages 打印man帮助手册路径
–sharedir show location of architecture-independent support files 打印share路径
–sysconfdir show location of system-wide configuration files 打印系统范围配置文件的位置
–pgxs show location of extension makefile 打印扩展 makefile 的位置
–configure show options given to “configure” script when 打印当PostgreSQL被配置编译时给予configure脚本的选项,主从的要一致
PostgreSQL was built
–cc show CC value used when PostgreSQL was built 打印编译pg的工具
–cppflags show CPPFLAGS value used when PostgreSQL was built 打印用来编译PostgreSQL的CPPFLAGS变量值
–cflags show CFLAGS value used when PostgreSQL was built 打印用来编译PostgreSQL的CFLAGS变量值
–cflags_sl show CFLAGS_SL value used when PostgreSQL was built 打印用来编译PostgreSQL的CFLAGS_SL变量值
–ldflags show LDFLAGS value used when PostgreSQL was built 打印用来编译PostgreSQL的LDFLAGS变量值
–ldflags_ex show LDFLAGS_EX value used when PostgreSQL was built 打印用来编译PostgreSQL的LDFLAGS_EX变量值
–ldflags_sl show LDFLAGS_SL value used when PostgreSQL was built 打印用来编译PostgreSQL的LDFLAGS_SL变量值
–libs show LIBS value used when PostgreSQL was built 打印用来编译PostgreSQL的LIBS变量值
–version show the PostgreSQL version 打印PostgreSQL的版本
-?, --help show this help, then exit
参数使用示例
pg_config --bindir
/app/postgres/base/10.6/bin

pg_config --docdir
/app/postgres/base/10.6/share/doc

pg_config --htmldir
/app/postgres/base/10.6/share/doc

pg_config --includedir
/app/postgres/base/10.6/include

pg_config --pkgincludedir
/app/postgres/base/10.6/include

pg_config --includedir-server
/app/postgres/base/10.6/include/server

pg_config --libdir
/app/postgres/base/10.6/lib

pg_config --pkglibdir
/app/postgres/base/10.6/lib

pg_config --localedir
/app/postgres/base/10.6/share/locale

pg_config --mandir
/app/postgres/base/10.6/share/man

pg_config --sharedir
/app/postgres/base/10.6/share

pg_config --sysconfdir
/app/postgres/base/10.6/etc

pg_config --pgxs
/app/postgres/base/10.6/lib/pgxs/src/makefiles/pgxs.mk

pg_config --configure
‘–prefix=/app/postgres/base/10.6’ ‘–with-libedit-preferred’ ‘–with-perl’ ‘–with-python’ ‘–with-uuid=e2fs’

pg_config --cc
gcc

pg_config --cppflags
-D_GNU_SOURCE

pg_config --cflags
-Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2

pg_config --cflags_sl
-fPIC

pg_config --ldflags
-Wl,–as-needed -Wl,-rpath,’/app/postgres/base/10.6/lib’,–enable-new-dtags

pg_config --libs
-lpgcommon -lpgport -lpthread -lz -lreadline -lrt -lcrypt -ldl -lm

pg_dumpall

pg_dumpall extracts a PostgreSQL database cluster into an SQL script file.

Usage:
pg_dumpall [OPTION]…

General options:
-f, --file=FILENAME output file name 指定逻辑备份导出的文件名,如未指定,则输出到标准输出
-v, --verbose verbose mode 打印备份的起止时间到备份文件和进程信息到标准错误输出
-V, --version output version information, then exit 打印版本信息
–lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock 备份遇到锁等待的时间
-?, --help show this help, then exit

Options controlling the output content:
-a, --data-only dump only the data, not the schema 只导出数据
-c, --clean clean (drop) databases before recreating 导出database的drop语句
-g, --globals-only dump only global objects, no databases 只导出全局对象(角色或者表空间)
-o, --oids include OIDs in dump 导出OID
-O, --no-owner skip restoration of object ownership 默认会导出owner的设置语句,添加-O则不导出
-r, --roles-only dump only roles, no databases or tablespaces 只导出roles
-s, --schema-only dump only the schema, no data 只导出表结构
-S, --superuser=NAME superuser user name to use in the dump 指定要在禁用触发器时使用的超级用户的用户名。只有使用–disable-triggers时,这个选项才相关
-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 把数据导出成insert 带列名的SQL语句格式,但这会导致恢复非常慢,一般用于导入到别的数据库才使用
–disable-dollar-quoting disable dollar quoting, use SQL standard quoting 禁止函数中使用$符号
–disable-triggers disable triggers during data-only restore 只有在只恢复数据的时候使用,在导入的时候临时禁止triggers
–exclude-database=PATTERN exclude databases whose name matches PATTERN 不导出指定的database
–extra-float-digits=NUM override default setting for extra_float_digits 导出浮点数时用extra_float_digits的精度值覆盖,一般不使用
–if-exists use IF EXISTS when dropping objects 当导出的语句带drop时,使用if exists 判断。只有同时指定了–clean时,这个选项才可用
–inserts dump data as INSERT commands, rather than COPY 把数据导出成insert模式,但这会导致恢复非常慢,一般用于导入到别的数据库才使用,–column-inserts选项对于列序改变是安全的,但是会更慢。
–no-publications do not dump publications
–no-role-passwords do not dump passwords for roles 不导出roles的密码,在设置密码前的认证都会失败
–no-security-labels do not dump security label assignments
–no-subscriptions do not dump subscriptions
–no-sync do not wait for changes to be written safely to disk pg_dumpall将等待所有文件被安全地写入到磁盘。这个选项会让pg_dumpall不做这种等待而返回,这样会更快,但是意味着后续的操作系统崩溃可能会造成dump文件损坏
–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
–rows-per-insert=NROWS number of rows per INSERT; implies --inserts 控制一条insert语句插入的行数
–use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership

Connection options:
-d, --dbname=CONNSTR connect using connection string
-h, --host=HOSTNAME database server host or socket directory
-l, --database=DBNAME alternative default database
-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

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

pg_dump

pg_dump [OPTION]… [DBNAME]

General options:
-f, --file=FILENAME output file or directory name 指定导出的文件
-F, --format=c|d|t|p output file format (custom, directory, tar, plain text (default)) 指定输出格式,默认是p
-j, --jobs=NUM use this many parallel jobs to dump 指定并发
-v, --verbose verbose mode 打印备份起止时间,并打印进程信息
-V, --version output version information, then exit 打印版本信息
-Z, --compress=0-9 compression level for compressed formats 压缩级别
–lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock 锁等待超时时间
–no-sync do not wait for changes to be written safely to disk 这个选项会让pg_dump不做写入磁盘等待而返回,这样会更快,但是意味着后续的操作系统崩溃可能会造成dump文件损坏
-?, --help show this help, then exit

Options controlling the output content:
-a, --data-only dump only the data, not the schema 只导出数据
-b, --blobs include large objects in dump 导出包括大对象
-B, --no-blobs exclude large objects in dump 不导出大对象
-c, --clean clean (drop) database objects before recreating 导出带drop语句的database
-C, --create include commands to create database in dump 导出带crete database的语句
-E, --encoding=ENCODING dump the data in encoding ENCODING 指定导出的编码
-n, --schema=PATTERN dump the specified schema(s) only 导出指定的schema
-N, --exclude-schema=PATTERN do NOT dump the specified schema(s) 不导出指定的schema
-O, --no-owner skip restoration of object ownership in 不导出对象的owner属性和对象的拥有关系
plain-text format
-s, --schema-only dump only the schema, no data 只导出表结构
-S, --superuser=NAME superuser user name to use in plain-text format 指定要在禁用触发器时使用的超级用户的用户名。只有使用–disable-triggers时,这个选项才相关
-t, --table=PATTERN dump the specified table(s) only 导出指定的表
-T, --exclude-table=PATTERN do NOT dump the specified 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 导出语句为insert列名values格式
–disable-dollar-quoting disable dollar quoting, use SQL standard quoting 禁止函数中使用$符号
–disable-triggers disable triggers during data-only restore 只恢复数据时禁用triggers
–enable-row-security enable row security (dump only content user has 在导出有安全性表的内容时,这个选项才相关,设置为on,则用户只导出该表中 它们能够访问到的部分内容。注意如果你使用了这个选项,你还得想到以INSERT格式的导出,因为恢复期间的COPY FROM不支持行安全性
access to)
–exclude-table-data=PATTERN do NOT dump data for the specified table(s) 不导出指定表的数据
–extra-float-digits=NUM override default setting for extra_float_digits 参考pg_dumpall
–if-exists use IF EXISTS when dropping objects 参考pg_dumpall
–inserts dump data as INSERT commands, rather than COPY 参考pg_dumpall
–load-via-partition-root load partitions via the root table 导出分区时,指定这个参数,会让在恢复的时候数据按表分区规定重新分配到不同的分区,适用于两个表的分区定义不同。如果使用了此选项,最好不要开并行,容易导致恢复失败
–no-comments do not dump comments 不导出comments
–no-publications do not dump publications
–no-security-labels do not dump security label assignments
–no-subscriptions do not dump subscriptions
–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
–on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands
–quote-all-identifiers quote all identifiers, even if not key words
–rows-per-insert=NROWS number of rows per INSERT; implies --inserts 指定一条insert的行数
–section=SECTION dump named section (pre-data, data, or post-data)
–serializable-deferrable wait until the dump can run without anomalies
–snapshot=SNAPSHOT use given snapshot for the dump 指定快照导出
–strict-names require table and/or schema include patterns to
match at least one entity each
–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

If no database name is supplied, then the PGDATABASE environment
variable value is used.

pg_restore

pg_restore [OPTION]… [FILE]

General options:
-d, --dbname=NAME connect to database name
-f, --file=FILENAME output file name (- for stdout) 指定要被恢复的归档文件(对于一个目录格式的归档则是目录)的位置。如果没有指定,则使用标准输入。
-F, --format=c|d|t backup file format (should be automatic) 指定归档的格式。并不一定要指定该格式,因为pg_restore将会自动决定格式。
-l, --list print summarized TOC of the archive
-v, --verbose verbose mode
-V, --version output version information, then exit
-?, --help 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 导入前先drop database对象
-C, --create create the target database 导入前创建指定的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 只恢复指定的schema
-N, --exclude-schema=NAME do not restore objects in this schema 不恢复指定的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 只恢复schema的定义,不导入数据
-S, --superuser=NAME superuser user name to use for disabling triggers
-t, --table=NAME restore named relation (table, view, etc.) 恢复指定的表
-T, --trigger=NAME restore named trigger 恢复指定的trigger
-x, --no-privileges skip restoration of access privileges (grant/revoke) 不恢复权限
-1, --single-transaction restore as a single transaction 将恢复作为单一的事务恢复,这个选项隐含了–exit-on-error。
–disable-triggers disable triggers during data-only restore
–enable-row-security enable row security
–if-exists use IF EXISTS when dropping objects 删除对象是用if exists判断
–no-comments do not restore comments 不恢复comments
–no-data-for-failed-tables do not restore data of tables that could not be created 默认如果表存在,表创建失败也会恢复数据到表中,添加此选项表不能创建就不恢复数据
–no-publications do not restore publications
–no-security-labels do not restore security labels
–no-subscriptions do not restore subscriptions
–no-tablespaces do not restore tablespace assignments
–section=SECTION restore named section (pre-data, data, or post-data)
–strict-names require table and/or schema include patterns to
match at least one entity each
–use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership

Connection options:
-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 restore

The options -I, -n, -N, -P, -t, -T, and --section can be combined and specified
multiple times to select multiple objects.

If no input file name is supplied, then standard input is used.

pg_basebackup

pg_basebackup [OPTION]…

Options controlling the output:
-D, --pgdata=DIRECTORY receive base backup into directory
-F, --format=p|t output format (plain (default), tar)
-r, --max-rate=RATE maximum transfer rate to transfer data directory (in kB/s, or use suffix “k” or “M”) 限制远程备份传输速度
-R, --write-recovery-conf write configuration for replication 备份文件中自动生成recover.conf
-T, --tablespace-mapping=OLDDIR=NEWDIR relocate tablespace in OLDDIR to NEWDIR 指定恢复到特定表空间,相当于oracle恢复时表空间替换
–waldir=WALDIR location for the write-ahead log directory 指定wal路径,waldir必须是绝对路径。只有当备份是平面文件模式时才能指定事务日志目录。
-X, --wal-method=none|fetch|stream include required WAL files with specified method
-z, --gzip compress tar output
-Z, --compress=0-9 compress tar output with given compression level

General options:
-c, --checkpoint=fast|spread set fast or spread checkpointing 将检查点模式设置为 fast(立刻)或 spread(默认)
-C, --create-slot create replication slot
-l, --label=LABEL set backup label 为备份设置标签
-n, --no-clean do not clean up after errors 如果备份报错,默认会删除创建的目录和文件,此选项可禁止删除
-N, --no-sync do not wait for changes to be written safely to disk
-P, --progress show progress information
-S, --slot=SLOTNAME replication slot to use
-v, --verbose output verbose messages
-V, --version output version information, then exit
–no-slot prevent creation of temporary replication slot 如果服务器支持临时复制槽,这个选项防止备份期间创建临时复制槽
–no-verify-checksums
do not verify checksums
-?, --help show this help, then exit

Connection options:
-d, --dbname=CONNSTR connection string
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port number
-s, --status-interval=INTERVAL
time between status packets sent to server (in seconds)
-U, --username=NAME connect as specified database user
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)

常用备份命令:pg_basebackup -D /dbdata/pg7810/backup/ -R -X stream -P -h 100.70.24.15 -p 7810 -U repuser -w

pg_resetwal

pg_resetwal [OPTION]… DATADIR

Options:
-c, --commit-timestamp-ids=XID,XID set oldest and newest transactions bearing commit timestamp (zero means no change) 手工设置提交时间可以检索到的最老的和最新的事务 ID
[-D, --pgdata=]DATADIR data directory 指定data目录
-e, --epoch=XIDEPOCH set next transaction ID epoch 手工设置下一个事务 ID 的 epoch
-f, --force force update to be done 强制命令进行
-l, --next-wal-file=WALFILE set minimum starting location for new WAL 通过指定下一个WAL段文件名称来手工设置WAL开始位置
-m, --multixact-ids=MXID,MXID set next and oldest multitransaction ID 确定下一个和最老的多事务 ID
-n, --dry-run no update, just show what would be done 不真正执行
-o, --next-oid=OID set next OID 设置下一个OID
-O, --multixact-offset=OFFSET set next multitransaction offset 手工设置下一个多事务偏移量
-V, --version output version information, then exit
-x, --next-transaction-id=XID set next transaction ID 手工设置下一个事务 ID
–wal-segsize=SIZE size of WAL segments, in megabytes 设置新的WAL段尺寸,以兆字节为单位。这个值必须被设为2的1次幂和1024次幂(兆字节)之间
-?, --help show this help, then exit

pg_test_fsync

pg_test_fsync 是测试 wal_sync_method设置哪个值最快,报告每个wal_sync_method的平均文件同步操作时间(以微秒为单位)
-f --filename 指定要写入测试数据到其中的文件名
-s --secs-per-test 指定每次测试的秒数。每个测试的时间越长,测试的精度就越高,默认是5秒

pg_controldata

pg_controldata displays control information of a PostgreSQL database cluster.

Usage:
pg_controldata [OPTION] [DATADIR]

Options:
[-D, --pgdata=]DATADIR data directory 指定pg的data路径,打印pg的状态统计信息(Database cluster state:可以判断是主备库,in production是主)
-V, --version output version information, then exit
-?, --help show this help, then exit

If no data directory (DATADIR) is specified, the environment variable PGDATA

pg_recvlogical

pg_recvlogical [OPTION]… 主要是用来获取数据库的增量变化

Action to be performed:
–create-slot create a new replication slot (for the slot’s name see --slot) 创建一个新的复制槽
–drop-slot drop the replication slot (for the slot’s name see --slot)
–start start streaming in a replication slot (for the slot’s name see --slot)

Options:
-E, --endpos=LSN exit after receiving the specified LSN
-f, --file=FILE receive log into this file, - for stdout 指定接收日志的写入文件
-F --fsync-interval=SECS
time between fsyncs to the output file (default: 10)
–if-not-exists do not error if slot already exists when creating a slot
-I, --startpos=LSN where in an existing slot should the streaming start
-n, --no-loop do not loop on connection lost
-o, --option=NAME[=VALUE]
pass option NAME with optional value VALUE to the
output plugin
-P, --plugin=PLUGIN use output plugin PLUGIN (default: test_decoding)
-s, --status-interval=SECS
time between status packets sent to server (default: 10)
-S, --slot=SLOTNAME name of the logical replication slot 指定复制槽的名字
-v, --verbose output verbose messages
-V, --version output version information, then exit
-?, --help show this help, then exit

Connection options:
-d, --dbname=DBNAME database to connect to
-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)

pg_isready

pg_isready --help 如果服务器正常接受连接,pg_isready返回0给shell;如果服务器拒绝连接(例如处于启动阶段)则返回1;如果连接尝试没有被响应则返回2;如果没有尝试(例如由于非法参数)则返回3。
pg_isready issues a connection check to a PostgreSQL database.

Usage:
pg_isready [OPTION]…

Options:
-d, --dbname=DBNAME database name
-q, --quiet run quietly
-V, --version output version information, then exit
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-t, --timeout=SECS seconds to wait when attempting connection, 0 disables (default: 3)
-U, --username=USERNAME user name to connect as

pg_test_timing

pg_test_timing --help
Usage: pg_test_timing [-d DURATION] 指定测试的持续时间,以秒计默认的测试持续时间是 3 秒。用来评测操作系统计时效率和开销的

pgbench

pgbench [OPTION]… [DBNAME]

Initialization options:
-i, --initialize invokes initialization mode
-I, --init-steps=[dtgvpf]+ (default “dtgvp”) run selected initialization steps 指定初始化的步骤,d删除已有的pgbench表,t创建表,g生成数据,v清理,p创建主键,f创建外键
-F, --fillfactor=NUM set fill factor
-n, --no-vacuum do not run VACUUM during initialization
-q, --quiet quiet logging (one message each 5 seconds)
-s, --scale=NUM scaling factor 指定生成表的行数,-s 100将在pgbench_accounts表中创建 10,000,000 行。默认为 1
–foreign-keys create foreign key constraints between tables
–index-tablespace=TABLESPACE create indexes in the specified tablespace
–tablespace=TABLESPACE create tables in the specified tablespace
–unlogged-tables create tables as unlogged tables

Options to select what to run:
-b, --builtin=NAME[@W] add builtin script NAME weighted at W (default: 1)
(use “-b list” to list available scripts)
-f, --file=FILENAME[@W] add script FILENAME weighted at W (default: 1)
-N, --skip-some-updates skip updates of pgbench_tellers and pgbench_branches
(same as “-b simple-update”)
-S, --select-only perform SELECT-only transactions (same as “-b select-only”) 为每一个事务建立一个新连接,而不是只为每个客户端会话建立一个连接。这对于度量连接开销有用。

Benchmarking options:
-c, --client=NUM number of concurrent database clients (default: 1) 指定并发
-C, --connect establish new connection for each transaction
-D, --define=VARNAME=VALUE 自定义变量
define variable for use by custom script
-j, --jobs=NUM number of threads (default: 1) 工作的线程数
-l, --log write transaction times to log file 指定测试日志输出
-L, --latency-limit=NUM count transactions lasting more than NUM ms as late 对持续超过limit毫秒的事务进行独立的计数和报告
-M, --protocol=simple|extended|prepared
protocol for submitting queries (default: simple)
-n, --no-vacuum do not run VACUUM before tests 在运行测试前不进行清理
-P, --progress=NUM show thread progress report every NUM seconds 每sec秒显示进度报告
-r, --report-latencies report average latency per command 测试结束后打印每个命令的执行时间
-R, --rate=NUM target rate in transactions per second 按照指定的速率执行事务而不是尽可能的快(默认是尽可能的快)
-s, --scale=NUM report this scale factor in output
-t, --transactions=NUM number of transactions each client runs (default: 10) 每个客户端运行的事务数量。默认为 10
-T, --time=NUM duration of benchmark test in seconds 运行测试这么多秒,而不是为每个客户端运行固定数量的事务。-t和-T是互斥的。
-v, --vacuum-all vacuum all four standard tables before tests 在运行测试前清理所有四个标准的表。在没有用-n以及-v时, pgbench将清理pgbench_tellers 和pgbench_branches表,并且清空pgbench_history。
–aggregate-interval=NUM aggregate data over NUM seconds
–log-prefix=PREFIX prefix for transaction time log file 设置–log创建的日志文件的文件名前缀。默认是pgbench_log。
(default: “pgbench_log”)
–progress-timestamp use Unix epoch timestamps for progress 当显示进度(选项-P)时,使用一个时间戳(Unix 时间)取代从运行开始的秒数
–random-seed=SEED set random seed (“time”, “rand”, integer)
–sampling-rate=NUM fraction of transactions to log (e.g., 0.01 for 1%)

Common options:
-d, --debug print debugging output
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port number
-U, --username=USERNAME connect as specified database user
-V, --version output version information, then exit
-?, --help show this help, then exit

pg_rewind

pg_rewind [OPTION]… 使一个postgresql数据目录与另一个数据目录一致,一个典型的场景是在故障转移之后,让一个老的主服务器重新在线作为一个standby跟随新主服务器。

Options:
-D, --target-pgdata=DIRECTORY existing data directory to modify 这个选项指定要与源数据目录同步的目标数据目录,但同步前必须停止
–source-pgdata=DIRECTORY source data directory to synchronize with 指定要和目标服务器同步的源服务器的数据目录的文件系统路径,同步前必须停止服务
–source-server=CONNSTR source server to synchronize with
-n, --dry-run stop before modifying anything 干跑不执行
-N, --no-sync do not wait for changes to be written 默认情况下,pg_rewind将等待所有文件安全地写入磁盘。 此选项会导致pg_rewind不等待即可返回,这更快,但意味着后续操作系统崩溃会使同步数据目录损坏
safely to disk
-P, --progress write progress messages 打印进度报告
–debug write a lot of debug messages
-V, --version output version information, then exit
-?, --help show this help, then exit
常用命令:pg_rewind --target-pgdata /usr/local/pg/data --source-server=‘host=192.168.56.25 port=5432 user=postgres dbname=postgres’ -P

pg_upgrade

pg_upgrade [OPTION]… 升级Pg

Options:
-b, --old-bindir=BINDIR old cluster executable directory 指定旧的 PostgreSQL 可执行文件目录
-B, --new-bindir=BINDIR new cluster executable directory 指定新的 PostgreSQL 可执行文件目录
-c, --check check clusters only, don’t change any data 只检查集群,不更改数据
-d, --old-datadir=DATADIR old cluster data directory 指定旧集群的data目录
-D, --new-datadir=DATADIR new cluster data directory 指定新集群的data目录
-j, --jobs=NUM number of simultaneous processes or threads to use 指定并发
-k, --link link instead of copying files to new cluster 使用硬链接代替文件拷贝到新集群
-o, --old-options=OPTIONS old cluster options to pass to the server
-O, --new-options=OPTIONS new cluster options to pass to the server
-p, --old-port=PORT old cluster port number (default 50432) 指定旧pg的端口
-P, --new-port=PORT new cluster port number (default 50432) 指定新pg的端口
-r, --retain retain SQL and log files after success 即使在成功完成后也保留 SQL 和日志文件
-s, --socketdir=DIR socket directory to use (default current dir.) 指定新socket目录
-U, --username=NAME cluster superuser (default “postgres”) 指定集群的超级用户默认是postgres
-v, --verbose enable verbose internal logging 打开详细的信息
-V, --version display version information, then exit
–clone clone instead of copying files to new cluster 克隆而不是拷贝文件到新集群
-?, --help show this help, then exit

Before running pg_upgrade you must:
create a new database cluster (using the new version of initdb)
shutdown the postmaster servicing the old cluster
shutdown the postmaster servicing the new cluster

When you run pg_upgrade, you must provide the following information:
the data directory for the old cluster (-d DATADIR)
the data directory for the new cluster (-D DATADIR)
the “bin” directory for the old version (-b BINDIR)
the “bin” directory for the new version (-B BINDIR)

For example:
pg_upgrade -d oldCluster/data -D newCluster/data -b oldCluster/bin -B newCluster/bin
or
$ export PGDATAOLD=oldCluster/data
$ export PGDATANEW=newCluster/data
$ export PGBINOLD=oldCluster/bin
$ export PGBINNEW=newCluster/bin
$ pg_upgrade

vacuumdb

vacuumdb [OPTION]… [DBNAME] 清理pg数据库的工具
1、释放,再利用 更新/删除的行所占据的磁盘空间.
2、更新PostgreSQL查询计划中使用的统计数据.
3、防止因事务ID的重置而使非常老的数据丢失.

Options:
-a, --all vacuum all databases 清理所有数据库
-d, --dbname=DBNAME database to vacuum 清理指定的数据库
–disable-page-skipping disable all page-skipping behavior
-e, --echo show the commands being sent to the server 输出工具发送给服务器的命令
-f, --full do full vacuuming 执行完全清理
-F, --freeze freeze row transaction information
-j, --jobs=NUM use this many concurrent connections to vacuum 指定并发
–min-mxid-age=MXID_AGE minimum multixact ID age of tables to vacuum
–min-xid-age=XID_AGE minimum transaction ID age of tables to vacuum
-q, --quiet don’t write any messages 不显示进度信息
–skip-locked skip relations that cannot be immediately locked 跳过无法立即锁定以进行处理的对象
-t, --table=‘TABLE[(COLUMNS)]’ vacuum specific table(s) only 只清理指定的表
-v, --verbose write a lot of output 输出详细的信息
-V, --version output version information, then exit
-z, --analyze update optimizer statistics 更新表的统计信息
-Z, --analyze-only only update optimizer statistics; no vacuum 只更新统计信息,不清理
–analyze-in-stages only update optimizer statistics, in multiple 只更新统计信息,不清理,使用多个步骤默认是3个来加快进度
stages for faster results; no vacuum
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as
-w, --no-password never prompt for password
-W, --password force password prompt
–maintenance-db=DBNAME alternate maintenance database

dropdb

dropdb [OPTION]… DBNAME 移除一个PostgreSQL数据库

Options:
-e, --echo show the commands being sent to the server 打印发送到服务的命令
-i, --interactive prompt before deleting anything 在删除前发出一个需要验证的提示
-V, --version output version information, then exit
–if-exists don’t report error if database doesn’t exist 如果database不存在,不输出报错信息
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as
-w, --no-password never prompt for password
-W, --password force password prompt
–maintenance-db=DBNAME alternate maintenance database
使用命令
/app/postgres/base/bin/dropdb -e -i wjz -U postgres -h 127.0.0.1 -p 7666 -w
Database “wjz” will be permanently removed.
Are you sure? (y/n) y
SELECT pg_catalog.set_config(‘search_path’, ‘’, false);
DROP DATABASE wjz;

pg_waldump

pg_waldump [OPTION]… [STARTSEG [ENDSEG]] 解析wal日志

Options:
-b, --bkp-details output detailed information about backup blocks 从指定的日志段文件开始读取
-e, --end=RECPTR stop reading at WAL location RECPTR 在读取指定的日志段文件后停止
-f, --follow keep retrying after reaching end of WAL 在到达可用 WAL 的末尾之后,保持每秒轮询一次是否有新的 WAL 出现。
-n, --limit=N number of records to display 显示指定数量的记录,然后停止
-p, --path=PATH directory in which to find log segment files or a 指定搜索日志段文件的目录或包含这些文件的包含pg_wal子目录的目录。 缺省值是在当前目录中搜索,当前目录的pg_wal子目录和 PGDATA的pg_wal子目录
directory with a ./pg_wal that contains such files
(default: current directory, ./pg_wal, $PGDATA/pg_wal)
-r, --rmgr=RMGR only show records generated by resource manager RMGR; 只显示由指定资源管理器生成的记录
use --rmgr=list to list valid resource manager names
-s, --start=RECPTR start reading at WAL location RECPTR 要从哪个WAL位置开始读取。默认是从找到的最早的文件的第一个可用日志记录开始
-t, --timeline=TLI timeline from which to read log records 要从哪个时间线读取日志记录。默认是使用startseg(如果指定) 中的值,否则默认为 1。
(default: 1 or the value used in STARTSEG)
-V, --version output version information, then exit
-x, --xid=XID only show records with transaction ID XID 只显示用给定事务 ID 标记的记录
-z, --stats[=record] show statistics instead of records 显示概括统计信息
(optionally, show per-record statistics)
-?, --help show this help, then exit

vacuumlo

vacuumlo [OPTION]… DBNAME… 从pg里删除无依赖的大对象

Options:
-l, --limit=LIMIT commit after removing each LIMIT large objects 在每一个事务中移除不超过limit个大对象(默认值为1000)
-n, --dry-run don’t remove large objects, just show what would be done 不移除大对象,只是输出将要执行的内容
-v, --verbose write a lot of progress messages
-V, --version output version information, then exit
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as
-w, --no-password never prompt for password
-W, --password force password prompt

dropuser

dropuser [OPTION]… [ROLENAME] 删除一个已有的用户

Options:
-e, --echo show the commands being sent to the server 输出执行的命令
-i, --interactive prompt before deleting anything, and prompt for role name if not specified 删除前提示验证,并且在没有在命令行指定用户名提示要求一个用户名
-V, --version output version information, then exit
–if-exists don’t report error if user doesn’t exist
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as (not the one to drop)
-w, --no-password never prompt for password
-W, --password force password prompt

ecpg

ecpg [OPTION]… FILE… 嵌入式 SQL C 预处理器

Options:
-c automatically generate C code from embedded SQL code;
this affects EXEC SQL TYPE
-C MODE set compatibility mode; MODE can be one of
“INFORMIX”, “INFORMIX_SE”, “ORACLE”
-D SYMBOL define SYMBOL
-h parse a header file, this option includes option “-c”
-i parse system include files as well
-I DIRECTORY search DIRECTORY for include files
-o OUTFILE write result to OUTFILE
-r OPTION specify run-time behavior; OPTION can be:
“no_indicator”, “prepare”, “questionmarks”
–regression run in regression testing mode
-t turn on autocommit of transactions
-V, --version output version information, then exit
-?, --help show this help, then exit

pg_checksums

pg_checksums [OPTION]… [DATADIR] 用于备份恢复后检查集群的数据,检查的时候,数据库必须关闭。如果没有校验和错误,则退出状态为零,如果检测到至少一个校验和失败,则退出状态为非零。

Options:
[-D, --pgdata=]DATADIR data directory 指定数据目录
-c, --check check data checksums (default)
-d, --disable disable data checksums 禁止数据的检查
-e, --enable enable data checksums 检查数据
-f, --filenode=FILENODE check only relation with specified filenode 仅验证文件节点为filenode的关系中的校验和
-N, --no-sync do not wait for changes to be written safely to disk
-P, --progress show progress information
-v, --verbose output verbose messages
-V, --version output version information, then exit
-?, --help show this help, then exit

If no data directory (DATADIR) is specified, the environment variable PGDATA
is used.

pg_standby

pg_standby [OPTION]… ARCHIVELOCATION NEXTWALFILE XLOGFILEPATH [RESTARTWALFILE]

Options:
-c copy file from archive (default)
-d generate lots of debugging output (testing only)
-k NUMFILESTOKEEP if RESTARTWALFILE is not used, remove files prior to limit
(0 keeps all)
-l does nothing; use of link is now deprecated
-r MAXRETRIES max number of times to retry, with progressive wait
(default=3)
-s SLEEPTIME seconds to wait between file checks (min=1, max=60,
default=5)
-t TRIGGERFILE trigger file to initiate failover (no default)
-V, --version output version information, then exit
-w MAXWAITTIME max seconds to wait for a file (0=no limit) (default=0)
-?, --help show this help, then exit

Main intended use as restore_command in postgresql.conf:
restore_command = ‘pg_standby [OPTION]… ARCHIVELOCATION %f %p %r’
e.g.
restore_command = ‘pg_standby /mnt/server/archiverdir %f %p %r’

postmaster

postmaster [OPTION]… postmaster是postgres的一个废弃的别名。
postgres
Options:
-B NBUFFERS number of shared buffers 设置被服务器进程使用的共享内存缓冲区数量。这个参数的默认值是initdb自动选择的。指定这个选项等效于设置shared_buffers配置参数。
-c NAME=VALUE set run-time parameter 设置启动参数
-C NAME print value of run-time parameter, then exit 打印运行的参数值,然后退出
-d 1-5 debugging level
-D DATADIR database directory 指定目录
-e use European date input format (DMY)
-F turn fsync off 禁用fsync调用以提高性能,但是要冒系统崩溃时数据损坏的风险
-h HOSTNAME host name or IP address to listen on
-i enable TCP/IP connections
-k DIRECTORY Unix-domain socket location
-N MAX-CONNECT maximum number of allowed connections
-o OPTIONS pass “OPTIONS” to each server process (obsolete)
-p PORT port number to listen on
-s show statistics after each query
-S WORK-MEM set amount of memory for sorts (in kB)
-V, --version output version information, then exit
–NAME=VALUE set run-time parameter
–describe-config describe configuration parameters, then exit
-?, --help show this help, then exit

Developer options:
-f s|i|n|m|h forbid use of some plan types
-n do not reinitialize shared memory after abnormal exit
-O allow system table structure changes
-P disable system indexes
-t pa|pl|ex show timings after each query
-T send SIGSTOP to all backend processes if one dies
-W NUM wait NUM seconds to allow attach from a debugger

Options for single-user mode:
–single selects single-user mode (must be first argument)
DBNAME database name (defaults to user name)
-d 0-5 override debugging level
-E echo statement before execution
-j do not use newline as interactive query delimiter
-r FILENAME send stdout and stderr to given file

Options for bootstrapping mode:
–boot selects bootstrapping mode (must be first argument)
DBNAME database name (mandatory argument in bootstrapping mode)
-r FILENAME send stdout and stderr to given file
-x NUM internal use

clusterdb

clusterdb [OPTION]… [DBNAME] clusterdb 是一个用于对某个 PostgreSQL 数据库中的表进行重建聚簇索引的工具。它寻找以前建过聚簇索引的表,然后在上次用过的同一个索引上再次建聚簇索引。将不会动那些从未建簇的表。
创建cluster index,首先创建一个索引idx_test ,然后cluster table_name using idx_test;
Options:
-a, --all cluster all databases 对所有数据库建簇。
-d, --dbname=DBNAME database to cluster 对指定的数据库建簇
-e, --echo show the commands being sent to the server 打印要执行的命令
-q, --quiet don’t write any messages
-t, --table=TABLE cluster specific table(s) only 对指定的表进行建簇
-v, --verbose write a lot of output
-V, --version output version information, then exit
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as
-w, --no-password never prompt for password
-W, --password force password prompt
–maintenance-db=DBNAME alternate maintenance database

initdb

initdb [OPTION]… [DATADIR] 创建一个数据库

Options:
-A, --auth=METHOD default authentication method for local connections 这个选项为本地用户指定在pg_hba.conf中使用的默认认证方法(host和local行),trust是默认值
–auth-host=METHOD default authentication method for local TCP/IP connections 这个选项为通过 TCP/IP 连接的本地用户指定在pg_hba.conf中使用的认证方法(host行)
–auth-local=METHOD default authentication method for local-socket connections 这个选项为通过 Unix 域套接字连接的本地用户指定在pg_hba.conf中使用的认证方法(local行)
[-D, --pgdata=]DATADIR location for this database cluster 指定初始化的目录
-E, --encoding=ENCODING set default encoding for new databases 选择模板数据库的编码
-g, --allow-group-access allow group read/execute on data directory 允许与集簇拥有者同组的用户读取initdb创建的所有集簇文件
–locale=LOCALE set default locale for new databases 为数据库集簇设置默认区域
–lc-collate=, --lc-ctype=, --lc-messages=LOCALE
–lc-monetary=, --lc-numeric=, --lc-time=LOCALE
set default locale in the respective category for
new databases (default taken from environment)
–no-locale equivalent to --locale=C
–pwfile=FILE read password for the new superuser from file
-T, --text-search-config=CFG
default text search configuration
-U, --username=NAME database superuser name
-W, --pwprompt prompt for a password for the new superuser 为超级用户设置密码
-X, --waldir=WALDIR location for the write-ahead log directory 指定wal日志路径
–wal-segsize=SIZE size of WAL segments, in megabytes 指定wal日志的大小

Less commonly used options:
-d, --debug generate lots of debugging output
-k, --data-checksums use data page checksums
-L DIRECTORY where to find the input files
-n, --no-clean do not clean up after errors
-N, --no-sync do not wait for changes to be written safely to disk
-s, --show show internal settings
-S, --sync-only only sync data directory

Other options:
-V, --version output version information, then exit
-?, --help show this help, then exit

If the data directory is not specified, the environment variable PGDATA
is used.

oid2name

oid2name [OPTION]… 解析一个PostgreSQL数据目录中的 OID 和文件结点

Options:
-f, --filenode=FILENODE show info for table with given file node 显示具有文件结点的表的信息filenode.
-i, --indexes show indexes and sequences too 输出索引和序列
-o, --oid=OID show info for table with given OID 输出指定OID的表
-q, --quiet quiet (don’t show headers)
-s, --tablespaces show all tablespaces 输出所有表空间
-S, --system-objects show system objects too 输出数据库对象
-t, --table=TABLE show info for named table 输出指定表名的信息
-V, --version output version information, then exit
-x, --extended extended (show additional columns) 输出特定列的信息
-?, --help show this help, then exit

Connection options:
-d, --dbname=DBNAME database to connect to
-h, --host=HOSTNAME database server host or socket directory
-H same as -h, deprecated option
-p, --port=PORT database server port number
-U, --username=USERNAME connect as specified database user

The default action is to show all database OIDs.

[postgres@cnsz92vl10964 ~]$ /app/postgres/base/bin/oid2name -U postgres -h 127.0.0.1 -p 7666 -d wjz -t test -x -i
From database “wjz”
Filenode Table Name Oid Schema Tablespace


 16386        test  16386  public  pg_default

[postgres@cnsz92vl10964 ~]$ /app/postgres/base/bin/oid2name -U postgres -h 127.0.0.1 -p 7666 -d wjz -f 16386
From database “wjz”:
Filenode Table Name


 16386        test

reindexdb

reindexdb [OPTION]… [DBNAME] 重建索引

Options:
-a, --all reindex all databases 对所有数据库重建索引
–concurrently reindex concurrently 指定在线重建索引,默认重建索引会锁表,指定后则不锁表
-d, --dbname=DBNAME database to reindex 指定对特定的database重建索引
-e, --echo show the commands being sent to the server 打印重建索引的命令
-i, --index=INDEX recreate specific index(es) only 指定对特定索引进行重建
-q, --quiet don’t write any messages
-s, --system reindex system catalogs 重建系统目录下的索引
-S, --schema=SCHEMA reindex specific schema(s) only 指定特定schema进行重建索引
-t, --table=TABLE reindex specific table(s) only 对指定的表进行重建索引
-v, --verbose write a lot of output
-V, --version output version information, then exit
-?, --help show this help, then exit

Connection options:
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port
-U, --username=USERNAME user name to connect as
-w, --no-password never prompt for password
-W, --password force password prompt
–maintenance-db=DBNAME alternate maintenance database

[postgres@cnsz92vl10964 ~]$ /app/postgres/base/bin/reindexdb -h 127.0.0.1 -U postgres -p 7666 -w -e wjz
SELECT pg_catalog.set_config(‘search_path’, ‘’, false);
REINDEX DATABASE wjz;

你可能感兴趣的:(postgresql)