关于PostgreSQL 10下psql元命令的使用方法及示例

作者:瀚高PG实验室 (Highgo PG Lab)- 徐云鹤

本文章介绍了关于PG 10下psql元命令的使用方法及示例

General
通用
\copyright show PostgreSQL usage and distribution terms
显示PostgreSQL的版权以及发布条款

postgres=# \copyright 
PostgreSQL Database Management System
(formerly known as Postgres, then as Postgres95)

Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group

Portions Copyright (c) 1994, The Regents of the University of California

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose, without fee, and without a written agreement
is hereby granted, provided that the above copyright notice and this
paragraph and the following two paragraphs appear in all copies.

IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

\crosstabview [COLUMNS] execute query and display results in crosstab
执行当前的查询缓冲区(像\g那样)并且在一个交叉表格子中显示结果。该查询必须返回至少三列。
\errverbose show most recent error message at maximum verbosity
以最详细的程度显示最近的服务器错误消息

postgres=# \errverbose
ERROR:  22021: invalid byte sequence for encoding "UTF8": 0xb8
LOCATION:  report_invalid_encoding, wchar.c:2017

\g [FILE] or ; execute query (and send results to file or |pipe)
执行查询(并将结果发送到文件或管道)

postgres=# select * from abcd; \g /tmp/a.txt
 a | b | c | d 
---+---+---+---
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
(7 rows)
[root@db1 ~]# tail -f /tmp/a.txt
---+---+---+---
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
 1 | 2 | 3 | 4
(7 rows)

\gexec execute query, then execute each value in its result
执行查询,然后在结果中执行每个值

postgres=# insert into abcd select * from abcd; \gexec
INSERT 0 7
INSERT 0 14
postgres=# select count(*) from abcd;
 count 
-------
    28
(1 row)

\gset [PREFIX] execute query and store results in psql variables
执行查询并将结果存储在psql变量中

postgres=# select count(*) from abcd;\gset
 count 
-------
    28
(1 row)

postgres=# \echo :count 
28

\gx [FILE] as \g, but forces expanded output mode
类似\g,但是展开了输出模式

postgres=# select * from abc;\gx /tmp/a.txt
 int 
-----
   1
   2
   3
   3
   3
   3
   3
(7 rows)
[root@db1 ~]# cat /tmp/a.txt 
-[ RECORD 1 ]
int | 1
-[ RECORD 2 ]
int | 2
-[ RECORD 3 ]
int | 3
-[ RECORD 4 ]
int | 3
-[ RECORD 5 ]
int | 3
-[ RECORD 6 ]
int | 3
-[ RECORD 7 ]
int | 3

\q quit psql
退出psql
\watch [SEC] execute query every SEC seconds
每SEC秒执行查询,默认2s

postgres=# select * from abc;\watch 1
 int 
-----
   1
   2
   3
   3
   3
   3
   3
(7 rows)

Mon 13 Nov 2017 04:24:57 PM CST (every 1s)

 int 
-----
   1
   2
   3
   3
   3
   3
   3
(7 rows)

Mon 13 Nov 2017 04:24:58 PM CST (every 1s)

Help
帮助
? [commands] show help on backslash commands
显示反斜杠命令的帮助

postgres=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab...

? options show help on psql command-line options
显示有关psql命令行选项的帮助

postgres=# \? options
psql is the PostgreSQL interactive terminal.

Usage:
  psql [OPTION]... [DBNAME [USERNAME]]....

? variables show help on special variables
显示专用变量的帮助

postgres=# \? variables
List of specially treated variables
psql variables:....

\h [NAME] help on syntax of SQL commands, * for all commands
显示SQL命令的语法帮助,*为所有命令

postgres=# \h select
Command:     SELECT
Description: retrieve rows from a table or view...

Query Buffer
查询缓冲区

\e [FILE] [LINE] edit the query buffer (or file) with external editor
用外部编辑器编辑查询缓冲区(或文件)

postgres=# \e
select * from abc;
postgres=# \e /tmp/a.txt
-[ RECORD 1 ]
int | 1

\ef [FUNCNAME [LINE]] edit function definition with external editor
使用外部编辑器编辑function定义

postgres=# \ef 
CREATE FUNCTION ( )
 RETURNS
 LANGUAGE
 -- common options:  IMMUTABLE  STABLE  STRICT  SECURITY DEFINER
AS $function$

$function$

\ev [VIEWNAME [LINE]] edit view definition with external editor
使用外部编辑器编辑view定义

postgres-# \ev v_abc
CREATE OR REPLACE VIEW public.v_abc AS
 SELECT abc."int"
   FROM abc

\p show the contents of the query buffer
显示查询缓冲区的内容

postgres=# select * from v_abc;
 int 
-----
   1
   2
   3
   3
   3
   3
   3
(7 rows)   
postgres=# 
postgres=# \p
select * from v_abc;

\r reset (clear) the query buffer
重置(清除)查询缓冲区

postgres=# \r
Query buffer reset (cleared).

\s [FILE] display history or save it to file
显示历史记录或将其保存到文件

postgres=# \s
\?
\copyright
\crosstabview
create table abc(int int);....
postgres=# \s /tmp/log.log
Wrote history to file "/tmp/log.log".

\w FILE write query buffer to file
将查询缓冲区写入文件

postgres=# \p
select * from v_abc;
postgres=# \w /tmp/buf.log
postgres=# \! cat /tmp/buf.log
select * from v_abc;

Input/Output
输入/输出

\copy … perform SQL COPY with data stream to the client host
用数据流执行SQL COPY到客户端主机
完整使用语法
\copy { table [ ( column_list ) ] | ( query ) } { from | to } { ‘filename’ | program ‘command’ | stdin | stdout | pstdin | pstdout } [ [ with ] ( option [, …] ) ]

postgres=# \copy abc to /tmp/tableabc.txt
COPY 7
postgres=#  \! cat /tmp/tableabc.txt
1
2
3
3
3
3
3

\echo [STRING] write string to standard output
把字符打印到标准输出

postgres=# \echo `date` 星期二 晴    
Wed Nov 15 10:41:11 CST 2017 星期二 晴

\i FILE execute commands from file
从文件执行命令

postgres=# \! cat /tmp/sql.sql
select version();

postgres=# \i /tmp/sql.sql
                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18), 64-bit
(1 row)

\ir FILE as \i, but relative to location of current script
\ir命令类似于\i,但是以不同的方式处理相对路径文件名。在交互模式中执行时,这两个命令的行为相同。不过,当被从脚本中调用时,\ir相对于脚本所在的目录而不是根据当前工作目录来解释文件名。
\o [FILE] send all query results to file or |pipe
将所有查询结果发送到文件或管道

postgres=# \o /tmp/sql.log
postgres=# \i  sql.sql
postgres=# \i  sql.sql
postgres=# \o
postgres=# \i  sql.sql
                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18), 64-bit
(1 row)
postgres=# \! cat /tmp/sql.log
                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18), 64-bit
(1 row)

                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18), 64-bit
(1 row)

\qecho [STRING] write string to query output stream (see \o)
类似echo,将输出结果发送到文件或管道

postgres=# \o /tmp/test.log
postgres=# \qecho -----------
postgres=# \o
postgres=# \qecho -----------
-----------
postgres=# \! cat /tmp/test.log
-----------

Conditional
条件

\if EXPR begin conditional block
开始带条件的块
\elif EXPR alternative within current conditional block
在当前条件块内替代
\else final alternative within current conditional block
在当前的条件块内的最终替代
\endif end conditional block
结束带条件的块

postgres=# \! cat /tmp/ba.sql
SELECT
                   EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer,
                   EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee
               \gset
               \if :is_customer
                   SELECT * FROM customer WHERE customer_id = 123;
               \elif :is_employee
                   \echo 'is not a customer but is an employee'
                   SELECT * FROM employee WHERE employee_id = 456;
               \else
                   \if yes
                       \echo 'not a customer or employee'
                   \else
                       \echo 'this will never print'
                   \endif
               \endif
