暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

postgresql自带指令命令系列一

necessary 2024-02-20
310

目录


简介

        在安装postgresql数据库的时候会需要设置一个关于postgresql数据库的PATH变量
export PATH=/home/postgres/pg/bin:$PATH,该变量会指向postgresql安装路径下的bin目录。这个安装目录和我们在进行编译的时候./configure --prefix= [指定安装目录]    中的prefix参数设置相关。--bindir=DIR  参数可以指定bin目录的具体存放路径。postgresql对应的PATH变量没有设置正确,会导致执行文件对应的命令无法使用

        本文使用postgresql-15.2版本进行讲解

bin目录

        进入到对应的bin目录中去,可以看到有以下的执行文件,本博主将进行一一讲解

  1. clusterdb
  2. createdb
  3. createuser
  4. dropdb
  5. dropuser
  6. ecpg
  7. initdb
  8. oid2name
  9. pg_amcheck
  10. pg_archivecleanup
  11. pg_basebackup
  12. pgbench
  13. pg_checksums
  14. pg_config
  15. pg_controldata
  16. pg_ctl
  17. pg_dump
  18. pg_dumpall
  19. pg_isready
  20. pg_receivewal
  21. pg_recvlogical
  22. pg_resetwal
  23. pg_restore
  24. pg_rewind
  25. pg_test_fsync
  26. pg_test_timing
  27. pg_upgrade
  28. pg_verifybackup
  29. pg_waldump
  30. postgres
  31. postmaster -> postgres
  32. psql
  33. reindexdb
  34. vacuumdb
  35. vacuumlo
复制

1.clusterdb

  1. clusterdb clusters all previously clustered tables in a database.

  2. clusterdb [OPTION]... [DBNAME]

  3. -a, --all cluster all databases

  4. -d, --dbname=DBNAME database to cluster

  5. -e, --echo show the commands being sent to the server

  6. -q, --quiet don't write any messages

  7. -t, --table=TABLE cluster specific table(s) only

  8. -v, --verbose write a lot of output

  9. -V, --version output version information, then exit

  10. -?, --help show this help, then exit

  11. -h, --host=HOSTNAME database server host or socket directory

  12. -p, --port=PORT database server port

  13. -U, --username=USERNAME user name to connect as

  14. -w, --no-password never prompt for password

  15. -W, --password force password prompt

  16. --maintenance-db=DBNAME alternate maintenance database

复制

        相当于数据库库中的cluster语法。重新组织表的物理存储顺序。它通过按照指定的索引对表进行排序来优化数据存储布局。这个排序的过程可以使得表中的数据更紧凑地存储在磁盘上,这有助于减少磁盘 I/O 操作,提高查询性能,尤其是对于范围查询和顺序访问的查询。支持远程执行

        一下几种情况需要使用clusterdb对数据库中的表进行重新组织

        数据库性能下降: 当数据库性能下降,特别是对于数据范围查询或顺序扫描性能不佳时,重新组织可以改善表的物理存储顺序,减少磁盘 I/O,从而提高性能。

        大量数据更新和删除: 如果数据库中的某些表经常进行大量的更新和删除操作,可能导致表的碎片化,即数据不再紧凑存储。clusterdb 可以清理这些碎片,重新组织表以提高数据存储的效率。

        索引性能问题: 索引是数据库性能的关键因素之一。如果索引的性能受到影响,可能需要重新组织索引。clusterdb 会考虑重新组织表的默认索引。

        数据库定期维护: 作为数据库维护的一部分,管理员可能会定期执行 clusterdb 操作,以确保数据库表的物理存储顺序保持最佳状态。


2.createdb        

  1. createdb creates a PostgreSQL database.

  2. createdb [OPTION]... [DBNAME] [DESCRIPTION]

  3. -D, --tablespace=TABLESPACE default tablespace for the database

  4. -e, --echo show the commands being sent to the server

  5. -E, --encoding=ENCODING encoding for the database

  6. -l, --locale=LOCALE locale settings for the database

  7. --lc-collate=LOCALE LC_COLLATE setting for the database

  8. --lc-ctype=LOCALE LC_CTYPE setting for the database

  9. --icu-locale=LOCALE ICU locale setting for the database

  10. --locale-provider={libc|icu}

  11. locale provider for the database's default collation

  12. -O, --owner=OWNER database user to own the new database

  13. -S, --strategy=STRATEGY database creation strategy wal_log or file_copy

  14. -T, --template=TEMPLATE template database to copy

  15. -V, --version output version information, then exit

  16. -?, --help show this help, then exit

  17. -h, --host=HOSTNAME database server host or socket directory

  18. -p, --port=PORT database server port

  19. -U, --username=USERNAME user name to connect as

  20. -w, --no-password never prompt for password

  21. -W, --password force password prompt

  22. --maintenance-db=DBNAME alternate maintenance database

