gsql是openGauss提供在命令行下运行的数据库连接工具,可以通过此工具连接服务器并对其进行操作和维护,除了具备操作数据库的基本功能,gsql还提供了若干高级特性,便于用户使用。
1.使用gsql命令连接数据库
1.1)切换至omm用户下,gsql登录数据库
root@modb:~# su - omm
omm@modb:~$ 1.2)使用omm用户连接到opengauss数据,命令中的-r选项提供了对gsql命令的历史版本支持。
利用客户端工具gsql登录opengauss数据库
[omm@node1 ~]$ gsql -d postgres -p 26000 -r
gsql ((openGauss 2.0.0 build 78689da9) compiled at 2021-03-31 21:04:03 commit 0 last mr )
Non-SSL connection (SSL connection is recommended when requiring high-security)
Type "help" for help.
postgres=# gsql:客户端工具
-d:db的选项缩写
postgres:数据库名
-p:port的选项缩写
26000:端口号
1.3)使用omm用户连接到本机omm数据库的5432端口,命令中的-r选项提供了对gsql命令的历史版本支持。
1.3.1)启动数据库容器
存储数据持久化,从容器外部连接容器数据库,opengauss默认监听启动在容器内的5432端口,如果想要从容器外部访问数据库,则需要在 docker run 的时候指定-p 参数。
【参数说明】:
a)数据持久化:
Docker 中 openGauss 的 所 有 数 据 文 件 : /var/lib/opengauss 目 录 , 存 储 在 宿 主 机 的/enmotech/opengauss 下。
宿主机的/enmotech/opengauss 如果不存在,会自动创建,但是必须是绝对路径。Docker 对其拥有读写权限。
b)网络端口:
8888:对外访问端口。
1.3.2)测试
关于使用docker,启动数据库容器,我们可以选择最新的版本enmotech/opengauss:latest 的镜像,也就是opengauss 3.0.0;也可以选择指定的版本enmotech/opengauss:2.0.1。
或者是opengauss 2.0.0的数据库,想要利用docker技术去持久化opengauss 2.0.1的数据库
docker run --name opengaussnet --privileged=true -d -e GS_PASSWORD=Passw0rd@1234 -v /enmotech/opengauss:/var/lib/opengauss -p 8888:5432 enmotech/opengauss:2.0.1或者是opengauss 2.0.0的数据库,想要利用docker技术去持久化opengauss 3.0.0的数据库
docker run --name opengaussnet --privileged=true -d -e GS_PASSWORD=Passw0rd@1234 -v /enmotech/opengauss:/var/lib/opengauss -p 8888:5432 enmotech/opengauss:latest利用docker技术登录opengauss数据库
启动容器
[root@node1 ~]# docker exec -it opengaussnet bash
root@ade4b851ac47:/#切换omm用户
root@ade4b851ac47:/# su - omm
omm@ade4b851ac47:~$ 登录数据库
omm@ade4b851ac47:~$ gsql -d postgres -p5432 -r
gsql ((openGauss 2.0.1 build d97c0e8a) compiled at 2021-06-02 19:37:17 commit 0 last mr )
Non-SSL connection (SSL connection is recommended when requiring high-security)
Type "help" for help.
postgres=#
利用docker技术,研究opengauss数据库中的基本命令
2.在gsql中查看数据库的版本、pg基础版本和版权信息
select version();

show server_version;
\copyright
3.常见元命令的使用
元命令\l的作用是显示openGauss数据库集簇中,目前有哪些数据库。
- \l
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+-------+-----------+---------+-------+-------------------
enmodb | omm | SQL_ASCII | C | C |
mydb | omm | GBK | C | C |
postgres | omm | SQL_ASCII | C | C |
template0 | omm | SQL_ASCII | C | C | =c/omm +
| | | | | omm=CTc/omm
template1 | omm | SQL_ASCII | C | C | =c/omm +
| | | | | omm=CTc/omm
(5 rows)
postgres=#元命令\conninfo的作用是在gsql中,显示会话的连接信息。
- \conninfo
postgres=# \conninfo
You are connected to database "postgres" as user "omm" via socket in "/opt/huawei/tmp" at port "26000".
postgres=#
元命令\ c[onnect] [DBNAME]的作用是在gsql中,切换连接的数据库postgres。
- 语法格式:\c[onnect] [DBNAME]
例如,\c postgres
postgres=#
postgres=# \c mydb
Non-SSL connection (SSL connection is recommended when requiring high-security)
You are now connected to database "mydb" as user "omm".mydb=#
mydb=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+-------+-----------+---------+-------+-------------------
enmodb | omm | SQL_ASCII | C | C |
mydb | omm | GBK | C | C |
postgres | omm | SQL_ASCII | C | C |
template0 | omm | SQL_ASCII | C | C | =c/omm +
| | | | | omm=CTc/omm
template1 | omm | SQL_ASCII | C | C | =c/omm +
| | | | | omm=CTc/omm
(5 rows)
mydb=# 
元命令\dg命令与元命令\du命令的作用类似,都是显示openGauss数据库集簇中,目前有哪些用户和角色。
- \du
postgres=# \du
List of roles
Role name | Attributes
| Member of
-----------+-----------------------------------------------------------------------------------------------------------------
-+-----------
gaussdb | Sysadmin
| {}
omm | Sysadmin, Create role, Create DB, Replication, Administer audit, Monitoradmin, Operatoradmin, Policyadmin, UseFT
| {}
postgres=#
- \dg
postgres=# \dg
List of roles
Role name | Attributes
| Member of
-----------+-----------------------------------------------------------------------------------------------------------------
-+-----------
gaussdb | Sysadmin
| {}
omm | Sysadmin, Create role, Create DB, Replication, Administer audit, Monitoradmin, Operatoradmin, Policyadmin, UseFT
| {}
postgres=# 元命令\db的作用是显示openGauss数据库集簇中,目前有哪些表空间。
- \db
enmodb=# \db
List of tablespaces
Name | Owner | Location
------------+-------+-----------------------
enmodb_ts | omm | tablespace/enmodb_ts1
pg_default | omm |
pg_global | omm |
(3 rows)
enmodb=#元命令\dn的作用是显示当前数据库有哪些数据库模式。
- \dn
enmodb=# \dn
List of schemas
Name | Owner
-------------+-------
cstore | omm
dbe_perf | omm
pkg_service | omm
public | omm
snapshot | omm
(5 rows)
enmodb=#
--创建表
CREATE TABLE customer_t
( c_customer_sk integer,
c_customer_id char(5),
c_first_name char(6),
c_last_name char(8)
) ;
--插入数据
INSERT INTO customer_t (c_customer_sk, c_customer_id, c_first_name,c_last_name) VALUES (3769, 5, 'Grace','White');
INSERT INTO customer_t (c_customer_sk, c_customer_id, c_first_name,c_last_name) VALUES (3770, 6, 'Grace','Black');
INSERT INTO customer_t (c_customer_sk, c_customer_id, c_first_name,c_last_name) VALUES (3771, 7, 'Grace','Orange');
命令\dt的作用是显示数据库中所有的表。
- \dt
enmodb=# \dt
List of relations
Schema | Name | Type | Owner | Storage
--------+------------+-------+-------+----------------------------------
public | advisor | table | omm | {orientation=row,compression=no}
public | classroom | table | omm | {orientation=row,compression=no}
public | course | table | omm | {orientation=row,compression=no}
public | customer_t | table | omm | {orientation=row,compression=no}
public | department | table | omm | {orientation=row,compression=no}
public | instructor | table | omm | {orientation=row,compression=no}
public | prereq | table | omm | {orientation=row,compression=no}
public | section | table | omm | {orientation=row,compression=no}
public | student | table | omm | {orientation=row,compression=no}
public | takes | table | omm | {orientation=row,compression=no}
public | teaches | table | omm | {orientation=row,compression=no}
public | time_slot | table | omm | {orientation=row,compression=no}
(12 rows)
enmodb=#
元命令\d TableName的作用是查看某个表的信息。
- 语法格式:\d TableName命令,
比如,\d customer_t
enmodb=# \d customer_t
Table "public.customer_t"
Column | Type | Modifiers
---------------+--------------+-----------
c_customer_sk | integer |
c_customer_id | character(5) |
c_first_name | character(6) |
c_last_name | character(8) |
enmodb=# 查看索引信息,元命令\di IndexName的作用是查看某个索引的信息。
- 语法格式:\di IndexName命令
比如,create index idx_customer_id on customer_t(c_customer_id);
\di
enmodb=# create index idx_customer_id on customer_t(c_customer_id);
CREATE INDEX
enmodb=# \di
List of relations
Schema | Name | Type | Owner | Table | Storage
--------+-----------------+-------+-------+------------+---------
public | advisor_pkey | index | omm | advisor |
public | classroom_pkey | index | omm | classroom |
public | course_pkey | index | omm | course |
public | department_pkey | index | omm | department |
public | idx_customer_id | index | omm | customer_t |
public | instructor_pkey | index | omm | instructor |
public | prereq_pkey | index | omm | prereq |
public | section_pkey | index | omm | section |
public | student_pkey | index | omm | student |
public | takes_pkey | index | omm | takes |
public | teaches_pkey | index | omm | teaches |
public | time_slot_pkey | index | omm | time_slot |
(12 rows)
enmodb=# \di idx_customer_id
List of relations
Schema | Name | Type | Owner | Table | Storage
--------+-----------------+-------+-------+------------+---------
public | idx_customer_id | index | omm | customer_t |
(1 row)
enmodb=# 可以用\pset命令以不同的方法显示表:
- \pset border 2
enmodb=# \pset border 2
Border style is 2.
enmodb=# select * from customer_t;
+---------------+---------------+--------------+-------------+
| c_customer_sk | c_customer_id | c_first_name | c_last_name |
+---------------+---------------+--------------+-------------+
| 3769 | 5 | Grace | White |
| 3770 | 6 | Grace | Black |
| 3771 | 7 | Grace | Orange |
+---------------+---------------+--------------+-------------+
(3 rows)
enmodb=#打开扩展表格式模式。
- \x
enmodb=# \x
Expanded display is on.
enmodb=# select * from customer_t;
+-[ RECORD 1 ]--+----------+
| c_customer_sk | 3769 |
| c_customer_id | 5 |
| c_first_name | Grace |
| c_last_name | White |
+-[ RECORD 2 ]--+----------+
| c_customer_sk | 3770 |
| c_customer_id | 6 |
| c_first_name | Grace |
| c_last_name | Black |
+-[ RECORD 3 ]--+----------+
| c_customer_sk | 3771 |
| c_customer_id | 7 |
| c_first_name | Grace |
| c_last_name | Orange |
+---------------+----------+
enmodb=#4.gsql中的事务:测试gsql中的默认事务自动提交功能
- 查看gsql中事务是否默认为自动提交
enmodb=# show AUTOCOMMIT;

- 测试gsql中事务默认为自动提交功能
enmodb=# create table customer_new as select * from customer_t;
enmodb=# select * from customer_new;
+-[ RECORD 1 ]--+----------+
| c_customer_sk | 3769 |
| c_customer_id | 5 |
| c_first_name | Grace |
| c_last_name | White |
+-[ RECORD 2 ]--+----------+
| c_customer_sk | 3770 |
| c_customer_id | 6 |
| c_first_name | Grace |
| c_last_name | Black |
+-[ RECORD 3 ]--+----------+
| c_customer_sk | 3771 |
| c_customer_id | 7 |
| c_first_name | Grace |
| c_last_name | Orange |
+---------------+----------+
enmodb=# 如何关闭\x的拓展模式?
说明:\q退出当前数据库,再进入数据库,就不会出现\x的拓展模式。
退出当前数据库:\q
- 重新登录后看到之前创建的表customer_new:
postgres=# postgres=# \c enmodb
Non-SSL connection (SSL connection is recommended when requiring high-security)
You are now connected to database "enmodb" as user "omm".
enmodb=# \dt
List of relations
Schema | Name | Type | Owner | Storage
--------+--------------+-------+-------+----------------------------------
public | advisor | table | omm | {orientation=row,compression=no}
public | classroom | table | omm | {orientation=row,compression=no}
public | course | table | omm | {orientation=row,compression=no}
public | customer_new | table | omm | {orientation=row,compression=no}
public | customer_t | table | omm | {orientation=row,compression=no}
public | department | table | omm | {orientation=row,compression=no}
public | instructor | table | omm | {orientation=row,compression=no}
public | prereq | table | omm | {orientation=row,compression=no}
public | section | table | omm | {orientation=row,compression=no}
public | student | table | omm | {orientation=row,compression=no}
public | takes | table | omm | {orientation=row,compression=no}
public | teaches | table | omm | {orientation=row,compression=no}
public | time_slot | table | omm | {orientation=row,compression=no}
(13 rows)
enmodb=# select * from customer_new;
c_customer_sk | c_customer_id | c_first_name | c_last_name
---------------+---------------+--------------+-------------
3769 | 5 | Grace | White
3770 | 6 | Grace | Black
3771 | 7 | Grace | Orange
(3 rows)
enmodb=# 5.gsql中的事务:测试gsql中的事务手动提交功能
- 测试gsql手动提交
1)opengauss默认执行完一条语句后,立即提交。可以关闭自动提交功能:
2)注意:此处设置ATUOCOMMIT必须用大写!
postgres=# \set AUTOCOMMIT off- 插入一些数据
INSERT INTO customer_t (c_customer_sk, c_customer_id, c_first_name,c_last_name) VALUES
(6885, 1, 'Joes', 'Hunter'),
(4321, 2, 'Lily','Carter'),
(9527, 3, 'James', 'Cook'),
(9500, 4, 'Lucy', 'Baker');
- 查看表中数据
postgres=# select * from customer_t;

- 执行回滚
postgres=# rollback;
- 检查是否回滚成功
postgres=# select * from customer_t;

6.gsql相关的帮助
- 连接数据库时,可以使用如下命令获取帮助信息。
[omm@node1 ~]$ gsql --help
gsql is the openGauss interactive terminal.
Usage:
gsql [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: "omm")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set gsql variable NAME to VALUE
-V, --version output version information, then exit
-X, --no-gsqlrc do not read startup file (~/.gsqlrc)
-1 ("one"), --single-transaction
execute command file as a single transaction
-?, --help show this help, then exit
Input and output options:
-a, --echo-all echo all input from script
-e, --echo-queries echo commands sent to server
-E, --echo-hidden display queries that internal commands generate
-k, --with-key=KEY the key for decrypting the encrypted file
-L, --log-file=FILENAME send session log to file
-m, --maintenance can connect to cluster during 2-pc transaction recovery
-n, --no-libedit disable enhanced command line editing (libedit)
-o, --output=FILENAME send query results to file (or |pipe)
-q, --quiet run quietly (no messages, only query output)
-C, --enable-client-encryption enable client encryption feature
-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
-F, --field-separator=STRING
set field separator (default: "|")
-H, --html HTML table output mode
-P, --pset=VAR[=ARG] set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
set record separator (default: newline)
-r if this parameter is set,use libedit
-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 to zero byte
-0, --record-separator-zero
set record separator to zero byte
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "/opt/huawei/tmp")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "omm")
-W, --password=PASSWORD the password of specified database user
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within gsql, or consult the gsql section in the openGauss documentation.
[omm@node1 ~]$ - 获取和SQL语法有关的帮助信息
postgres-# \h
Available help:
ABORT CREATE BARRIER DROP MATERIALIZED VIEW
ALTER APP WORKLOAD GROUP CREATE CLIENT MASTER KEY DROP NODE
ALTER APP WORKLOAD GROUP MAPPING CREATE COLUMN ENCRYPTION KEY DROP NODE GROUP
ALTER AUDIT POLICY CREATE DATA SOURCE DROP OWNED
ALTER DATA SOURCE CREATE DATABASE DROP PROCEDURE
ALTER DATABASE CREATE DIRECTORY DROP RESOURCE LABEL
ALTER DEFAULT PRIVILEGES CREATE EXTENSION DROP RESOURCE POOL
ALTER DIRECTORY CREATE FOREIGN TABLE DROP ROLE
ALTER EXTENSION CREATE FUNCTION DROP ROW LEVEL SECURITY POLICY
ALTER FOREIGN TABLE CREATE GROUP DROP SCHEMA
ALTER FOREIGN TABLE FOR HDFS CREATE INDEX DROP SEQUENCE
ALTER FUNCTION CREATE MASKING POLICY DROP SERVER
ALTER GROUP CREATE MATERIALIZED VIEW DROP SYNONYM
ALTER INDEX CREATE NODE DROP TABLE
ALTER LARGE OBJECT CREATE NODE GROUP DROP TABLESPACE
ALTER MASKING POLICY CREATE PROCEDURE DROP TEXT SEARCH CONFIGURATION
ALTER NODE CREATE RESOURCE LABEL DROP TEXT SEARCH DICTIONARY
ALTER NODE GROUP CREATE RESOURCE POOL DROP TRIGGER
ALTER RESOURCE LABEL CREATE ROLE DROP TYPE
ALTER RESOURCE POOL CREATE ROW LEVEL SECURITY POLICY DROP USER
ALTER ROLE CREATE SCHEMA DROP VIEW
ALTER ROW LEVEL SECURITY POLICY CREATE SEQUENCE DROP WEAK PASSWORD DICTIONARY
ALTER SCHEMA CREATE SERVER DROP WORKLOAD GROUP
ALTER SEQUENCE CREATE SYNONYM END
ALTER SERVER CREATE TABLE EXECUTE
ALTER SESSION CREATE TABLE AS EXECUTE DIRECT
ALTER SYNONYM CREATE TABLE PARTITION EXPLAIN
ALTER SYSTEM KILL SESSION CREATE TABLESPACE FETCH
ALTER SYSTEM SET CREATE TEXT SEARCH CONFIGURATION GRANT
ALTER TABLE CREATE TEXT SEARCH DICTIONARY INSERT
ALTER TABLE PARTITION CREATE TRIGGER LOCK
ALTER TABLESPACE CREATE TYPE MERGE
ALTER TEXT SEARCH CONFIGURATION CREATE USER MOVE
ALTER TEXT SEARCH DICTIONARY CREATE VIEW PREPARE
ALTER TRIGGER CREATE WEAK PASSWORD DICTIONARY PREPARE TRANSACTION
ALTER TYPE CREATE WORKLOAD GROUP REASSIGN OWNED
ALTER USER CURSOR REFRESH MATERIALIZED VIEW
ALTER VIEW DEALLOCATE REINDEX
ALTER WORKLOAD GROUP DECLARE RESET
ANALYSE DELETE REVOKE
ANALYZE DO ROLLBACK
ANONYMOUS BLOCK DROP APP WORKLOAD GROUP ROLLBACK PREPARED
BEGIN DROP APP WORKLOAD GROUP MAPPING SELECT
CALL DROP AUDIT POLICY SELECT INTO
CHECKPOINT DROP CLIENT MASTER KEY SET
CLEAN CONNECTION DROP COLUMN ENCRYPTION KEY SET CONSTRAINTS
CLOSE DROP DATA SOURCE SET ROLE
CLUSTER DROP DATABASE SET SESSION AUTHORIZATION
COMMENT DROP DIRECTORY SET TRANSACTION
COMMIT DROP EXTENSION SHOW
COMMIT PREPARED DROP FOREIGN TABLE START TRANSACTION
COPY DROP FUNCTION TRUNCATE
CREATE APP WORKLOAD GROUP DROP GROUP UPDATE
CREATE APP WORKLOAD GROUP MAPPING DROP INDEX VACUUM
CREATE AUDIT POLICY DROP MASKING POLICY VALUES
postgres-# 获取和元命令有关的帮助信息
enmodb=# \?
General
\copyright show openGauss usage and distribution terms
\g [FILE] or ; execute query (and send results to file or |pipe)
\h(\help) [NAME] help on syntax of SQL commands, * for all commands
\parallel [on [num]|off] toggle status of execute (currently off)
\q quit gsql
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\w FILE write query buffer to file
Input/Output
\copy ... perform SQL COPY with data stream to the client host
\echo [STRING] write string to standard output
\i FILE execute commands from file
\i+ FILE KEY execute commands from encrypted file
\ir FILE as \i, but relative to location of current script
\ir+ FILE KEY as \i+, but relative to location of current script
\o [FILE] send all query results to file or |pipe
\qecho [STRING] write string to query output stream (see \o)
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
\db[+] [PATTERN] list tablespaces
\dc[S+] [PATTERN] list conversions
\dC[+] [PATTERN] list casts
\dd[S] [PATTERN] show object descriptions not displayed elsewhere
\ddp [PATTERN] list default privileges
\dD[S+] [PATTERN] list domains
\ded[+] [PATTERN] list data sources
\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
\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[+] [PATTERN] list roles
\di[S+] [PATTERN] list indexes
\dl list large objects, same as \lo_list
\dL[S+] [PATTERN] list procedural languages
\dn[S+] [PATTERN] list schemas
\do[S] [PATTERN] list operators
\dO[S+] [PATTERN] list collations
\dp [PATTERN] list table, view, and sequence access privileges
\drds [PATRN1 [PATRN2]] list per-database role settings
\ds[S+] [PATTERN] list sequences
\dt[S+] [PATTERN] list tables
\dT[S+] [PATTERN] list data types
\du[+] [PATTERN] list roles
\dv[S+] [PATTERN] list views
\dE[S+] [PATTERN] list foreign tables
\dx[+] [PATTERN] list extensions
\l[+] list all databases
\sf[+] FUNCNAME show a function'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
(NAME := {format|border|expanded|fieldsep|fieldsep_zero|footer|null|
numericlocale|recordsep|recordsep_zero|tuples_only|title|tableattr|pager})
\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|-]
connect to new database (currently "enmodb")
\encoding [ENCODING] show or set client encoding
\conninfo display information about current connection
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
enmodb=# 