postgres=#  \i /tmp/ba.sql
is not a customer but is an employee
 employee_id 
-------------
         456
(1 row)

Informational
信息

(options: S = show system objects, + = additional detail)
(选项:S =显示系统对象,+ =附加的详细信息)
\d[S+] list tables, views, and sequences
列举表格视图和序列

postgres=# \d
          List of relations
 Schema |   Name   | Type  |  Owner   
--------+----------+-------+----------
 public | aaa      | table | postgres
 public | abc      | table | postgres
 public | abcd     | table | postgres
 public | customer | table | postgres
 public | employee | table | postgres
 public | v_abc    | view  | postgres
(6 rows)

postgres=# \d+
                        List of relations
 Schema |   Name   | Type  |  Owner   |    Size    | Description 
--------+----------+-------+----------+------------+-------------
 public | aaa      | table | postgres | 0 bytes    | 
 public | abc      | table | postgres | 8192 bytes | 
 public | abcd     | table | postgres | 8192 bytes | 
 public | customer | table | postgres | 8192 bytes | 
 public | employee | table | postgres | 8192 bytes | 
 public | v_abc    | view  | postgres | 0 bytes    | 
(6 rows)

postgres=# \dS
                        List of relations
   Schema   |              Name               | Type  |  Owner   
------------+---------------------------------+-------+----------
 pg_catalog | pg_aggregate                    | table | postgres
 pg_catalog | pg_am                           | table | postgres
 pg_catalog | pg_amop                         | table | postgres....

\d[S+] NAME describe table, view, sequence, or index
表格视图和序列的描述信息

postgres=# \dS+ v_abc
                            View "public.v_abc"
 Column |  Type   | Collation | Nullable | Default | Storage | Description 
--------+---------+-----------+----------+---------+---------+-------------
 int    | integer |           |          |         | plain   | 
View definition:
 SELECT abc."int"
   FROM abc;

\da[S] [PATTERN] list aggregates
列出聚集函数

postgres=# \daS count
                                                  List of aggregate functions
   Schema   | Name  | Result data type | Argument data types |                           Description                           
------------+-------+------------------+---------------------+-----------------------------------------------------------------
 pg_catalog | count | bigint           | *                   | number of input rows
 pg_catalog | count | bigint           | "any"               | number of input rows for which the input expression is not null
(2 rows)

\dA[+] [PATTERN] list access methods
列出访问方法

postgres=# \dA+
                        List of access methods
  Name  | Type  |   Handler   |              Description               
--------+-------+-------------+----------------------------------------
 brin   | Index | brinhandler | block range index (BRIN) access method
 btree  | Index | bthandler   | b-tree index access method
 gin    | Index | ginhandler  | GIN index access method
 gist   | Index | gisthandler | GiST index access method
 hash   | Index | hashhandler | hash index access method
 spgist | Index | spghandler  | SP-GiST index access method
(6 rows)

\db[+] [PATTERN] list tablespaces
列出表空间

  postgres=# \db
       List of tablespaces
    Name    |  Owner   | Location 
------------+----------+----------
 pg_default | postgres | 
 pg_global  | postgres | 
(2 rows)

\dc[S+] [PATTERN] list conversions
列出字符集编码之间的转换。

postgres=# \dcS
                                   List of conversions
   Schema   |              Name              |     Source     |  Destination   | Default? 
------------+--------------------------------+----------------+----------------+----------
 pg_catalog | ascii_to_mic                   | SQL_ASCII      | MULE_INTERNAL  | yes
 pg_catalog | ascii_to_utf8                  | SQL_ASCII      | UTF8           | yes
 pg_catalog | big5_to_euc_tw                 | BIG5           | EUC_TW         | yes

\dC[+] [PATTERN] list casts
列出类型转换

postgres=# \dC
                                         List of casts
         Source type         |         Target type         |      Function      |   Implicit?   
