1. 程式人生 > 實用技巧 >PG-客戶端工具

PG-客戶端工具

客戶端工具

  • pgAdmin 是一款功能豐富、開源免費的 PostgreSQL 圖形化客戶端工具

  • psql 是 PostgreSQL 自帶的命令列客戶端工具,功能全面

pgAdmin

pgAdmin 4 是一款專門針對PostgreSQL資料庫基於瀏覽器的BS架構的客戶端管理軟體。

pgAdmin軟體下載地址

適用文件

psql

用法

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 (default: "postgres")
  -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
                           (e.g., -v ON_ERROR_STOP=1)
  -V, --version            output version information, then exit
  -X, --no-psqlrc          do not read startup file (~/.psqlrc)
  -1 ("one"), --single-transaction
                           execute as a single transaction (if non-interactive)
  -?, --help[=options]     show this help, then exit
      --help=commands      list backslash commands, then exit
      --help=variables     list special variables, then exit

Input and output options:
  -a, --echo-all           echo all input from script
  -b, --echo-errors        echo failed commands
  -e, --echo-queries       echo commands sent to server
  -E, --echo-hidden        display queries that internal commands generate
  -L, --log-file=FILENAME  send session log to file
  -n, --no-readline        disable enhanced command line editing (readline)
  -o, --output=FILENAME    send query results to file (or |pipe)
  -q, --quiet              run quietly (no messages, only query output)
  -s, --single-step        single-step mode (confirm each query)
  -S, --single-line        single-line mode (end of line terminates SQL command)

Output format options:
  -A, --no-align           unaligned table output mode
      --csv                CSV (Comma-Separated Values) table output mode
  -F, --field-separator=STRING
                           field separator for unaligned output (default: "|")
  -H, --html               HTML table output mode
  -P, --pset=VAR[=ARG]     set printing option VAR to ARG (see \pset command)
  -R, --record-separator=STRING
                           record separator for unaligned output (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 for unaligned output to zero byte
  -0, --record-separator-zero
                           set record separator for unaligned output to zero byte

Connection options:
  -h, --host=HOSTNAME      database server host or socket directory (default: "local socket")
  -p, --port=PORT          database server port (default: "5432")
  -U, --username=USERNAME  database user name (default: "postgres")
  -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.

元命令

psql 中的元命令是指以反斜線開頭的命令 , psql 提供豐富 的元命令,能夠便捷地管理資料庫 , 比如檢視資料庫物件定義 、檢視資料庫物件 佔用空 間大小 、 列出資料庫各種物件名稱 、 資料導人匯出等。

檢視資料庫列表
10:37:12 [local]:5432 dev@devdb=> \l
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************

                                  List of databases
    Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
------------+----------+----------+-------------+-------------+-----------------------
 devdb      | dev      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres   | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 regression | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =Tc/postgres         +
            |          |          |             |             | postgres=CTc/postgres
 template0  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
 template1  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
(5 rows)

10:47:38 [local]:5432 dev@devdb=> 
\db 查看錶空間列表
10:47:38 [local]:5432 dev@devdb=> \db
********* QUERY **********
SELECT spcname AS "Name",
  pg_catalog.pg_get_userbyid(spcowner) AS "Owner",
  pg_catalog.pg_tablespace_location(oid) AS "Location"
FROM pg_catalog.pg_tablespace
ORDER BY 1;
**************************

                List of tablespaces
    Name    |  Owner   |          Location          
------------+----------+----------------------------
 devtbs     | postgres | /ups/data/pgdata/12/pg_usr
 pg_default | postgres | 
 pg_global  | postgres | 
(3 rows)

10:48:37 [local]:5432 dev@devdb=>
\x 設定查詢結果輸出

獲取元命令對應的 SQL 程式碼

psql 連線資料庫時,加上-E引數

psql -E

\watch 反覆執行當前 SQL
-- 每秒執行一次 now() 命令 
SELECT now();
\watch 1

執行SQL指令碼

-- 1. psql 的 -c 選項支援在作業系統層面通過 psql 向資料庫發起 SQL 命令
psql -c "SELECT current_user ;"
psql -At -c "SELECT current_user ;"

-- 輸出
[postgres@progs ~]$ psql -c "SELECT current_user ;"
 current_user 
--------------
 postgres
(1 row)

[postgres@progs ~]$ psql -At -c "SELECT current_user ;"
postgres
[postgres@progs ~]$

-- 2. -f 選項 通過 psql 向資料庫發起 SQL檔案命令
echo "SELECT current_user;" > t.sql
psql -f t.sql

傳遞變數

\set 元命令方式傳遞變數
10:57:48 [local]:5432 dev@devdb=> \set v_id 1
10:57:55 [local]:5432 dev@devdb=> select * from tb1 where id=:v_id;
 id | ival | description |             ctime             
----+------+-------------+-------------------------------
  1 |    1 |             | 2020-06-12 11:10:00.769246+08
(1 row)

10:58:10 [local]:5432 dev@devdb=> 

psql 的 -v 引數傳遞變數
echo "SELECT * FROM tb1 WHERE id=:v_id" > t.sql

[postgres@progs ~]$ psql -v v_id=1 devdb dev -f t.sql
 id | ival | description |             ctime             
----+------+-------------+-------------------------------
  1 |    1 |             | 2020-06-12 11:10:00.769246+08
(1 row)

[postgres@progs ~]$ 

維護指令碼

查詢活動會話
SELECT pid, usename , datname , query , client_addr
FROM pg_stat_activity
WHERE pid <> pg_backend_pid () AND state='active' 
ORDER BY query;

state程序的狀態值:

  • active : 後臺程序正在執行 SQL 。
  • idle :後臺程序為空 閒狀態,等待後續客戶端發出命令 。
  • idle in transaction : 後臺程序正在事務中,並不是指正在執行 SQL 。
  • idle in transaction (aborted):和 idle in transaction 狀態類似,只是事務中的部分SQL 異常 。

定製~/.psqlrc指令碼檔案,編輯如下內容

cat >> ~/.psqlrc <<-EOF
\set active_session 'select pid , usename , datname , query , client_addr from pg_stat_activity where pid <> pg_backend_pid () and state=\'active\' order by query;'
EOF

[postgres@progs ~]$ cat ~/.psqlrc 
\set active_session 'select pid , usename , datname , query , client_addr from pg_stat_activity where pid <> pg_backend_pid () and state=\'active\' order by query;'

# 登入資料庫執行 :active_session 命令
[postgres@progs ~]$ psql devdb dev
psql (12.0)
Type "help" for help.

devdb=> :active_session
 pid | usename | datname | query | client_addr 
-----+---------+---------+-------+-------------
(0 rows)

devdb=> exit

查詢等待事件
SELECT pid, usename, datname, query, client_addr, wait_event_type , wait_event
FROM pg_stat_activity
WHERE pid <> pg_backend_pid () AND wait_event is not null
ORDER BY wait_event_type;

定製~/.psqlrc指令碼檔案,編輯如下內容

cat >> ~/.psqlrc <<-EOF
\set wait_event 'SELECT pid, usename, datname, query, client_addr, wait_event_type, wait_event FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND wait_event is not null ORDER BY wait_event_type;'
EOF

客戶端提示符

psql 預設有三個提 示 符 : PROMPT1 、 PROMPT2 、 PROMPT3

  • PROMPT1 是指當 psql 等待新命令發出時的常規提示符,這個提示符使用得最多
  • PROMPT2 是指在命令輸入過程中等待更多輸入時發出的提示符, 例如當命令沒有使用分號終止或者
    引用沒有被關閉時就會發出這個提示符, PROMPT2 的預設設直值與 PROMPT1 一樣;
  • PROMPT3 指在執行一個 SQL COPY FROM STDIN 命令並且需要在終端上輸入一個行值時發出的提示符。
選項
  • %M :資料庫伺服器別名,不是指主機名,顯示的是 psql 的 -h 引數設定的值;當連
    接建立在 Unix 域套接字上時則是 [local]
  • %> :資料庫伺服器的埠號 。
  • %n :資料庫會話的使用者名稱,在資料庫會話期間,這個值可能會因為命令 SET
    SESSION AUTHORIZATION 的結果而改變 。
  • %/ :當前資料庫名稱。
  • %# :如果是超級使用者則顯示“#”,其他使用者顯示“>”,在資料庫會話期間,這個
    值可能會因為命令 SET SESSION AUTHORIZATION 的結果而改變 。
  • %p :當前資料庫連線的後臺程序號 。
  • %R :在 PROMPT1 中通常顯示“=”,如果程序被斷開則顯示“!” 。
  • %x: 指事務狀態–通常為空白,除非在事務語句塊中(*)
配置方式
臨時配置
-- 檢視當前配置 \echo :PROMPT1
11:24:50 [local]:5432 dev@devdb=> \echo :PROMPT1
%`date +%H:%M:%S` %M:%[%033[1;35m%]%>%[%033[0m%] %n@%/%R%#%x 
11:24:55 [local]:5432 dev@devdb=> 
                                       
-- 設定
\set PROMPT1 '%M%R%#'

檔案配置方式

vi ~/.psqlrc 新增以下內容

-- 登入提示符
--\set PROMPT1 '%n->%/@%M:%>%R%# '
\set PROMPT1 '%`date +%H:%M:%S` %M:%[%033[1;35m%]%>%[%033[0m%] %n@%/%R%#%x '
\set PROMPT2 '%M %n@%/%R%# '
-- 關鍵字大寫形式
\set COMP_KEYWORD_CASE upper