复制

        等同于create database 语法,创建一个数据库,支持远程执行


3.createuser

  1. createuser creates a new PostgreSQL role.

  2. createuser [OPTION]... [ROLENAME]

  3. -c, --connection-limit=N connection limit for role (default: no limit)

  4. -d, --createdb role can create new databases

  5. -D, --no-createdb role cannot create databases (default)

  6. -e, --echo show the commands being sent to the server

  7. -g, --role=ROLE new role will be a member of this role

  8. -i, --inherit role inherits privileges of roles it is a

  9. member of (default)

  10. -I, --no-inherit role does not inherit privileges

  11. -l, --login role can login (default)

  12. -L, --no-login role cannot login

  13. -P, --pwprompt assign a password to new role

  14. -r, --createrole role can create new roles

  15. -R, --no-createrole role cannot create roles (default)

  16. -s, --superuser role will be superuser

  17. -S, --no-superuser role will not be superuser (default)

  18. -V, --version output version information, then exit

  19. --interactive prompt for missing role name and attributes rather

  20. than using defaults

  21. --replication role can initiate replication

  22. --no-replication role cannot initiate replication

  23. -?, --help show this help, then exit

  24. -h, --host=HOSTNAME database server host or socket directory

  25. -p, --port=PORT database server port

  26. -U, --username=USERNAME user name to connect as (not the one to create)

  27. -w, --no-password never prompt for password

  28. -W, --password force password prompt

复制

        相当于数据库中的create user 语法。支持远程执行


4.dropdb

  1. dropdb removes a PostgreSQL database.

  2. dropdb [OPTION]... DBNAME

  3. -e, --echo show the commands being sent to the server

  4. -f, --force try to terminate other connections before dropping

  5. -i, --interactive prompt before deleting anything

  6. -V, --version output version information, then exit

  7. --if-exists don't report error if database doesn't exist

  8. -?, --help show this help, then exit

  9. -h, --host=HOSTNAME database server host or socket directory

  10. -p, --port=PORT database server port

  11. -U, --username=USERNAME user name to connect as

  12. -w, --no-password never prompt for password

  13. -W, --password force password prompt

  14. --maintenance-db=DBNAME alternate maintenance database

复制

        相当于数据库中drop table database语法,支持远程执行


5.dropuser 

  1. dropuser removes a PostgreSQL role.

  2. dropuser [OPTION]... [ROLENAME]

  3. -e, --echo show the commands being sent to the server

  4. -i, --interactive prompt before deleting anything, and prompt for

  5. role name if not specified

  6. -V, --version output version information, then exit

  7. --if-exists don't report error if user doesn't exist

  8. -?, --help show this help, then exit

  9. -h, --host=HOSTNAME database server host or socket directory

  10. -p, --port=PORT database server port

  11. -U, --username=USERNAME user name to connect as (not the one to drop)

  12. -w, --no-password never prompt for password

  13. -W, --password force password prompt

复制

        相当于数据库中的drop  user 语法,支持远程执行 


6.ecpg

  1. ecpg is the PostgreSQL embedded SQL preprocessor for C programs.

  2. ecpg [OPTION]... FILE...

  3. -c automatically generate C code from embedded SQL code;

  4. this affects EXEC SQL TYPE

  5. -C MODE set compatibility mode; MODE can be one of

  6. "INFORMIX", "INFORMIX_SE", "ORACLE"

  7. -D SYMBOL define SYMBOL

  8. -h parse a header file, this option includes option "-c"

  9. -i parse system include files as well

  10. -I DIRECTORY search DIRECTORY for include files

  11. -o OUTFILE write result to OUTFILE

  12. -r OPTION specify run-time behavior; OPTION can be:

  13. "no_indicator", "prepare", "questionmarks"

  14. --regression run in regression testing mode

  15. -t turn on autocommit of transactions

  16. -V, --version output version information, then exit

  17. -?, --help show this help, then exit

复制

         ecpg是一个嵌入的用于 C 语言的 SQL 预编译器。 它把嵌有 SQL 语句的 C 程序通过将 SQL 调用替换成特殊的函数调用的方法转换成普通的 C 代码。 然后输出的文件就可以用任何 C 编译工具进行处理。这个指令在进行postgresql内核开发的时候比较重要。

        做个范例:

        创建测试表,插入测试数据。

  1. id SERIAL PRIMARY KEY,

  2. INSERT INTO employees (name, salary) VALUES

