Postgres - psql


Подключиться к серверу БД

psql -h host -p port -d dbname -U user

  • host - узел
  • port - порт
  • dbname - название базы данных
  • user - пользователь

psql -h 192.168.16.106 -p 5432 -d avis -U avis

Информация о текущем подключении


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

Получить справку по командам \?, \h


postgres=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \g [FILE] or ;         execute query (and send results to file or |pipe)
  \gset [PREFIX]         execute query and store results in psql variables
  \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

postgres=# \h select
Command:     SELECT
Description: retrieve rows from a table or view
Syntax:
[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]

Список БД на сервере \l


postgres=# \l
                                    List of databases
      Name      |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
----------------+----------+----------+-------------+-------------+-----------------------
 dvdrental      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 foo            | foo      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =T/foo               +
                |          |          |             |             | foo=CTc/foo
 hello_postgres | 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
(6 rows)

Переключиться на другую БД \c dbname username


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

Список таблиц в БД \dt


dvdrental=# \dt
             List of relations
 Schema |     Name      | Type  |  Owner   
--------+---------------+-------+----------
 public | actor         | table | postgres
 public | address       | table | postgres
 public | category      | table | postgres
 public | city          | table | postgres
 public | country       | table | postgres
 public | customer      | table | postgres
 public | film          | table | postgres
 public | film_actor    | table | postgres
 public | film_category | table | postgres
 public | inventory     | table | postgres
 public | language      | table | postgres
 public | payment       | table | postgres
 public | rental        | table | postgres
 public | staff         | table | postgres
 public | store         | table | postgres
(15 rows)

Информация о таблице \d table_name


dvdrental=# \d actor
                                         Table "public.actor"
   Column    |            Type             |                        Modifiers                         
-------------+-----------------------------+----------------------------------------------------------
 actor_id    | integer                     | not null default nextval('actor_actor_id_seq'::regclass)
 first_name  | character varying(45)       | not null
 last_name   | character varying(45)       | not null
 last_update | timestamp without time zone | not null default now()
Indexes:
    "actor_pkey" PRIMARY KEY, btree (actor_id)
    "idx_actor_last_name" btree (last_name)
Referenced by:
    TABLE "film_actor" CONSTRAINT "film_actor_actor_id_fkey" FOREIGN KEY (actor_id) REFERENCES actor(actor_id) ON UPDATE CASCADE ON DELETE RESTRICT
Triggers:
    last_updated BEFORE UPDATE ON actor FOR EACH ROW EXECUTE PROCEDURE last_updated()

Список схем в БД \dh


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

Список функций в БД \df


dvdrental=# \df
                                                           List of functions
 Schema |            Name            | Result data type |                         Argument data types                         |  Type   
--------+----------------------------+------------------+---------------------------------------------------------------------+---------
 public | _group_concat              | text             | text, text                                                          | normal
 public | film_in_stock              | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer     | normal
 public | film_not_in_stock          | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer     | normal
 public | get_customer_balance       | numeric          | p_customer_id integer, p_effective_date timestamp without time zone | normal
 public | group_concat               | text             | text                                                                | agg
 public | inventory_held_by_customer | integer          | p_inventory_id integer                                              | normal
 public | inventory_in_stock         | boolean          | p_inventory_id integer                                              | normal
 public | last_day                   | date             | timestamp without time zone                                         | normal
 public | last_updated               | trigger          |                                                                     | trigger
 public | rewards_report             | SETOF customer   | min_monthly_purchases integer, min_dollar_amount_purchased numeric  | normal
(10 rows)

Список views \dv


dvdrental=# \dv
                   List of relations
 Schema |            Name            | Type |  Owner   
--------+----------------------------+------+----------
 public | actor_info                 | view | postgres
 public | customer_list              | view | postgres
 public | film_list                  | view | postgres
 public | nicer_but_slower_film_list | view | postgres
 public | sales_by_film_category     | view | postgres
 public | sales_by_store             | view | postgres
 public | staff_list                 | view | postgres
(7 rows)

Список пользователей и их роли \du


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

Повторить последнюю команду \g

PS Распространяется на все команды, в том числе и не успешно выполненые


dvdrental=# select version();
                                                     version                                                      
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.5.12 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609, 64-bit
(1 row)

dvdrental=# \g
                                                     version                                                      
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.5.12 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609, 64-bit
(1 row)

Вывести историю команд \s [file_name]


dvdrental=# \s
\g
select 1;
\g
select version();
\g

Если нужно сохранить историю в файл


dvdrental=# \s history.txt
Wrote history to file "history.txt".

Выполнить команды из файла \i


postgres=# \i /var/lib/postgresql/commands.sql 
 ?column? 
----------
        1
(1 row)

                                                     version                                                      
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.5.12 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609, 64-bit
(1 row)

Выводить результат в файл \o


postgres=# \o result.txt
postgres=# select 1;
postgres=# select version();
postgres=# \! cat result.txt
 ?column? 
----------
        1
(1 строка)

                                                                     version                                                                     
-------------------------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.16 on x86_64-pc-linux-gnu (Ubuntu 9.6.16-1.pgdg16.04+1), compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609, 64-bit
(1 строка)

Выводить сколько времени выполнялся запрос \timing


dvdrental=# \timing 
Timing is on.
dvdrental=# select count(*) from payment;
 count 
-------
 14596
(1 row)

Time: 11.992 ms

Выполнить команду в своем редакторе \e

Запускает редактор в котором вводиться команда. Команда выполняется после закрытия редактора.

Удобнее всего использовать для редактирования функций


dvdrental=# \df
                                                           List of functions
 Schema |            Name            | Result data type |                         Argument data types                         |  Type   
--------+----------------------------+------------------+---------------------------------------------------------------------+---------
 public | _group_concat              | text             | text, text                                                          | normal
 public | film_in_stock              | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer     | normal
 public | film_not_in_stock          | SETOF integer    | p_film_id integer, p_store_id integer, OUT p_film_count integer     | normal
 public | get_customer_balance       | numeric          | p_customer_id integer, p_effective_date timestamp without time zone | normal
 public | group_concat               | text             | text                                                                | agg
 public | inventory_held_by_customer | integer          | p_inventory_id integer                                              | normal
 public | inventory_in_stock         | boolean          | p_inventory_id integer                                              | normal
 public | last_day                   | date             | timestamp without time zone                                         | normal
 public | last_updated               | trigger          |                                                                     | trigger
 public | rewards_report             | SETOF customer   | min_monthly_purchases integer, min_dollar_amount_purchased numeric  | normal
(10 rows)

dvdrental=# \ef film_in_stock
1 CREATE OR REPLACE FUNCTION public.film_in_stock(p_film_id integer, p_store_id integer, OUT p_film_count integer)
2  RETURNS SETOF integer
3  LANGUAGE sql
4 AS $function$
5      SELECT inventory_id
6      FROM inventory
7      WHERE film_id = $1
8      AND store_id = $2
9      AND inventory_in_stock(inventory_id);
10 $function$

Формат

Выравнивать/не выравнивать результат \a


dvdrental=# select 1;
 ?column? 
----------
        1
(1 row)

dvdrental=# \a
Output format is unaligned.
dvdrental=# \g
?column?
1
(1 row)
dvdrental=# 

Вывести результат в столбец \x


dvdrental=# select * from actor limit 3;
 actor_id | first_name | last_name |      last_update       
----------+------------+-----------+------------------------
        1 | Penelope   | Guiness   | 2013-05-26 14:47:57.62
        2 | Nick       | Wahlberg  | 2013-05-26 14:47:57.62
        3 | Ed         | Chase     | 2013-05-26 14:47:57.62
(3 rows)

dvdrental=# \x
Expanded display is on.
dvdrental=# \g
-[ RECORD 1 ]-----------------------
actor_id    | 1
first_name  | Penelope
last_name   | Guiness
last_update | 2013-05-26 14:47:57.62
-[ RECORD 2 ]-----------------------
actor_id    | 2
first_name  | Nick
last_name   | Wahlberg
last_update | 2013-05-26 14:47:57.62
-[ RECORD 3 ]-----------------------
actor_id    | 3
first_name  | Ed
last_name   | Chase
last_update | 2013-05-26 14:47:57.62

Вывести результат в HTML разметке \H

<pre><code class="shell"> dvdrental=# \H Output format is html. dvdrental=# \g <table border="1"> <tr> <th align="center">?column?</th> </tr> <tr valign="top"> <td align="right">1</td> </tr> </table> <p>(1 row)<br /> </p> dvdrental=# </code></pre>

Отключает вывод столбцов \t


dvdrental=# select 1;
 ?column? 
----------
        1
(1 row)

dvdrental=# \t
Tuples only is on.
dvdrental=# \g
        1

Уст. разделитель столбцов \pset fieldsep [разделитель]


postgres=# select 1,2,3;
 ?column? | ?column? | ?column? 
----------+----------+----------
        1 |        2 |        3
(1 строка)
postgres=# \a \t
Формат вывода: unaligned.
Режим вывода только кортежей включён.
postgres=# \pset fieldsep ' '
Разделитель полей: " ".
postgres=# select 1,2,3;
1 2 3

Разное

Выполнить команду в ОС \!


dvdrental=# \! perl -e 'print "hello\n"'
hello

Установить переменную окружения \setenv


postgres=# \setenv TEST alala
postgres=# \! echo $TEST
alala
postgres=#