블루베리소르베

[입문] 03. PostgreSQL 접속하기 (psql) 본문

DATA/PostgreSQL

[입문] 03. PostgreSQL 접속하기 (psql)

블루베리소르베 2022. 12. 27. 23:00
PostgreSQL에 접속하기 앞서

지난 포스팅에서는 PostgreSQL을 설치하는 방법을 알아보았다.

그렇다면 이제 PostgreSQL을 사용해 볼 시간이다.

PostgreSQL에 접속하는 방법은 기본적으로 CLI를 통한 접속과 GUI를 통한 접속으로 나뉜다.

CLI를 통한 접속은 psql이라는 PostreSQL 기본 유틸리티를 통해 접속을 할 예정이고, GUI 사용은 DBeaver를 통해 진행해 볼 것이다.

물론 CLI와 GUI 모두 해당 방법만 존재하는 것은 아니다. CLI에서는 psql 이외에도 psycopg2, JDBC와 같은 커넥션 툴을 사용해 데이터를 불러오고, 원하는 형태로 가공할 수 있으며 GUI에서는 DBeaver, pgAdmin4, Squirrel SQL등과 같은 클라이언트 들을 사용할 수 있다. 이런 접속 툴들은 상황에 따라, 사용자의 기호에 따라 선택하여 사용하면 된다.

 

psql 사용하기

psql은 대화형 PostgreSQL 접속 인터페이스로, 질의를 입력하면 답을 출력해주는 역할을 한다.

우선 psql의 버전을 확인하는 방법은 다음과 같다.

psql --version
> psql (PostgreSQL) 14.6

psql은 기본적으로 PostgreSQL 서버의 버전을 그대로 따라간다. PostgreSQL을 설치하면 기본적으로 설치가 되는 기본제공 유틸리티인 만큼, 그 버전도 동일하게 따라가는 것이다.

 

공식 문서에서도 해당 유틸리티에 대한 자세한 내용을 확인할 수 있다.

https://www.postgresql.org/docs/14/app-psql.html

psql을 사용하기 위해서는 여러가지 옵션을 자유롭게 사용할 수 있어야 한다.

옵션들에는 여러가지가 있으며, 그 내용은 다음과 같다.

psql is the PostgreSQL interactive terminal.

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

General options:
  -c, --command=COMMAND    run only single command (SQL or internal) and exit
  -d, --dbname=DBNAME      database name to connect to (default: "experdb")
  -f, --file=FILENAME      execute commands from file, then exit
  -l, --list               list available databases, then exit
  -v, --set=, --variable=NAME=VALUE
                           set psql variable NAME to VALUE
                           (e.g., -v ON_ERROR_STOP=1)
  -V, --version            output version information, then exit
  -X, --no-psqlrc          do not read startup file (~/.psqlrc)
  -1 ("one"), --single-transaction
                           execute as a single transaction (if non-interactive)
  -?, --help[=options]     show this help, then exit
      --help=commands      list backslash commands, then exit
      --help=variables     list special variables, then exit

Input and output options:
  -a, --echo-all           echo all input from script
  -b, --echo-errors        echo failed commands
  -e, --echo-queries       echo commands sent to server
  -E, --echo-hidden        display queries that internal commands generate
  -L, --log-file=FILENAME  send session log to file
  -n, --no-readline        disable enhanced command line editing (readline)
  -o, --output=FILENAME    send query results to file (or |pipe)
  -q, --quiet              run quietly (no messages, only query output)
  -s, --single-step        single-step mode (confirm each query)
  -S, --single-line        single-line mode (end of line terminates SQL command)

Output format options:
  -A, --no-align           unaligned table output mode
      --csv                CSV (Comma-Separated Values) table output mode
  -F, --field-separator=STRING
                           field separator for unaligned output (default: "|")
  -H, --html               HTML table output mode
  -P, --pset=VAR[=ARG]     set printing option VAR to ARG (see \pset command)
  -R, --record-separator=STRING
                           record separator for unaligned output (default: newline)
  -t, --tuples-only        print rows only
  -T, --table-attr=TEXT    set HTML table tag attributes (e.g., width, border)
  -x, --expanded           turn on expanded table output
  -z, --field-separator-zero
                           set field separator for unaligned output to zero byte
  -0, --record-separator-zero
                           set record separator for unaligned output to zero byte

Connection options:
  -h, --host=HOSTNAME      database server host or socket directory (default: "local socket")
  -p, --port=PORT          database server port (default: "5432")
  -U, --username=USERNAME  database user name (default: "experdba")
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)

For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.

Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>

해당 내용을 CLI 상에서 보고자 한다면 다음 명령어를 사용하면 된다.

psql --help

여기서 우리는 psql의 기본적인 사용법을 알 수 있다.

psql은 명령어 뒤에 옵션과 Database명을 명시하여 사용해야 한다.

psql [OPTION]... [DBNAME [USERNAME]]

psql로 접속할 Database의 이름은 반드시 명시해 주어야 한다. 차후에 포스팅을 할 예정이지만, PostgreSQL은 Database들의 집합 형태로 동작하며, 때문에 접근하고자 하는 Database에 대한 명시가 반드시 필요하다.

Database에 대한 정보는 " -d " 플래그를 사용하여 옵션을 지정해 줄 수 있다.

psql에서는 두가지 모드가 존재한다. psql 인터페이스에 접속하여 쿼리를 입력할 수 있는 인터널 모드와 외부 CLI환경에서 psql을 통한 응답 값을 제공받을 수 있는 터미널 모드가 있다. 터미널 모드를 사용하기 위해서는 " -c " 플래그를 통해 옵션을 지정하여 질의하고자 하는 쿼리를 PostgreSQL 서버에 제공할 수 있다.

다음은 test라는 Database에 현재 시간을 확인하는 function을 사용하여 값을 제공받는 예시이다.

psql -d test -c "select now()"
>               now
-------------------------------
 2022-12-31 20:02:00.360608+09
(1 row)

터미널 모드의 경우 해당 값을 "-t" 플래그와 함께 사용하여 터미널의 변수에 할당 할 수도 있다.

v1=$(psql -d test -c 'select now()' -t)
echo $v1
> 2022-12-31 20:02:00.360608+09

인터널 모드의 경우에는 따로 값을 조작할 수는 없지만, 더욱 많은 정보를 손쉽게 얻을 수 있다.

"\l"과 같은 토글 명령어를 사용하면 해당 DBMS가 가지고 있는 여러가지 정보값들을 일일이 쿼리를 통해 조회하지 않아도 바로바로 알 수 있다.

psql (14.6)
Type "help" for help.

test=# \l
                             List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 test      | postgres | UTF8     | C       | C     |
 postgres  | postgres | UTF8     | C       | C     |
 template0 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
(5 rows)

인터널 모드의 토글 명령어에 대한 정보는 "\?" 명령어를 통해 확인할 수 있다.

설명을 따로 서버에 접속해 찾아보지 않더라도 확인할 수 있도록 아래에는 모든 정보를 담도록 하겠다.

test=# \?
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 [(OPTIONS)] [FILE]  execute query (and send results to file or |pipe);
                         \g with no arguments is equivalent to a semicolon
  \gdesc                 describe result of query, without executing it
  \gexec                 execute query, then execute each value in its result
  \gset [PREFIX]         execute query and store results in psql variables
  \gx [(OPTIONS)] [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

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Input/Output
  \copy ...              perform SQL COPY with data stream to the client host
  \echo [-n] [STRING]    write string to standard output (-n for no newline)
  \i FILE                execute commands from file
  \ir FILE               as \i, but relative to location of current script
  \o [FILE]              send all query results to file or |pipe
  \qecho [-n] [STRING]   write string to \o output stream (-n for no newline)
  \warn [-n] [STRING]    write string to standard error (-n for no newline)

Conditional
  \if EXPR               begin conditional block
  \elif EXPR             alternative within current conditional block
  \else                  final alternative within current conditional block
  \endif                 end conditional block

Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
  \da[S]  [PATTERN]      list aggregates
  \dA[+]  [PATTERN]      list access methods
  \dAc[+] [AMPTRN [TYPEPTRN]]  list operator classes
  \dAf[+] [AMPTRN [TYPEPTRN]]  list operator families
  \dAo[+] [AMPTRN [OPFPTRN]]   list operators of operator families
  \dAp[+] [AMPTRN [OPFPTRN]]   list support functions of operator families
  \db[+]  [PATTERN]      list tablespaces
  \dc[S+] [PATTERN]      list conversions
  \dC[+]  [PATTERN]      list casts
  \dd[S]  [PATTERN]      show object descriptions not displayed elsewhere
  \dD[S+] [PATTERN]      list domains
  \ddp    [PATTERN]      list default privileges
  \dE[S+] [PATTERN]      list foreign tables
  \des[+] [PATTERN]      list foreign servers
  \det[+] [PATTERN]      list foreign tables
  \deu[+] [PATTERN]      list user mappings
  \dew[+] [PATTERN]      list foreign-data wrappers
  \df[anptw][S+] [FUNCPTRN [TYPEPTRN ...]]
                         list [only agg/normal/procedure/trigger/window] functions
  \dF[+]  [PATTERN]      list text search configurations
  \dFd[+] [PATTERN]      list text search dictionaries
  \dFp[+] [PATTERN]      list text search parsers
  \dFt[+] [PATTERN]      list text search templates
  \dg[S+] [PATTERN]      list roles
  \di[S+] [PATTERN]      list indexes
  \dl                    list large objects, same as \lo_list
  \dL[S+] [PATTERN]      list procedural languages
  \dm[S+] [PATTERN]      list materialized views
  \dn[S+] [PATTERN]      list schemas
  \do[S+] [OPPTRN [TYPEPTRN [TYPEPTRN]]]
                         list operators
  \dO[S+] [PATTERN]      list collations
  \dp     [PATTERN]      list table, view, and sequence access privileges
  \dP[itn+] [PATTERN]    list [only index/table] partitioned relations [n=nested]
  \drds [ROLEPTRN [DBPTRN]] 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
  \dT[S+] [PATTERN]      list data types
  \du[S+] [PATTERN]      list roles
  \dv[S+] [PATTERN]      list views
  \dx[+]  [PATTERN]      list extensions
  \dX     [PATTERN]      list extended statistics
  \dy[+]  [PATTERN]      list event triggers
  \l[+]   [PATTERN]      list databases
  \sf[+]  FUNCNAME       show a function's definition
  \sv[+]  VIEWNAME       show a view's definition
  \z      [PATTERN]      same as \dp
  Formatting
  \a                     toggle between unaligned and aligned output mode
  \C [STRING]            set table title, or unset if none
  \f [STRING]            show or set field separator for unaligned query output
  \H                     toggle HTML output mode (currently off)
  \pset [NAME [VALUE]]   set table output option
                         (border|columns|csv_fieldsep|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)
  \t [on|off]            show only rows (currently off)
  \T [STRING]            set HTML <table> tag attributes, or unset if none
  \x [on|off|auto]       toggle expanded output (currently off)

Connection
  \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                         connect to new database (currently "experdb")
  \conninfo              display information about current connection
  \encoding [ENCODING]   show or set client encoding
  \password [USERNAME]   securely change the password for a user

Operating System
  \cd [DIR]              change the current working directory
  \setenv NAME [VALUE]   set or unset environment variable
  \timing [on|off]       toggle timing of commands (currently off)
  \! [COMMAND]           execute command in shell or start interactive shell

Variables
  \prompt [TEXT] NAME    prompt user to set internal variable
  \set [NAME [VALUE]]    set internal variable, or list all if no parameters
  \unset NAME            unset (delete) internal variable

Large Objects
  \lo_export LOBOID FILE
  \lo_import FILE [COMMENT]
  \lo_list
  \lo_unlink LOBOID      large object operations

 

psql 사용시 주의사항과 Tip

psql은 PostgreSQL을 사용함에 있어 매우 강력한 유틸리티임이 틀림없다. 하지만 그만큼 주의할 점도 존재한다.

psql에서 수행되는 명령어들은 곧바로 DBMS에 영향을 미친다. PostgreSQL은 기본적으로 AutoCommit 모드로 동작을 하기 때문에 해당 쿼리들은 바로바로 반영이 되며, 되돌릴 수 없다.

이를 방지하기 위해서는 단일 트랜잭션을 사용하여 작업을 진행하거나, AutoCommit모드를 꺼주어야 한다.

단일 트랜잭션은 begin; end; 구문 사이에 원하는 쿼리문을 입력하면 된다.

test=# begin;
BEGIN
test=*# select now();
              now
-------------------------------
 2022-12-31 20:02:00.360608+09
(1 row)

test=*# end;
COMMIT

물론 위의 쿼리는 단순 조회이기 때문에 PostgreSQL 상의 Data가 변경되는 작업은 진행되지 않지만, create나 update와 같은 작업들은 end;나 commit을 진행하지 않으면 실제로 반영되지 않는다.

AutoCommit 모드를 사용하지 않는 방법도 있다.

해당 모드는 "\set" 명령어를 통해 사용할 수 있으며, "\echo"를 통해 상태값을 확인할 수 있다.

여기서 주의할 점은 AUTOCOMMIT 명령어를 대문자로 입력해주어야 한다는 점이다.

test=# \echo :AUTOCOMMIT 
on
test=# \set AUTOCOMMIT off
test=# \echo :AUTOCOMMIT 
off

 

마치며

psql은 가볍지만 강력한 툴이다. 사용법도 간결하고, 그 기능또한 다양하다. 하지만 우리가 CLI환경에서 작업할때의 효율은 분명 제한적이다. 그렇기 때문에 대부분의 사용자들은 GUI를 사용한 작업을 선호한다.

그러나 코드베이스로 터미널, OS와의 연동작업 등은 CLI에서만 가능한 부분이기에 우리는 psql의 사용법을 익혀둘 필요가 있다.

위에서 설명한 psql의 사용법들은 정말 간단한 것들이며, 입문시에 반드시 알아야 할 기본적인 것들만을 설명하였다. 때문에 위의 예시만으로는 실 사용에 있어서 설명이 부족하다고 느끼는 사람들이 분명히 있을 것이다. 당장 필자도 다른 포스팅이나 문서들을 보고 "그래서 어떻게 쓰는건데?" 라는 물음을 항상 했었기에 이를 잘 알고있다. 그래서 앞으로의 포스팅을 통해 그 내용을 보강해 나갈 예정이다.