第二章 psql客戶端工具
pgAdmin是一款功能豐富、開源免費的PostgreSQL圖形化工具。psql是PostgreSQL自帶的命令行工具,功能全面,是PostgreSQL數據庫工程師必須熟練掌握的命令行工具之一。
pgAdmin的下載網址是:https://www.pgadmin.org/download/
2.2 pgsql功能及應用
psql是PostgreSQL自帶的命令行客戶端工具,具有豐富的功能,類似於Oracle命令行客戶端工具sqlplus,這一節將介紹psql常用的功能和少數特殊功能。
熟練掌握psql能便捷處理PostgreSQL日常維護工作。
2.2.1 使用psql連接數據庫
用psql連接數據庫非常簡單,可以在數據庫服務端執行,也可以遠程連接數據庫,在數據庫服務端連接本地數據庫實例所示:
[postgres@fudao_db_cluster_003 ~]$ cat ~/.bash_profile # .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/bin:/opt/pgsql/bin export PATH [postgres@fudao_db_cluster_003 ~]$ [postgres@fudao_db_cluster_003 ~]$ psql postgres postgres psql (10.0) Type "help" for help. postgres=#
psql后面的第一個postgres表示庫名,第二個postgres表示用戶名,端口號默認使用變量$PGPORT配置的數據庫端口號,這里是1921端口,為了后續演示方便,創建一個測試庫mydb,
歸屬為用戶mydb庫分配一個新表空間tbs_mydb,如下所示:
-- 創建用戶 postgres=# CREATE ROLE pguser WITH ENCRYPTED PASSWORD 'pguser'; CREATE ROLE -- 創建表空間目錄 [postgres@fudao_db_cluster_003 ~]$ mkdir -p /data01/pgdata/10/pg_tbs/tbs_mydb -- 創建表空間 postgres=# CREATE TABLESPACE tbs_mydb OWNER pguser LOCATION '/data01/pgdata/10/pg_tbs/tbs_mydb'; CREATE TABLESPACE -- 創建數據庫 CREATE DATABASE mydb WITH OWNER = pguser TEMPLATE = template0 ENCODING = 'UTF8' TABLESPACE = 'tbs_mydb'; -- 賦權 GRANT ALL ON DATABASE mydb TO pguser WITH GRANT OPTION; GRANT ALL ON TABLESPACE tbs_mydb TO pguser; -- 查看角色 postgres=# select rolname from pg_roles; rolname ---------------------- pg_monitor pg_read_all_settings pg_read_all_stats pg_stat_scan_tables pg_signal_backend postgres pguser (7 rows) postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- pguser | Cannot login | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} postgres=# 授權登錄 postgres=# alter role pguser login; ALTER ROLE postgres=# \du
CREATE DATABASE 命令中的OWNER選項表示數據庫屬主,TEMPLATE表示數據庫模板,默認有template0和template1模板,也能自定義數據庫模板,ENCODING表示數據庫字符集,
這里設置成UTF8,TABLESPACE 表示數據庫的默認表空間,新建數據庫對象將默認創建在此表空間上,通過psql遠程連接數據庫的語法如下:
psql [option...] [dbname] [username]
服務器pghost1的IP為10.192.30.60, pghost2的IP為10.192.30.59,在pghost2主機上遠程連接pghost1的mydb的命令如下:
[postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser Password for user pguser: psql (10.0) Type "help" for help. mydb=>
2.2.2 psql元命令介紹
pgsql中的元命令是指以反斜杠開頭的命令,psql提供豐富的元命令,能夠便捷地管理數據庫,比如查看數據庫對象定義、查看數據庫對象占用空間大小,列出
數據庫各種對象名稱、數據導入導出等,比如查看數據庫列表,如下所示:
[postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser psql (10.0) Type "help" for help. mydb=> \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- mydb | pguser | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/pguser + | | | | | pguser=C*T*c*/pguser postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | 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 (4 rows) mydb=> 1. \db查看表空間列表 mydb=> \db List of tablespaces Name | Owner | Location ------------+----------+----------------------------------- pg_default | postgres | pg_global | postgres | tbs_mydb | pguser | /data01/pgdata/10/pg_tbs/tbs_mydb (3 rows) mydb=>
2. \d查看表定義
先創建一張測試表,如下所示:
mydb=> CREATE TABLE test_1(id int4, name text, create_time timestamp without time zone default clock_timestamp()); CREATE TABLE mydb=> ALTER TABLE test_1 ADD PRIMARY KEY (id); ALTER TABLE generate_series函數產生連續的整數,使用這個函數能非常方便地產生測試數據,查看表test_1定義只需要執行元命令\d后接表名,如下所示: postgres=# \d test_1 Table "public.test_1" Column | Type | Collation | Nullable | Default -------------+-----------------------------+-----------+----------+------------------- id | integer | | not null | name | text | | | create_time | timestamp without time zone | | | clock_timestamp() Indexes: "test_1_pkey" PRIMARY KEY, btree (id) mydb=>
3. 查看表、索引占用空間大小
給測試表test_1插入500w數據,如下所示:
mydb=> insert into test_1(id,name) select n,n || '_francs' from generate_series(1,5000000) n; 2019-06-26 16:29:47.498 CST [19689] LOG: checkpoints are occurring too frequently (25 seconds apart) 2019-06-26 16:29:47.498 CST [19689] HINT: Consider increasing the configuration parameter "max_wal_size". INSERT 0 5000000 mydb=> 查看表大小執行\dt+ 后接表名,如下所示: mydb=> \dt+ test_1 List of relations Schema | Name | Type | Owner | Size | Description --------+--------+-------+--------+--------+------------- public | test_1 | table | pguser | 287 MB | (1 row) 查看索引大小執行\di+ 后接索引名,如下所示: mydb=> \di+ test_1_pkey List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------------+-------+--------+--------+--------+------------- public | test_1_pkey | index | pguser | test_1 | 107 MB | (1 row)
4. \sf 查看函數代碼
5. \x 設置查詢結果輸出
mydb=> select * from test_1 limit 1; id | name | create_time ----+----------+---------------------------- 1 | 1_francs | 2019-06-26 16:32:36.100912 (1 row) mydb=> \x Expanded display is on. mydb=> select * from test_1 limit 1; -[ RECORD 1 ]--------------------------- id | 1 name | 1_francs create_time | 2019-06-26 16:32:36.100912 mydb=>
6. 獲取元數據對應的SQL代碼
psql提供的元命令實質上向數據庫發出相應的SQL查看,當使用psql連接數據庫時,-E選項可以獲取元命令的SQL代碼,如下所示:
[postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser -E Password for user pguser: psql (10.0) Type "help" for help. mydb=> \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 ------------+----------+----------------------------------- pg_default | postgres | pg_global | postgres | tbs_mydb | pguser | /data01/pgdata/10/pg_tbs/tbs_mydb (3 rows) mydb=>
7. \?
PostgreSQL支持的元命令很多,當忘記具體的元命令名稱時,可以查詢手冊,另一種便捷的方式是執行\?元命令列出所有的元命令,如下所示:
mydb=> \? General \copyright show PostgreSQL usage and distribution terms \crosstabview [COLUMNS] execute query and display results in crosstab \errverbose show most recent error message at maximum verbosity \g [FILE] or ; execute query (and send results to file or |pipe) \gexec execute query, then execute each value in its result \gset [PREFIX] execute query and store results in psql variables \gx [FILE] as \g, but forces expanded output mode \q quit psql \watch [SEC] execute query every SEC seconds Help \? [commands] show help on backslash commands \? options show help on psql command-line options \? variables show help on special variables \h [NAME] help on syntax of SQL commands, * for all commands ......
8. 便捷的HELP命令
psql的HELP命令非常方便,使用元命令\h后接SQL命令關鍵字能將SQL的語法列出,對日常的數據庫管理工作帶來極大的便利,例如:
mydb=> \h create tablespace Command: CREATE TABLESPACE Description: define a new tablespace Syntax: CREATE TABLESPACE tablespace_name [ OWNER { new_owner | CURRENT_USER | SESSION_USER } ] LOCATION 'directory' [ WITH ( tablespace_option = value [, ... ] ) ] mydb=>
2.2.3 psql導入、導出表數據
psql支持文件數據導入到數據,也支持數據表數據導出到文件中。COPY命令和\copy命令都支持這兩類操作,但兩者有如下區別:
1) COPY命令是SQL命令,\copy是元命令;
2) COPY命令必須具有SUPERUSER超級權限(將數據通過stdin、stuout方式導入導出情況外),而\copy元命令不需要SUPERUSER權限。
3) COPY命令讀取或寫入數據庫服務端主機上的文件,而\copy元命令是從psql客戶端主機上寫入文件。
4) 從性能方面看,大數據量導出到文件或大文件數據導入數據庫,COPY比、copy性能高。
1. 使用COPY命令導入導出數據
先來看看COPY命令如何將文件數據導入到數據表中,首先在mydb中創建測試表 test_copy,如下:
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 -U pguser -W -d mydb Password for user pguser: psql (10.0) Type "help" for help. mydb=> \d List of relations Schema | Name | Type | Owner --------+--------+-------+-------- public | test_1 | table | pguser (1 row) mydb=> CREATE TABLE test_copy(id int4, name text); CREATE TABLE mydb=>
之后編寫數據文件test_copy_in.txt,字段分隔符用TAB鍵,也可以設置其他分隔符,導入時再指定設置的字段分隔符。test_copy_in.txt文件如下所示:
[postgres@fudao_db_cluster_003 ~]$ cat /home/postgres/test_copy_in.txt 1,a 2,b 3,c
[postgres@fudao_db_cluster_002 ~]$
之后以postgres用戶登錄mydb庫,並將test_copy_in.txt文件中的數據導入到test_copy表中。導入命令如下:
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 -d mydb -U postgres Password for user postgres: psql (10.0) Type "help" for help. mydb=# copy public.test_copy from '/home/postgres/test_copy_in.txt' with csv; COPY 3 mydb=# select * from test_copy; id | name ----+------ 1 | a 2 | b 3 | c (3 rows)
# 使用普通用戶
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 mydb pguser Password for user pguser: psql (10.0) Type "help" for help. mydb=> copy public.test_copy from '/home/postgres/test_cpoy_in.txt'; ERROR: must be superuser to COPY to or from a file HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone. mydb=>
# 從遠程登錄看看
[postgres@fudao_db_cluster_002 ~]$ cat /home/postgres/test_copy_in.txt 1,a 2,b 3,c 4,d [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb pguser Password for user pguser: psql (10.0) Type "help" for help. mydb=> \dt List of relations Schema | Name | Type | Owner --------+-----------+-------+-------- public | test_1 | table | pguser public | test_copy | table | pguser (2 rows) mydb=> select * from test_copy; id | name ----+------ (0 rows) mydb=> copy test_copy from '/home/postgres/test_copy_in.txt' with csv; ERROR: must be superuser to COPY to or from a file HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone. mydb=> \copy test_copy from '/home/postgres/test_copy_in.txt' with csv; COPY 4 mydb=> select * from test_copy ; id | name ----+------ 1 | a 2 | b 3 | c 4 | d (4 rows)
# 使用postgres用戶遠程登錄,copy導出數據的文件,是在postgres數據的服務器端,不在客戶端機器上
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb postgres Password for user postgres: psql (10.0) Type "help" for help. mydb=# \dt List of relations Schema | Name | Type | Owner --------+-----------+-------+-------- public | test_1 | table | pguser public | test_copy | table | pguser (2 rows) mydb=# copy pguser.test_copy to '/tmp/test_copy_out.txt'; ERROR: schema "pguser" does not exist mydb=# copy public.test_copy to '/tmp/test_copy_out.txt'; COPY 4 mydb=# \! cat /tmp/test_copy_out.txt cat: /tmp/test_copy_out.txt: No such file or directory mydb=#
# 使用非postgres用戶登錄,是在本地產生
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb pguser Password for user pguser: psql (10.0) Type "help" for help. mydb=> copy public.test_copy to '/tmp/test_copy_out.txt'; ERROR: must be superuser to COPY to or from a file HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone. mydb=> \copy public.test_copy to '/tmp/test_copy_out.txt'; COPY 4 mydb=> \! cat /tmp/test_copy_out.txt 1 a 2 b 3 c 4 d mydb=> mydb=> truncate table test_copy mydb-> ; TRUNCATE TABLE mydb=> select * from test_copy ; id | name ----+------ (0 rows) mydb=> \copy test_copy from /tmp/test_copy_out.txt'; ERROR: unterminated quoted string at or near "';" LINE 1: COPY test_copy FROM STDIN '; ^ mydb=> \copy test_copy from '/tmp/test_copy_out.txt'; COPY 4 mydb=> select * from test_copy ; id | name ----+------ 1 | a 2 | b 3 | c 4 | d (4 rows) mydb=>
經常有運營或開發人員要求DBA提供生產庫的運營數據,為了顯示方便,這時需要將數據導出到csv格式。
[postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb postgres Password for user postgres: psql (10.0) Type "help" for help. mydb=# \dt List of relations Schema | Name | Type | Owner --------+-----------+-------+-------- public | test_1 | table | pguser public | test_copy | table | pguser (2 rows) mydb=# \copy public.test_copy to '/tmp/test_copy_out.csv' with csv header; COPY 4 mydb=# \! cat '/tmp/test_copy_out.csv' id,name 1,a 2,b 3,c 4,d mydb=#
上述命令中的with scv header是指導出格式為csv格式並且顯示字段名稱,以csv為后綴名的文件可以使用office execl打開。以上數據導出示例
都是基於全表數據導出的,如何僅導出表的一部分數據呢?如下代碼僅導出表test_copy中ID等於1的數據記錄。
mydb=# copy (select * from public.test_copy where id = 1) to '/tmp/1.txt'; COPY 1 mydb=# \! cat /tmp/1.txt 1 a mydb=#
2. 使用copy元命令導入導出數據
COPY命令是從數據庫服務端主機讀取或寫入文件數據,而\copy元命令從psql用客戶端主機讀取或寫入文件數據。並且\copy元命令不需要超級用戶權限。
下面在pghost2中以普通用戶pguser遠程登錄pghost1主機上的mydb庫,並且使用\copy元命令導出text_copy數據。如下:
mydb=> \copy test_copy to '/tmp/2_test_copy.dump.txt'; COPY 4 mydb=> \! cat /tmp/2_test_copy.dump.txt 1 a 2 b 3 c 4 d mydb=> [postgres@fudao_db_cluster_002 tmp]$ cat 3_test_copy.dump.txt 1 a 2 b 3 c 4 d 5 e 6 f 7 h [postgres@fudao_db_cluster_002 tmp]$ mydb=> select * from test_copy ; id | name ----+------ 1 | a 2 | b 3 | c 4 | d (4 rows) mydb=> \copy test_copy from '/tmp/3_test_copy.dump.txt'; COPY 7 mydb=> mydb=> select * from test_copy ; id | name ----+------ 1 | a 2 | b 3 | c 4 | d 1 | a 2 | b 3 | c 4 | d 5 | e 6 | f 7 | h (11 rows)
沒有超級用戶權限的情況下,需要導出小表,通常使用\copy元命令。如果是大表導入導出,建議在數據庫服務器端主機使用copy命令,效率更好
2.2.4 psql的語法和選項介紹
psql連接數據庫語法如下:
psql [OPTION]... [DBNAME [USERNAME]]
其中dbname指連接的數據庫名稱,username指登錄數據庫的用戶名,option有很多參數選項,這節列出重要的參數選項。
1. -A設置非對齊輸出模式
psql執行SQL的輸出默認是對齊模式,例如:
[postgres@fudao_db_cluster_003 ~]$ psql -c "select * from test_copy where id=1" mydb pguser id | name ----+------ 1 | a (1 row) [postgres@fudao_db_cluster_003 ~]$
注意以上輸出,格式是對齊的,psql加上-A選項如下:
[postgres@fudao_db_cluster_003 ~]$ psql -A -c "select * from test_copy where id=1" mydb pguser id|name 1|a (1 row) [postgres@fudao_db_cluster_003 ~]$
加上-A選項后,以上輸出的格式變成不對齊的了,並且返回結果中沒有空行,接着看-t選項。
2. -t只顯示記錄數據
另一個psql重要選項參數為-t,-t參數設置輸出只顯示數據,而不顯示字段名稱和返回的結果集行數,如下所示:
[postgres@fudao_db_cluster_003 ~]$ psql -t -c "select * from test_copy where id=1" mydb pguser 1 | a [postgres@fudao_db_cluster_003 ~]$
注意以上結果,字段名稱不再顯示,返回的結果行數也沒有顯示,但尾部仍然有空行,因此-t參數通常和-A參數結合使用,
這時金返回數據本身,如下所示:
[postgres@fudao_db_cluster_003 ~]$ psql -At -c "select * from test_copy where id=1" mydb pguser 1|a [postgres@fudao_db_cluster_003 ~]$
以上結果進返回了數據本身,在編寫shell腳本時非常有效,特別是只取一個字段的時候,如下所示:
[postgres@fudao_db_cluster_003 ~]$ psql -At -c "select name from test_copy where id=1" mydb pguser a [postgres@fudao_db_cluster_003 ~]$
3. -q不顯示輸出信息
默認情況下,使用psql執行SQL命令時會返回多種消息,使用-q參數后將不再顯示這些信息,下面通過一個例子進行演示,首先創建 test_q.sql。
並輸入一下SQL:
[postgres@fudao_db_cluster_003 ~]$ psql mydb -f /tmp/test_q.sql DROP TABLE CREATE TABLE TRUNCATE TABLE INSERT 0 1 INSERT 0 1 [postgres@fudao_db_cluster_003 ~]$
執行腳本后,返回了一對消息,加上-q參數后,這些信息不再顯示了。
[postgres@fudao_db_cluster_003 ~]$ psql -q mydb -f /tmp/test_q.sql [postgres@fudao_db_cluster_003 ~]$
-q選項通常和-c或-f選項使用,在執行維護操作過程中,當輸出信息不重要時,這個特性非常重要。
2.2.5 psql執行sql腳本
psql的-c選項支持在操作系統層面通過psql向數據庫發起SQL命令,如下所示:
[postgres@fudao_db_cluster_003 ~]$ psql -c "select * from test_copy" mydb id | name ----+------ 1 | a 2 | b 3 | c 4 | d 5 | e 6 | f 7 | h (7 rows) [postgres@fudao_db_cluster_003 ~]$
-c選項后接執行的SQL命令,可以使用單引號或者雙引號,同時支持格式化輸出,如果想僅僅顯示命令返回的結果,psql加上-At選項即可。
[postgres@fudao_db_cluster_003 ~]$ psql -At -c "select * from test_copy" mydb 1|a 2|b 3|c 4|d 5|e 6|f 7|h [postgres@fudao_db_cluster_003 ~]$
上述內容演示了在操作系統層面通過psql執行SQL命令,那么如何導入數據庫腳文件了?首先編寫一下文件,文件名稱為test_1.sql
[postgres@fudao_db_cluster_003 ~]$ cat /tmp/test_2.sql CREATE TABLE test_2(id int4); INSERT INTO test_2 VALUES(1); INSERT INTO test_2 VALUES(2); INSERT INTO test_2 VALUES(3); [postgres@fudao_db_cluster_003 ~]$
通過-f參數導入次腳本,命令如下:
[postgres@fudao_db_cluster_003 ~]$ psql mydb pguser -f /tmp/test_2.sql CREATE TABLE INSERT 0 1 INSERT 0 1 INSERT 0 1 [postgres@fudao_db_cluster_003 ~]$
以上命令的輸出結果沒有報錯,表示文件中所有的SQL正常導入。psql的 --single-transaction或-l選項支持在一個事務中執行腳本,要么腳本中的所有
SQL執行成功,如果其中有SQL執行失敗,則文件中的所有SQL。
2.2.6 psql如何傳遞變量到SQL
如何通過psql工具將變量傳遞到SQL中,例如以下SQL:
SELECT * FROM test_name WHERE clumn_name = '變量';
下面演示兩種傳遞變量的方式。
1. \set 元命令方式傳遞變量
\set 元子命令可以設置變量,格式如下:name表示變量名稱,value表示變量值,如果不填寫value,變量值為空。
mydb=> \set v_id 2 mydb=> select * from test_copy where id=:v_id; id | name ----+------ 2 | b (1 row)
如果想取消之前的變量的值,\set 命令后跟參數名稱即可。
mydb=> \set v_id
通過\set 元命令設置變量的一個典型應用場景是使用pgbench進行壓測時使用\set元命令為變量賦值。
2. psql的-v參數傳遞變量
另一種方式是通過psql的-v參數傳遞變量,首先編寫select_1.sql腳本,腳本內容如下:
[postgres@fudao_db_cluster_003 ~]$ cat select_1.sql select * from test_copy where id=:v_id ; [postgres@fudao_db_cluster_003 ~]$ [postgres@fudao_db_cluster_003 ~]$ psql mydb pguser -v v_id=1 -f /home/postgres/select_1.sql id | name ----+------ 1 | a (1 row) [postgres@fudao_db_cluster_003 ~]$ 以上設置變量v_id值為1。