psql功能及应用

================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)

总结:上面说了\copy性能差,如果小表操作还可以,大表建议在服务器主机使用COPY命令,效率高。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容