-----------------------------+-----------------------------+--------------------+---------------
 abstime                     | date                        | date               | in assignment
 abstime                     | integer                     | (binary coercible) | no
 abstime                     | timestamp without time zone | timestamp          | yes...

\dd[S] [PATTERN] show object descriptions not displayed elsewhere
显示约束、操作符类、操作符族、规则以及触发器类型对象的描述。
\dD[S+] [PATTERN] list domains
列出域。

  postgres=# \dD
                                                          List of domains
 Schema |      Name      | Type | Collation | Nullable | Default |                              Check                               
--------+----------------+------+-----------+----------+---------+------------------------------------------------------------------
 public | us_postal_code | text |           |          |         | CHECK (VALUE ~ '^\d{5}$'::text OR VALUE ~ '^\d{5}-\d{4}$'::text)
(1 row)

\ddp [PATTERN] list default privileges
列出默认的访问特权设置。

postgres=# \ddp
           Default access privileges
  Owner   | Schema | Type  | Access privileges 
----------+--------+-------+-------------------
 postgres | public | table | =r/postgres
(1 row)

\dE[S+] [PATTERN] list foreign tables
列出外部表。
\det[+] [PATTERN] list foreign tables
列出外部表。
\des[+] [PATTERN] list foreign servers
列出外部服务器。
\deu[+] [PATTERN] list user mappings
列出用户映射。
\dew[+] [PATTERN] list foreign-data wrappers
列出外部数据包装器。
\df[antw][S+] [PATRN] list [only agg/normal/trigger/window] functions
列出函数,以及它们的结果数据类型、参数数据类型和函数类型,函数类型被分为"agg"(聚集)、“normal”、“trigger"以及"window”。

postgres=# \df
                        List of functions
 Schema | Name  | Result data type | Argument data types |  Type  
--------+-------+------------------+---------------------+--------
 public | add   | integer          | integer, integer    | normal
 public | addd  | text             |                     | normal
 public | adddd | void             |                     | normal
(3 rows)

\dF[+] [PATTERN] list text search configurations
列出文本搜索配置。

postgres=# \dF
               List of text search configurations
   Schema   |    Name    |              Description              
------------+------------+---------------------------------------
 pg_catalog | danish     | configuration for danish language
 pg_catalog | dutch      | configuration for dutch language
 pg_catalog | english    | configuration for english language
 pg_catalog | finnish    | configuration for finnish language...

\dFd[+] [PATTERN] list text search dictionaries
列出文本搜索字典。

postgres=# \dFd
                             List of text search dictionaries
   Schema   |      Name       |                        Description                        
------------+-----------------+-----------------------------------------------------------
 pg_catalog | danish_stem     | snowball stemmer for danish language
 pg_catalog | dutch_stem      | snowball stemmer for dutch language
 pg_catalog | english_stem    | snowball stemmer for english language

\dFp[+] [PATTERN] list text search parsers
列出文本搜索解析器。

postgres=# \dFp
        List of text search parsers
   Schema   |  Name   |     Description     
------------+---------+---------------------
 pg_catalog | default | default word parser
(1 row)

\dFt[+] [PATTERN] list text search templates
列出文本搜索模板。

postgres=# \dFt
                           List of text search templates
   Schema   |   Name    |                        Description                        
------------+-----------+-----------------------------------------------------------
 pg_catalog | ispell    | ispell dictionary
 pg_catalog | simple    | simple dictionary...

\dg[S+] [PATTERN] list roles
列出数据库角色,等同于与\du。

  postgres=# \dg
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

\di[S+] [PATTERN] list indexes
列出索引。

postgres=# \di
                 List of relations
 Schema |     Name      | Type  |  Owner   | Table 
--------+---------------+-------+----------+-------
 public | unique_abc_id | index | postgres | abc
(1 row)

\dl list large objects, same as \lo_list
这是\lo_list的一个别名,它显示大对象的列表。
\dL[S+] [PATTERN] list procedural languages
列出过程语言。

postgres=# \dL
                      List of languages
  Name   |  Owner   | Trusted |         Description          
---------+----------+---------+------------------------------
 plpgsql | postgres | t       | PL/pgSQL procedural language
(1 row)

\dm[S+] [PATTERN] list materialized views
列出物化视图。
\dn[S+] [PATTERN] list schemas
列出模式。

  postgres=# \dn
  List of schemas
  Name  |  Owner   
--------+----------
 public | postgres
(1 row)

\do[S] [PATTERN] list operators
列出操作符及其操作数和结果类型。
\dO[S+] [PATTERN] list collations
列出排序规则。
\dp [PATTERN] list table, view, and sequence access privileges
列出表、视图和序列,包括与它们相关的访问特权。

  postgres=# \dp
                                  Access privileges
 Schema |   Name   | Type  |     Access privileges     | Column privileges | Policies 
--------+----------+-------+---------------------------+-------------------+----------
 public | aaa      | table |  ...

\drds [PATRN1 [PATRN2]] list per-database role settings
列出已定义的配置设置。
\dRp[+] [PATTERN] list replication publications
列出复制发布。
\dRs[+] [PATTERN] list replication subscriptions
列出复制订阅。
\ds[S+] [PATTERN] list sequences
列出序列。
\dt[S+] [PATTERN] list tables
列出表。

  postgres=# \dt
          List of relations
 Schema |   Name   | Type  |  Owner   
--------+----------+-------+----------
 public | aaa      | table | postgres
 public | abc      | table | postgres

\dT[S+] [PATTERN] list data types
列出数据类型。

  postgres=# \dT
          List of data types
 Schema |      Name      | Description 
--------+----------------+-------------
 public | us_postal_code | 
(1 row)

\du[S+] [PATTERN] list roles
列出数据库角色

  postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

\dv[S+] [PATTERN] list views
列出视图。

  postgres=# \dv
        List of relations
 Schema | Name  | Type |  Owner   
--------+-------+------+----------
 public | v_abc | view | postgres
(1 row)

\dx[+] [PATTERN] list extensions
列出已安装的扩展。

  postgres=# \dx
                        List of installed extensions
   Name    | Version |   Schema   |               Description               
-----------+---------+------------+-----------------------------------------
 adminpack | 1.0     | pg_catalog | administrative functions for PostgreSQL
 plpgsql   | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)

\dy [PATTERN] list event triggers
列出事件触发器。
\l[+] [PATTERN] list databases
列出数据库

  postgres=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges   
-----------+----------+----------+------------+------------+-----------------------
 db1       | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |...

\sf[+] FUNCNAME show a function’s definition
显示函数定义

  postgres=# \sf add
CREATE OR REPLACE FUNCTION public.add(integer, integer)
 RETURNS integer
 LANGUAGE sql
 IMMUTABLE STRICT
AS $function$select $1 + $2;$function$

\sv[+] VIEWNAME show a view’s definition
显示视图定义

  postgres=# \sv v_abc
CREATE OR REPLACE VIEW public.v_abc AS
 SELECT abc."int"
   FROM abc

\z [PATTERN] same as \dp
列出表、视图和序列,包括与它们相关的访问特权。同\dp

postgres=# \z
                                  Access privileges
 Schema |   Name   | Type  |     Access privileges     | Column privileges | Policies 
--------+----------+-------+---------------------------+-------------------+----------
 public | aaa      | table |                           |                   | 
 public | abc      | table |                           |    ...

Formatting
格式化

\a toggle between unaligned and aligned output mode
在未对齐和对齐的输出模式之间切换

postgres=# select * from abcde;
int|int2
1|
|2
(2 rows)
postgres=# \a
Output format is aligned.
postgres=# select * from abcde;
 int | int2 
-----+------
   1 |     
     |    2
(2 rows)

\C [STRING] set table title, or unset if none
设置查询结果的任何表的标题,或者重置这类标题。

postgres=# \C nice
Title is "nice".
postgres=# select * from abcde;
    nice
 int | int2 
-----+------
   1 |     
     |    2
(2 rows)

\f [STRING] show or set field separator for unaligned query output
设置用于非对齐查询输出的域分隔符。

postgres=# \f *
Field separator is "*".
postgres=# select * from abcde;
nice
int*int2
1*
*2
(2 rows)

\H toggle HTML output mode (currently off)
开启HTML查询输出格式。

postgres=# \H
Output format is html.
postgres=# select * from abcde;
<table border="1">
  <caption>nice</caption>
  <tr>
    <th align="center">int</th>
    <th align="center">int2</th>
  </tr>
  <tr valign="top">
    <td align="right">1</td>
    <td align="right">&nbsp; </td>
  </tr>
  <tr valign="top">
    <td align="right">&nbsp; </td>
    <td align="right">2</td>
  </tr>
</table>
<p>(2 rows)<br />
</p>

\pset [NAME [VALUE]] set table output option
设置影响查询结果表输出的选项。
(NAME := {border|columns|expanded|fieldsep|fieldsep_zero|
footer|format|linestyle|null|numericlocale|pager|
pager_min_lines|recordsep|recordsep_zero|tableattr|title|
tuples_only|unicode_border_linestyle|
unicode_column_linestyle|unicode_header_linestyle})

border
value必须是一个数字。通常,数字越大,表格就会有更多的边框和线条,但具体要看是哪一种格式。在HTML格式中,这会直接被转换成border=…属性。在大部分其他格式中,只有值 0(没有边框)、1(内部分隔线)和 2(表格边框)有意义,并且 2 以上的值会被视为与border = 2相同。latex和latex-longtable格式会额外地允许一个值 3 表示在数据行之间增加分隔线。
columns
为wrapped格式设置目标宽度,还有扩展自动模式中决定输出是否足够多到需要分页器或者切换到垂直显示的宽度限制。零(默认)导致目标宽度由环境变量COLUMNS所控制,如果没有设置COLUMNS则使用检测到的屏幕宽度。此外,如果columns为零则wrapped格式只影响屏幕输出。如果columns为非零则文件和管道输出也会被包裹成该宽度。
expanded (or x)
如果value被指定,它必须是on或者off,它们分别会启用或者禁用扩展模式,也可以是auto。如果value被省略,则该命令会在开启和关闭设置之间切换。当扩展模式被启用时,查询结果被显示在两列中,第一列是列名而第二列是列值。如果在通常的"水平"模式中数据不适合屏幕,则可以用这种模式。在自动设置中,只要查询输出有多于一列并且比屏幕宽,就会使用扩展模式。否则,将使用常规模式。只有在对齐格式和 wrapped 格式中自动设置才有效。在其他格式中,它的行为总是像扩展模式被关闭一样。
fieldsep
指定在非对齐输出格式中使用的域分隔符。用那种方式,用户可以创建 tab 或者逗号分隔的输出,这种形式其他程序可能更喜欢。要设置 tab 为域分隔符,可以键入\pset fieldsep ‘\t’。默认的域分隔符是’|’(一个竖线)。
fieldsep_zero
把用在非对齐输出格式中的域分隔符设置为一个零字节。
footer
如果value被指定,它必须是on或者off,它们分别会启用或者禁用表格页脚((n rows)计数)的显示。如果value被省略,则该命令会切换页脚显示为打开或者关闭。
format
设置输出格式为unaligned、aligned、wrapped、html、asciidoc、latex(使用tabular)、latex-longtable或者troff-ms之一。也可以使用不造成歧义的缩写(这意味着一个字母就够了)。
unaligned格式把一个数据行的所有列都写在一行上,之间用当前活动的域分隔符分隔。这可用于生成意图由其他程序读取的输出(例如,tab 分隔或者逗号分隔格式)。
aligned格式是标准的、人类可读的、格式化好的文本输出,这是默认格式。
wrapped格式和aligned相似,但是前者会把过宽的数据值分成多个行以便输出能够适合目标行的宽度。目标行的宽度由columns选项决定。注意psql将不会尝试对列头部标题进行换行,因此如果列头部需要的总宽度超过目标宽度,wrapped格式的行为就变得和aligned一样了。
html、asciidoc、latex、latex-longtable和troff-ms格式分别用相应的标记语言把要输出的表格放在文档中,不过它们的输出并不是完整的文档。在HTML中这可能并不重要,但是在LaTeX中必须有完整的文档。latex-longtable还要求有LaTeX的longtable以及booktabs包。
linestyle
设置边框线的绘制样式为ascii、old-ascii或者unicode之一。允许不产生歧义的缩写(这意味着一个字母就足够了)。默认的设置是ascii。这个选项只影响aligned以及wrapped输出格式。
ascii样式使用纯ASCII字符。数据中的新行使用一个+符号在右手边的空白处显示。当在wrapped格式中包裹两行中间没有新行字符的数据时,会在第一行右手边空白处显示一个点号(.),并且在下一行的左手边空白处也显示一个点号(.)。
old-ascii样式使用纯ASCII字符,使用PostgreSQL 8.4 及更早版本中用过的格式化样式。数据中的新行使用:符号来代替左手边的列分隔符显示。在包裹两行中间没有新行字符的数据时,会用一个;符号取代左手边的列分隔符。
unicode样式使用 Unicode 的方框绘制字符。数据中的新行会使用一个回车符号显示在右手边的空白处。在包裹两行中间没有新行字符的数据时,会在第一行的右手边空白处显示一个省略号,并且在下一行的左手边空白处也显示一个省略号。
当border设置大于零时,linestyle选项也决定边框线用什么字符绘制。纯ASCII字符到处都可以使用,但是在识别 Unicode 字符的显示上使用 Unicode 字符会更好看。
null
设置要用来替代空值被打印的字符串。默认是什么也不打印,对于一个空字符串这很容易弄错。例如,有人可能更想用\pset null ‘(null)’。
numericlocale
如果value被指定,它必须是on或者off,它们将分别启用或者禁用一个与区域相关的字符来分隔数字和左边的十进制标记。如果value被省略,该命令会在常规输出和区域相关的数字输出之间切换。
pager
控制对查询和psql的帮助输出使用分页器程序。如果环境变量PAGER被设置,输出会被用管道输送到指定的程序。否则将使用与平台相关的默认分页器程序(例如more)。
如果pager选项被设为off,则不会使用分页器程序。如果pager选项被设为on,则会在适当的时候使用分页器,即当输出到终端并且无法适合屏幕时就会使用分页器。pager选项也可以被设置为always,这会导致对所有的终端输出都是用分页器而不管输出是否适合屏幕。不带value的\pset pager会切换分页器开、关状态。
pager_min_lines
如果pager_min_lines被设置为一个大于页面高度的数字,在至少这么多输出行被显示之前都不会调用分页器程序。默认设置为 0。
recordsep
指定用在非对齐输出格式中的记录(行)分隔符。
recordsep_zero
把用在非对齐输出格式中的记录分隔符设置为一个零字节。
tableattr (or T)
在HTML格式中,这会指定要放在table标记内的属性。例如,这可能是cellpadding或者bgcolor。注意你可能不想在这里指定border,因为那由\pset border负责。如果没有给出value,则表属性会被重置。
在latex-longtable格式中,这个选项控制每个包含左对齐数据类型的列的宽度比例。这个选项的值是一个由空格分隔的值列表,例如’0.2 0.2 0.6’。没有指定的输出列会使用最后一个指定的值。
title (or C)
设置用于任何后续被打印表的表标题。这可以用来给输出加上描述性的标签。如果没有给出value,这个标题会被复原。
tuples_only (or t)
如果value被指定,它必须是on或者off,这个选项将启用或者禁用只显示元组的模式。如果value被省略,则该命令会在常规输出和只显示元组输出之间切换。常规输出包括列头、标题以及多种页脚之类的额外信息。在只显示元组的模式中,只会显示实际的表数据。
unicode_border_linestyle
设置unicode线型的边框绘制风格为single或者double之一。
unicode_column_linestyle
设置unicode线型的列绘制风格为single或者double之一。
unicode_header_linestyle
设置unicode线型的页眉绘制风格为single或者double之一。

\t [on|off] show only rows (currently off)
只显示行(默认关闭)

postgres=# \t
Tuples only is on.
postgres=# select * from abc;
   1
   2

\T [STRING] set HTML

tag attributes, or unset if none
指定在HTML输出格式中,要放在table标签内的属性。

  postgres=# \T abcde
Table attributes are "abcde".
postgres=# select * from abcde;
<table border="1" abcde>
  <tr valign="top">
    <td align="right">1</td>
    <td align="right">&nbsp; </td>
  </tr>
  <tr valign="top">
    <td align="right">&nbsp; </td>
    <td align="right">2</td>
  </tr>
</table>

postgres=# select * from abc;
<table border="1" abcde>
  <tr valign="top">
    <td align="right">1</td>
  </tr>
  <tr valign="top">
    <td align="right">2</td>
  </tr>
</table>

\x [on|off|auto] toggle expanded output (currently off)
设置或者切换扩展表格格式化模式。

postgres=# \x
Expanded display is on.
postgres=# select * from abc;
int | 1
----+--
int | 2

postgres=# \x
Expanded display is off.
postgres=# select * from abc;
   1
   2

Connection
连接

\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
connect to new database (currently “postgres”)
连接到新数据库

postgres=# \c postgres
You are now connected to database "postgres" as user "postgres".