复制

         创建 example.ec 文件(C 代码):

  1. EXEC SQL BEGIN DECLARE SECTION;

  2. char conninfo[100] = "dbname=postgres user=postgres password=postgres";

  3. EXEC SQL END DECLARE SECTION;

  4. EXEC SQL CONNECT TO :conninfo;

  5. if (sqlca.sqlcode < 0) {

  6. fprintf(stderr, "Database connection error\n");

  7. EXEC SQL DECLARE cur CURSOR FOR SELECT name, salary FROM employees;

  8. if (sqlca.sqlcode < 0) {

  9. fprintf(stderr, "Error opening cursor\n");

  10. EXEC SQL FETCH cur INTO :name, :salary;

  11. if (SQLCODE == 100) break; // No more rows

  12. printf("Name: %s, Salary: %d\n", name, salary);

复制
  1. ##这将生成一个名为 example.c 的 C 代码文件。

  2. cc -o example example.c -I/usr/pgsql-14/include -lpq -lecpg

复制

        会输出显示所有员工的姓名和薪水。


7.initdb

         初始化一个新的 PostgreSQL 数据库簇(cluster)。也就是我们常说的一个数据库实例,仅支持本地初始化。


8.oid2name

         在 PostgreSQL 的较新版本,特别是在 PostgreSQL 12 之后的版本,OID(对象标识符)的使用方式发生了一些变化。OID 列默认不再是用户表的一部分,但仍然可能在某些系统表和特殊情况下使用。以下是 PostgreSQL 15.2 版本中 OID 可能用于标识的一些对象:

pg_class 表: pg_class 表存储了数据库中的所有表、索引、序列等的信息。oid唯一标识

pg_index 表: pg_index 表存储了索引的信息,包括索引的数据类型等。oid唯一标识

pg_constraint 表: pg_constraint 表存储了约束的信息,包括主键、外键等。oid唯一标识

pg_namespace 表: pg_namespace 表存储了数据库中的命名空间信息。oid唯一标识

pg_attrdef 表: pg_attrdef 表存储了表列的默认值信息。oid唯一标识

        以上的数据都会存储到磁盘的数据目录中去,并以oid作为文件名。

  1. postgres=# select pg_relation_filepath('form2_customer');

  2. [postgres@vm05 base]$ oid2name -f 24781

  3. From database "postgres":

  4. Filenode Table Name

  5. --------------------------

  6. 24781 form2_customer

复制

在数据库目录中可以通过oid2name去查看该文件的具体对应对象 ,执行远程查询


9.pg_amcheck

        该指令在PG14之后才有,pg_amcheck 仅仅 PostgreSQL 14.0 及更高版本配合使用。

        这个指令非常有用,常常用于检查数据库中索引损坏的排查

  1. pg_amcheck checks objects in a PostgreSQL database for corruption.

  2. pg_amcheck [OPTION]... [DBNAME]

  3. -a, --all check all databases

  4. -d, --database=PATTERN check matching database(s)

  5. -D, --exclude-database=PATTERN do NOT check matching database(s)

  6. -i, --index=PATTERN check matching index(es)

  7. -I, --exclude-index=PATTERN do NOT check matching index(es)

  8. -r, --relation=PATTERN check matching relation(s)

  9. -R, --exclude-relation=PATTERN do NOT check matching relation(s)

  10. -s, --schema=PATTERN check matching schema(s)

  11. -S, --exclude-schema=PATTERN do NOT check matching schema(s)

  12. -t, --table=PATTERN check matching table(s)

  13. -T, --exclude-table=PATTERN do NOT check matching table(s)

  14. --no-dependent-indexes do NOT expand list of relations to include indexes

  15. --no-dependent-toast do NOT expand list of relations to include TOAST tables

  16. --no-strict-names do NOT require patterns to match objects

  17. --exclude-toast-pointers do NOT follow relation TOAST pointers

  18. --on-error-stop stop checking at end of first corrupt page

  19. --skip=OPTION do NOT check "all-frozen" or "all-visible" blocks

  20. --startblock=BLOCK begin checking table(s) at the given block number

  21. --endblock=BLOCK check table(s) only up to the given block number

  22. B-tree index checking options:

  23. --heapallindexed check that all heap tuples are found within indexes

  24. --parent-check check index parent/child relationships

  25. --rootdescend search from root page to refind tuples

  26. -h, --host=HOSTNAME database server host or socket directory

  27. -p, --port=PORT database server port

  28. -U, --username=USERNAME user name to connect as

  29. -w, --no-password never prompt for password

  30. -W, --password force password prompt

  31. --maintenance-db=DBNAME alternate maintenance database

  32. -e, --echo show the commands being sent to the server

  33. -j, --jobs=NUM use this many concurrent connections to the server

  34. -P, --progress show progress information

  35. -v, --verbose write a lot of output

  36. -V, --version output version information, then exit

  37. --install-missing install missing extensions

  38. -?, --help show this help, then exit

复制
pg_amcheck -d <database_name> [options] table_name index_name
复制


10.pg_archivecleanup

         pg_archivecleanup 是 PostgreSQL 提供的一个用于清理归档日志文件的工具。归档日志(archive logs)是 PostgreSQL 中的事务日志,用于支持基于日志的流复制和点时间恢复。pg_archivecleanup 工具的主要作用是删除旧的归档日志文件,此工具与 PostgreSQL 的流复制设置一起使用,以确保备用服务器能够获取到所有需要的归档。同时释放主节点的磁盘空间。

  1. pg_archivecleanup removes older WAL files from PostgreSQL archives.

  2. pg_archivecleanup [OPTION]... ARCHIVELOCATION OLDESTKEPTWALFILE

  3. -d generate debug output (verbose mode)

  4. -n dry run, show the names of the files that would be removed

  5. -V, --version output version information, then exit

  6. -x EXT clean up files if they have this extension

  7. -?, --help show this help, then exit

  8. For use as archive_cleanup_command in postgresql.conf:

  9. archive_cleanup_command = 'pg_archivecleanup [OPTION]... ARCHIVELOCATION %r'

  10. archive_cleanup_command = 'pg_archivecleanup /mnt/server/archiverdir %r'

  11. Or for use as a standalone archive cleaner:

  12. pg_archivecleanup /mnt/server/archiverdir 000000010000000000000010.00000020.backup

复制

        可以植入到postgresql.conf中的archive_cleanup_command参数中去

 关键字解析:

%r:%r 会被替换为一个 32 位的十六进制数字,代表当前 PostgreSQL 服务器的最新复制位置。这确保了在清理归档日志时,只有早于当前复制位置的归档日志文件会被删除,而不会删除仍然需要进行复制的文件。

        
11.pg_basebackup

         常用的备份工具


12.pgbench

         数据库的压测工具,可以模拟多任务、多并发、多用户链接等测试。


13.pg_checksums

        用于管理 PostgreSQL 数据目录中的页校验和。页校验和是一种用于检测数据文件损坏的机制,它通过在文件的每个页面上存储一个校验和值,来确保读取和写入的数据的完整性。

        在使用时需要停库

  1. [postgres@vm05 bin]$ pg_checksums --enable $PGDATA

  2. Checksum operation completed

  3. Files scanned: 1752 --表示扫描的文件总数,这里是 PostgreSQL 数据目录下文件的数量

  4. Blocks scanned: 6247 --表示扫描的块总数,即扫描的文件中的页(block)的总数。

  5. Files written: 1316 --表示写入校验和的文件总数。这里是指在启用页校验和后,对文件进行了校验和写入的文件数量。

  6. Blocks written: 6247 --表示写入校验和的块总数。每个文件中的所有页都会被计算并写入校验和。

  7. pg_checksums: syncing data directory

  8. pg_checksums: updating control file

  9. Checksums enabled in cluster

  10. [postgres@vm05 bin]$ pg_checksums $PGDATA

  11. Checksum operation completed

  12. Files scanned: 1752 --表示扫描的文件总数,这里是 PostgreSQL 数据目录下文件的数量

  13. Blocks scanned: 6247 --表示扫描的块总数,即扫描的文件中的页(block)的总数。

  14. Bad checksums: 0 --表示发现的校验和错误数量。在这里是0,说明在扫描过程中没有发现校验和不匹配的块,即所有块的校验和都正确。

  15. Data checksum version: 1 --表示数据文件的校验和版本。在这里是1,表示使用的是版本1的校验和。校验和的版本可能因 PostgreSQL 的版本而有所不同。

  16. [postgres@vm05 bin]$ pg_checksums --disable

  17. pg_checksums: syncing data directory

  18. pg_checksums: updating control file

  19. Checksums disabled in cluster

  20. 上述返回值表示在扫描和启用页校验和的过程中,总共有1752个文件,6247个块被扫描,其中1316个文件的6247个块被写入了校验和。在这个过程中没有发现校验和错误,校验和的版本为1。

复制

        当第一次校验的时候需要加--enable参数,后面校验需要使用--disable 将其关掉,保持打开状态会在每次写入数据页时,都需要计算并存储校验和值。这会增加写入操作的开销。

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论