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 設置查詢結果輸出格式

類似mysql中的\G選項,按列輸出


獲取元命令對應的 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM