================psql元命令================
1 使用psql连接数据库,如果登录时添加-E 参数,就会把数据命令对应的SQL语句显示出来,这样方便了解命令的底层实现:
[postgres@otter3 pg12]$ /usr/local/pg12/bin/psql -E
psql (12.1)
Type "help" for help.
1.1 查看数据库列表,由于连接数据库时指定了参数-E,所以\l命令就会把SQL语句也列出来:
postgres=# \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
-----------+----------+----------+-------------+-------------+-----------------------
mydb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
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)
1.2 查看表空间列表:
postgres=# \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 |
(2 rows)
如果习惯带边框的表格输出可以使用命令:\pset border 2 设置
postgres=# \pset border 2
Border style is 2.
postgres=#
postgres=# \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 | |
+------------+----------+----------+
(2 rows)
1.3 先创建一个数据库tt
postgres=# create database tt;
CREATE DATABASE
连接数据tt用\c 命令:
postgres=# \c tt
You are now connected to database "tt" as user "postgres".
创建测试表company:
tt=# create table company(id int4,name varchar(30));
CREATE TABLE
查看tt库中的对象列表:
tt=# \d
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'partitioned table' WHEN 'I' THEN 'partitioned index' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','m','S','f','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
**************************
List of relations
+--------+---------+-------+----------+
| Schema | Name | Type | Owner |
+--------+---------+-------+----------+
| public | company | table | postgres |
+--------+---------+-------+----------+
(1 row)
给表company 添加主键:
tt=# alter table company add primary key(id);
ALTER TABLE
再次查看表company:
tt=# \d company
********* QUERY **********
SELECT c.oid,
n.nspname,
c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname OPERATOR(pg_catalog.~) '^(company)$' COLLATE pg_catalog.default
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3;
**************************
********* QUERY **********
SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, false AS relhasoids, c.relispartition, '', c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relpersistence, c.relreplident, am.amname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)
LEFT JOIN pg_catalog.pg_am am ON (c.relam = am.oid)
WHERE c.oid = '16396';
**************************
********* QUERY **********
SELECT a.attname,
pg_catalog.format_type(a.atttypid, a.atttypmod),
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid, true) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
a.attnotnull,
(SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t
WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation,
a.attidentity,
a.attgenerated
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = '16396' AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum;
**************************
********* QUERY **********
SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),
pg_catalog.pg_get_constraintdef(con.oid, true), contype, condeferrable, condeferred, i.indisreplident, c2.reltablespace
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))
WHERE c.oid = '16396' AND c.oid = i.indrelid AND i.indexrelid = c2.oid
ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname;
**************************
********* QUERY **********
SELECT pol.polname, pol.polpermissive,
CASE WHEN pol.polroles = '{0}' THEN NULL ELSE pg_catalog.array_to_string(array(select rolname from pg_catalog.pg_roles where oid = any (pol.polroles) order by 1),',') END,
pg_catalog.pg_get_expr(pol.polqual, pol.polrelid),
pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid),
CASE pol.polcmd
WHEN 'r' THEN 'SELECT'
WHEN 'a' THEN 'INSERT'
WHEN 'w' THEN 'UPDATE'
WHEN 'd' THEN 'DELETE'
END AS cmd
FROM pg_catalog.pg_policy pol
WHERE pol.polrelid = '16396' ORDER BY 1;
**************************
********* QUERY **********
SELECT oid, stxrelid::pg_catalog.regclass, stxnamespace::pg_catalog.regnamespace AS nsp, stxname,
(SELECT pg_catalog.string_agg(pg_catalog.quote_ident(attname),', ')
FROM pg_catalog.unnest(stxkeys) s(attnum)
JOIN pg_catalog.pg_attribute a ON (stxrelid = a.attrelid AND
a.attnum = s.attnum AND NOT attisdropped)) AS columns,
'd' = any(stxkind) AS ndist_enabled,
'f' = any(stxkind) AS deps_enabled,
'm' = any(stxkind) AS mcv_enabled
FROM pg_catalog.pg_statistic_ext stat WHERE stxrelid = '16396'
ORDER BY 1;
**************************
********* QUERY **********
SELECT pubname
FROM pg_catalog.pg_publication p
JOIN pg_catalog.pg_publication_rel pr ON p.oid = pr.prpubid
WHERE pr.prrelid = '16396'
UNION ALL
SELECT pubname
FROM pg_catalog.pg_publication p
WHERE p.puballtables AND pg_catalog.pg_relation_is_publishable('16396')
ORDER BY 1;
**************************
********* QUERY **********
SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND i.inhrelid = '16396' AND c.relkind != 'p' ORDER BY inhseqno;
**************************
********* QUERY **********
SELECT c.oid::pg_catalog.regclass, pg_catalog.pg_get_expr(c.relpartbound, c.oid), c.relkind FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhrelid AND i.inhparent = '16396' ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;
**************************
Table "public.company"
+--------+-----------------------+-----------+----------+---------+
| Column | Type | Collation | Nullable | Default |
+--------+-----------------------+-----------+----------+---------+
| id | integer | | not null | |
| name | character varying(30) | | | |
+--------+-----------------------+-----------+----------+---------+
Indexes:
"company_pkey" PRIMARY KEY, btree (id)
1.4 查看表、索引占用空间大小
先给测试表company 插入 1000000 测试数据:insert into company(id,name) select n,n||'_fances' from generate_series(1,1000000) n;
为了方便查看,不让输出sql语句可以设置:postgres=# \set ECHO_HIDDEN off
再次查看表大小执行\dt+表名称,即:
tt=# \dt+company
List of relations
+--------+---------+-------+----------+-------+-------------+
| Schema | Name | Type | Owner | Size | Description |
+--------+---------+-------+----------+-------+-------------+
| public | company | table | postgres | 50 MB | |
+--------+---------+-------+----------+-------+-------------+
(1 row)
1.5 查看索引大小执行\di+表名称,即:
tt=# \di+company
List of relations
+--------+--------------+-------+----------+---------+-------+-------------+
| Schema | Name | Type | Owner | Table | Size | Description |
+--------+--------------+-------+----------+---------+-------+-------------+
| public | company_pkey | index | postgres | company | 21 MB | |
+--------+--------------+-------+----------+---------+-------+-------------+
(1 row)
1.6 查看函数代码:
先定义一个函数
CREATE OR REPLACE PROCEDURE public.triple(INOUT x integer)
LANGUAGE plpgsql
AS $procedure$
BEGIN
x := x * 3;
END;
$procedure$
然后查看用命令:\sf triple 即:
tt=# \sf triple
CREATE OR REPLACE PROCEDURE public.triple(INOUT x integer)
LANGUAGE plpgsql
AS $procedure$
BEGIN
x := x * 3;
END;
$procedure$
1.7 \x设置查询结果输出:
使用\x可以设置查询结果输出模式,如下:
tt=# select * from company limit 1;
+----+----------+
| id | name |
+----+----------+
| 1 | 1_fances |
+----+----------+
(1 row)
tt=# \x
Expanded display is on.
tt=# select * from company limit 1;
+-[ RECORD 1 ]----+
| id | 1 |
| name | 1_fances |
+------+----------+
1.8 \? 这是查看所有元命令的帮助命令
1.9 \h 帮助文档命令,如想知道create index完整语法可以执行\h create index,即:
tt=# \h create index
Command: CREATE INDEX
Description: define a new index
Syntax:
CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON [ ONLY ] table_name [ USING method ]
( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
[ INCLUDE ( column_name [, ...] ) ]
[ WITH ( storage_parameter = value [, ... ] ) ]
[ TABLESPACE tablespace_name ]
[ WHERE predicate ]
URL: https://www.postgresql.org/docs/12/sql-createindex.html
================数据导入导出================
psql命令支持数据库表数据导出文件,也支持文件导入到数据库表,COPY 命令和 \copy命令都支持,但有区别
1、COPY 命令是SQL语句,\copy 是元命令
2、COPY 命令导出到文件时需要superuser权限,\copy 元命令不需superuser权限
3、COPY命令读取或写入是从数据库服务端主机上的文件,\copy 元命令是从psql客户端主机读取或写入文件
4、从性能方面来看,COPY 命令要比\copy 命令性能高(重点)
使用COPY命令导入导出数据
1.1 首先看看如何把文件中数据导入数据库表中
tt=# create table company_01(id int,name varchar(10));
CREATE TABLE
[root@otter3 scripts]# pwd
/data/pgdata/pg12/scripts
[root@otter3 scripts]# cat company_01.txt
1 a
2 b
3 c
注意:这里文本默认是TAB键,文件权限为postgres
tt=# COPY company_01 from '/data/pgdata/pg12/scripts/company_01.txt' ;
COPY 3
tt=# select * from company
company company_01
tt=# select * from company_01 ;
+----+------+
| id | name |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
+----+------+
(3 rows)
1.2 在用COPY 命令把数据库中的数据导出到文件
tt=# copy company_01 to '/data/pgdata/pg12/scripts/company_02.txt';
COPY 3
[postgres@otter3 scripts]$ cat company_02.txt
1 a
2 b
3 c
也可以从copy命令数据输出到标准输出:
tt=# copy company_01 to stdout;
1 a
2 b
3 c
1.3 导出csv格式
tt=# copy company_01 to '/data/pgdata/pg12/scripts/company_03.csv' with csv header;
COPY 3
[postgres@otter3 scripts]$ cat company_03.csv
id,name
1,a
2,b
3,c
带条件的导出:
tt=# copy (select * from company_01 where id = 3) to '/data/pgdata/pg12/scripts/company_04.csv' with csv header;
COPY 1
[postgres@otter3 scripts]$ cat company_04.csv
id,name
3,c
使用元命令\copy 导入导出数据:
首先我们用128 远程到130机器上操作,目的是把130上的数据导出到128客户端所在的机器上,操作如下:
root@otter1 ~ # psql -h 192.168.149.130 -p 1921 tt postgres
Password for user postgres:
psql (12.1)
Type "help" for help.
tt=# \copy company_01 to '/opt/tmp_data/company_01.txt';
COPY 3
root@otter1 tmp_data # pwd
/opt/tmp_data
root@otter1 tmp_data # cat company_01.txt
1 a
2 b
3 c
root@otter1 tmp_data #
导入:
a、准备文件
root@otter1 tmp_data # cat company_remote.txt
4 h
b、执行导入命令:
tt=# \copy company_01 from '/opt/tmp_data/company_remote.txt';
COPY 1
c、登录130服务器验证结果:
tt=# select * from company_01 ;
+----+------+
| id | name |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | h |
+----+------+
(4 rows)