\conninfo display information about current connection
输出有关当前数据库连接的信息。

postgres=# \conninfo
You are connected to database "postgres" as user "postgres" via socket in "/tmp" at port "5432".

\encoding [ENCODING] show or set client encoding
设置客户端字符集编码。

postgres=# \encoding
UTF8
postgres=# \encoding 
BIG5 
postgres=# \encoding
BIG5

\password [USERNAME] securely change the password for a user
更改指定用户(默认情况下是当前用户)的口令。

postgres=#  \password
Enter new password: 
Enter it again: 

Operating System
操作系统

\cd [DIR] change the current working directory
修改当前工作目录

postgres=# \cd /tmp
postgres=# \! pwd
/tmp

\setenv NAME [VALUE] set or unset environment variable
设置或取消设置环境变量

postgres=# \setenv  CHA asl
postgres=# \! env |grep CHA
CHA=asl

\timing [on|off] toggle timing of commands (currently off)
显示每个 SQL 语句花费的时间(以毫秒为单位),默认关闭。

postgres=# select count (*) from abc;
     2

postgres=# \timing 
Timing is on.
postgres=# select count (*) from abc;
     2

Time: 0.267 ms

! [COMMAND] execute command in shell or start interactive shell
跳到一个单独的 shell 或者执行 shell 命令

postgres=# \!
[postgres@db1 ~]$ exit
exit
postgres=# \! pwd
/home/postgres

Variables
变量

\prompt [TEXT] NAME prompt user to set internal variable
提示用户提供一个文本用于分配给变量。

postgres=# \prompt a 
ssds

\set [NAME [VALUE]] set internal variable, or list all if no parameters
设置变量name为value,或者列出所有变量

postgres=# \set bianlaing2 abc
postgres=# \set
bianlaing2 = 'abc'
bianliang = 'abc'...

\unset NAME unset (delete) internal variable
取消变量的设置。

postgres=# \unset cd

Large Objects
大对象

\lo_export LOBOID FILE
从数据库中读取具有OID LOBOID的大对象并且将它写入到file。
\lo_import FILE [COMMENT]
把该文件存储到PostgreSQL大对象。可选地,它可以把给定的注释关联到该对象。
\lo_list
显示当前存储在数据库中的所有PostgreSQL大对象,同时显示它们的任何注释。
\lo_unlink LOBOID large object operations
从数据库中删除OID为LOBOID的大对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值