You are on page 1of 1665

GaussDB 100

V300R001C00

Database Reference (Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Database Reference (Standalone) Contents

Contents

1 About This Document.................................................................................................................. 1


2 Parameters....................................................................................................................................... 4
2.1 Databases........................................................................................................................................................................ 5
2.1.1 Parameter Overview.................................................................................................................................................... 5
2.1.2 Control Files................................................................................................................................................................ 6
2.1.3 Page Management........................................................................................................................................................6
2.1.4 Maximum Number of Columns Allowed.................................................................................................................... 7
2.1.5 Archive Logs............................................................................................................................................................... 7
2.1.6 Transactions............................................................................................................................................................... 10
2.1.7 Data Correctness Verification.................................................................................................................................... 11
2.2 Instances........................................................................................................................................................................11
2.2.1 Parameter Overview.................................................................................................................................................. 11
2.2.2 Server Listening.........................................................................................................................................................18
2.2.3 Separation Between Sessions and Worker Threads...................................................................................................18
2.2.4 SGA........................................................................................................................................................................... 18
2.2.5 Sessions..................................................................................................................................................................... 22
2.2.6 Transactions............................................................................................................................................................... 23
2.2.7 Checkpoints............................................................................................................................................................... 24
2.2.8 Performance Statistics............................................................................................................................................... 25
2.2.9 SQL Resource Limit.................................................................................................................................................. 26
2.2.10 Background Process................................................................................................................................................ 27
2.2.11 HA............................................................................................................................................................................27
2.2.12 GS-Paxos Replication..............................................................................................................................................29
2.2.13 Local Temporary Tables.......................................................................................................................................... 33
2.2.14 Data Type Control Parameters.................................................................................................................................33
2.2.15 Cost-based Optimization......................................................................................................................................... 35
2.2.16 Maximum Number of Concurrent Jobs................................................................................................................... 35
2.2.17 Other Instance Parameters....................................................................................................................................... 35
2.2.18 Time Zone................................................................................................................................................................37
2.3 Sessions........................................................................................................................................................................ 38
2.3.1 Parameter Overview.................................................................................................................................................. 38
2.3.2 Cursors.......................................................................................................................................................................38
2.3.3 SQL Mapping............................................................................................................................................................ 39

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Database Reference (Standalone) Contents

2.4 Tools............................................................................................................................................................................. 39
2.4.1 Parameter Overview.................................................................................................................................................. 40
2.4.2 zsql Parameters.......................................................................................................................................................... 40
2.5 Advanced Optimization................................................................................................................................................ 40
2.5.1 Parameter Overview.................................................................................................................................................. 41
2.5.2 Flow Control Switch..................................................................................................................................................43
2.5.3 Soft Parse Switch.......................................................................................................................................................44
2.5.4 Thread Processing......................................................................................................................................................44
2.5.5 Session Control Parameters....................................................................................................................................... 45
2.6 Security and Audit........................................................................................................................................................ 49
2.6.1 Parameter Overview.................................................................................................................................................. 50
2.6.2 Parameter Descriptions..............................................................................................................................................52
2.7 Logs.............................................................................................................................................................................. 60
2.7.1 Parameter Overview.................................................................................................................................................. 60
2.7.2 Parameter Descriptions..............................................................................................................................................61
2.8 Reserved Parameters.....................................................................................................................................................63

3 Data Dictionary and Views....................................................................................................... 64


3.1 Data Dictionary Tables................................................................................................................................................. 64
3.1.1 SYS_BACKUP_SETS.............................................................................................................................................. 67
3.1.2 SYS_COLUMNS...................................................................................................................................................... 68
3.1.3 SYS_COMMENTS................................................................................................................................................... 70
3.1.4 SYS_CONSTRAINT_DEFS.....................................................................................................................................70
3.1.5 SYS_DATA_NODES................................................................................................................................................ 71
3.1.6 EXP_TAB_ORDERS................................................................................................................................................ 72
3.1.7 EXP_TAB_RELATIONS.......................................................................................................................................... 73
3.1.8 SYS_DEPENDENCIES............................................................................................................................................ 73
3.1.9 SYS_DISTRIBUTE_RULES.................................................................................................................................... 74
3.1.10 SYS_DISTRIBUTE_STRATEGIES....................................................................................................................... 75
3.1.11 SYS_DUMMY........................................................................................................................................................ 75
3.1.12 SYS_EXTERNAL_TABLES.................................................................................................................................. 75
3.1.13 SYS_GARBAGE_SEGMENTS............................................................................................................................. 76
3.1.14 SYS_HISTGRAM_ABSTR.................................................................................................................................... 77
3.1.15 SYS_HISTGRAM................................................................................................................................................... 78
3.1.16 SYS_INDEXES.......................................................................................................................................................79
3.1.17 SYS_INDEX_PARTS..............................................................................................................................................80
3.1.18 SYS_JOBS...............................................................................................................................................................82
3.1.19 SYS_LINKS............................................................................................................................................................ 83
3.1.20 SYS_LOBS..............................................................................................................................................................83
3.1.21 SYS_LOB_PARTS.................................................................................................................................................. 84
3.1.22 SYS_LOGIC_REPL................................................................................................................................................ 85
3.1.23 SYS_DML_STATS..................................................................................................................................................86
3.1.24 SYS_OBJECT_PRIVS............................................................................................................................................ 87

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Database Reference (Standalone) Contents

3.1.25 SYS_PART_COLUMNS.........................................................................................................................................88
3.1.26 SYS_PART_OBJECTS........................................................................................................................................... 89
3.1.27 SYS_PART_STORES............................................................................................................................................. 89
3.1.28 SYS_PENDING_DIST_TRANS............................................................................................................................ 90
3.1.29 SYS_PENDING_TRANS....................................................................................................................................... 90
3.1.30 SYS_PROCS........................................................................................................................................................... 91
3.1.31 SYS_PROC_ARGS.................................................................................................................................................92
3.1.32 SYS_PROFILE........................................................................................................................................................93
3.1.33 SYS_RECYCLEBIN...............................................................................................................................................93
3.1.34 SYS_ROLES........................................................................................................................................................... 95
3.1.35 SYS_SEQUENCES.................................................................................................................................................95
3.1.36 SYS_SHADOW_INDEXES................................................................................................................................... 96
3.1.37 SYS_SHADOW_INDEX_PARTS.......................................................................................................................... 97
3.1.38 SYS_SQL_MAPS................................................................................................................................................... 98
3.1.39 SYS_SYNONYMS................................................................................................................................................. 99
3.1.40 SYS_PRIVS.............................................................................................................................................................99
3.1.41 SYS_TABLES....................................................................................................................................................... 100
3.1.42 SYS_TABLE_PARTS............................................................................................................................................101
3.1.43 SYS_TMP_SEG_STATS.......................................................................................................................................103
3.1.44 SYS_USERS......................................................................................................................................................... 103
3.1.45 SYS_USER_HISTORY.........................................................................................................................................104
3.1.46 SYS_USER_ROLES............................................................................................................................................. 104
3.1.47 SYS_VIEWS......................................................................................................................................................... 105
3.1.48 SYS_VIEW_COLS............................................................................................................................................... 106
3.1.49 WSR_PARAMETER.............................................................................................................................................106
3.1.50 WSR_SQLAREA.................................................................................................................................................. 107
3.1.51 WSR_SYS_STAT.................................................................................................................................................. 109
3.1.52 WSR_SYSTEM.....................................................................................................................................................109
3.1.53 WSR_SYSTEM_EVENT......................................................................................................................................110
3.1.54 WSR_SNAPSHOT................................................................................................................................................ 110
3.1.55 WSR_CONTROL.................................................................................................................................................. 111
3.1.56 WSR_DBA_SEGMENTS..................................................................................................................................... 112
3.1.57 WSR_LATCH........................................................................................................................................................112
3.1.58 WSR_LIBRARYCACHE......................................................................................................................................113
3.1.59 WSR_LONGSQL.................................................................................................................................................. 114
3.1.60 WSR_SEGMENT..................................................................................................................................................114
3.1.61 WSR_SQL_LIST...................................................................................................................................................115
3.1.62 WSR_SQL_LIST_PLAN...................................................................................................................................... 115
3.1.63 WSR_WAITSTAT..................................................................................................................................................116
3.2 DBA Views................................................................................................................................................................. 116
3.2.1 DB_DB_LINKS.......................................................................................................................................................119
3.2.2 DB_IND_STATISTICS........................................................................................................................................... 120

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
Database Reference (Standalone) Contents

3.2.3 DB_JOBS................................................................................................................................................................ 121


3.2.4 DB_TAB_MODIFICATIONS................................................................................................................................. 122
3.2.5 DB_USERS............................................................................................................................................................. 123
3.2.6 DB_USER_SYS_PRIVS.........................................................................................................................................124
3.2.7 ADM_ARGUMENTS............................................................................................................................................. 124
3.2.8 ADM_BACKUP_SET.............................................................................................................................................125
3.2.9 ADM_COL_COMMENTS..................................................................................................................................... 126
3.2.10 ADM_CONSTRAINTS........................................................................................................................................ 126
3.2.11 ADM_DATA_FILES............................................................................................................................................. 129
3.2.12 ADM_DBLINK_TABLES.................................................................................................................................... 130
3.2.13 ADM_DBLINK_TAB_COLUMNS......................................................................................................................131
3.2.14 ADM_DEPENDENCIES...................................................................................................................................... 131
3.2.15 ADM_FREE_SPACE............................................................................................................................................ 132
3.2.16 ADM_HISTOGRAMS.......................................................................................................................................... 133
3.2.17 ADM_HIST_DBASEGMENTS........................................................................................................................... 133
3.2.18 ADM_HIST_LATCH............................................................................................................................................ 134
3.2.19 ADM_HIST_LIBRARYCACHE.......................................................................................................................... 135
3.2.20 ADM_HIST_LONGSQL...................................................................................................................................... 135
3.2.21 ADM_HIST_PARAMETER................................................................................................................................. 136
3.2.22 ADM_HIST_SEGMENT...................................................................................................................................... 137
3.2.23 ADM_HIST_SNAPSHOT.................................................................................................................................... 137
3.2.24 ADM_HIST_SQLAREA.......................................................................................................................................138
3.2.25 ADM_HIST_SYSSTAT........................................................................................................................................ 140
3.2.26 ADM_HIST_SYSTEM......................................................................................................................................... 140
3.2.27 ADM_HIST_SYSTEM_EVENT.......................................................................................................................... 140
3.2.28 ADM_HIST_WAITSTAT......................................................................................................................................141
3.2.29 ADM_HIST_WR_CONTROL..............................................................................................................................141
3.2.30 ADM_INDEXES...................................................................................................................................................142
3.2.31 ADM_IND_COLUMNS....................................................................................................................................... 144
3.2.32 ADM_IND_PARTITIONS.................................................................................................................................... 145
3.2.33 ADM_IND_STATISTICS..................................................................................................................................... 146
3.2.34 ADM_JOBS...........................................................................................................................................................147
3.2.35 ADM_JOBS_RUNNING...................................................................................................................................... 149
3.2.36 ADM_OBJECTS................................................................................................................................................... 150
3.2.37 ADM_PART_COL_STATISTICS.........................................................................................................................151
3.2.38 ADM_PART_KEY_COLUMNS...........................................................................................................................152
3.2.39 ADM_PART_STORE............................................................................................................................................152
3.2.40 ADM_PART_TABLES..........................................................................................................................................152
3.2.41 ADM_PROCEDURES.......................................................................................................................................... 153
3.2.42 ADM_PROFILES................................................................................................................................................. 154
3.2.43 ADM_ROLES....................................................................................................................................................... 154
3.2.44 ADM_ROLE_PRIVS............................................................................................................................................ 155

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. v


GaussDB 100
Database Reference (Standalone) Contents

3.2.45 ADM_SEGMENTS...............................................................................................................................................155
3.2.46 ADM_SEQUENCES.............................................................................................................................................156
3.2.47 ADM_SOURCE.................................................................................................................................................... 157
3.2.48 ADM_SYNONYMS............................................................................................................................................. 157
3.2.49 ADM_SYS_PRIVS............................................................................................................................................... 158
3.2.50 ADM_TABLES..................................................................................................................................................... 158
3.2.51 ADM_TABLESPACES......................................................................................................................................... 160
3.2.52 ADM_TAB_COLS................................................................................................................................................ 161
3.2.53 ADM_TAB_COLUMNS.......................................................................................................................................162
3.2.54 ADM_TAB_COL_STATISTICS...........................................................................................................................164
3.2.55 ADM_TAB_COMMENTS....................................................................................................................................165
3.2.56 ADM_TAB_DISTRIBUTE................................................................................................................................... 165
3.2.57 ADM_TAB_MODIFICATIONS........................................................................................................................... 166
3.2.58 ADM_TAB_PARTITIONS....................................................................................................................................167
3.2.59 ADM_TAB_PRIVS............................................................................................................................................... 169
3.2.60 ADM_TAB_STATISTICS.....................................................................................................................................170
3.2.61 ADM_TRIGGERS................................................................................................................................................ 171
3.2.62 ADM_USERS....................................................................................................................................................... 172
3.2.63 ADM_VIEWS....................................................................................................................................................... 173
3.2.64 ADM_VIEW_COLUMNS.................................................................................................................................... 174
3.3 User Views..................................................................................................................................................................174
3.3.1 DB_ARGUMENTS.................................................................................................................................................178
3.3.2 DB_COL_COMMENTS......................................................................................................................................... 179
3.3.3 DB_CONSTRAINTS.............................................................................................................................................. 180
3.3.4 DB_DBLINK_TABLES..........................................................................................................................................183
3.3.5 DB_DBLINK_TAB_COLUMNS........................................................................................................................... 183
3.3.6 DB_DEPENDENCIES............................................................................................................................................ 184
3.3.7 DB_DISTRIBUTE_RULES....................................................................................................................................185
3.3.8 DB_DIST_RULE_COLS........................................................................................................................................ 185
3.3.9 DB_HISTOGRAMS................................................................................................................................................186
3.3.10 DB_INDEXES.......................................................................................................................................................187
3.3.11 DB_IND_COLUMNS........................................................................................................................................... 189
3.3.12 DB_IND_PARTITIONS........................................................................................................................................190
3.3.13 DB_OBJECTS.......................................................................................................................................................191
3.3.14 DB_PART_COL_STATISTICS.............................................................................................................................192
3.3.15 DB_PART_KEY_COLUMNS.............................................................................................................................. 193
3.3.16 DB_PART_STORE............................................................................................................................................... 194
3.3.17 DB_PART_TABLES............................................................................................................................................. 194
3.3.18 DB_PROCEDURES..............................................................................................................................................195
3.3.19 DB_SEQUENCES.................................................................................................................................................196
3.3.20 DB_SOURCE........................................................................................................................................................ 197
3.3.21 DB_SYNONYMS................................................................................................................................................. 197

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. vi


GaussDB 100
Database Reference (Standalone) Contents

3.3.22 DB_TABLES......................................................................................................................................................... 198


3.3.23 DB_TAB_COLS....................................................................................................................................................200
3.3.24 DB_TAB_COLUMNS.......................................................................................................................................... 201
3.3.25 DB_TAB_COL_STATISTICS...............................................................................................................................203
3.3.26 DB_TAB_COMMENTS....................................................................................................................................... 204
3.3.27 DB_TAB_DISTRIBUTE.......................................................................................................................................205
3.3.28 DB_TAB_PARTITIONS....................................................................................................................................... 205
3.3.29 DB_TAB_STATISTICS.........................................................................................................................................207
3.3.30 DB_TRIGGERS.................................................................................................................................................... 209
3.3.31 DB_VIEWS........................................................................................................................................................... 209
3.3.32 DB_VIEW_COLUMNS........................................................................................................................................210
3.3.33 DB_VIEW_DEPENDENCIES............................................................................................................................. 210
3.3.34 ROLE_SYS_PRIVS.............................................................................................................................................. 211
3.3.35 MY_ARGUMENTS.............................................................................................................................................. 211
3.3.36 MY_COL_COMMENTS...................................................................................................................................... 212
3.3.37 MY_CONSTRAINTS........................................................................................................................................... 213
3.3.38 MY_CONS_COLUMNS.......................................................................................................................................215
3.3.39 MY_DEPENDENCIES......................................................................................................................................... 215
3.3.40 MY_FREE_SPACE............................................................................................................................................... 216
3.3.41 MY_HISTOGRAMS.............................................................................................................................................216
3.3.42 MY_INDEXES......................................................................................................................................................217
3.3.43 MY_IND_COLUMNS.......................................................................................................................................... 219
3.3.44 MY_IND_PARTITIONS....................................................................................................................................... 220
3.3.45 MY_IND_STATISTICS........................................................................................................................................ 221
3.3.46 MY_JOBS............................................................................................................................................................. 222
3.3.47 MY_OBJECTS...................................................................................................................................................... 223
3.3.48 MY_PART_COL_STATISTICS............................................................................................................................224
3.3.49 MY_PART_KEY_COLUMNS............................................................................................................................. 225
3.3.50 MY_PART_STORE...............................................................................................................................................226
3.3.51 MY_PART_TABLES............................................................................................................................................ 226
3.3.52 MY_PROCEDURES.............................................................................................................................................227
3.3.53 MY_ROLE_PRIVS............................................................................................................................................... 228
3.3.54 MY_SEGMENTS..................................................................................................................................................228
3.3.55 MY_SEQUENCES................................................................................................................................................229
3.3.56 MY_SOURCE....................................................................................................................................................... 229
3.3.57 MY_SQL_MAPS.................................................................................................................................................. 230
3.3.58 MY_SYNONYMS................................................................................................................................................ 230
3.3.59 MY_SYS_PRIVS.................................................................................................................................................. 231
3.3.60 MY_TABLES........................................................................................................................................................ 231
3.3.61 MY_TAB_COLS................................................................................................................................................... 233
3.3.62 MY_TAB_COLUMNS..........................................................................................................................................234
3.3.63 MY_TAB_COL_STATISTICS..............................................................................................................................236

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. vii


GaussDB 100
Database Reference (Standalone) Contents

3.3.64 MY_TAB_COMMENTS...................................................................................................................................... 237


3.3.65 MY_TAB_DISTRIBUTE......................................................................................................................................237
3.3.66 MY_TAB_MODIFICATIONS.............................................................................................................................. 238
3.3.67 MY_TAB_PARTITIONS...................................................................................................................................... 239
3.3.68 MY_TAB_PRIVS..................................................................................................................................................241
3.3.69 MY_TAB_STATISTICS........................................................................................................................................241
3.3.70 MY_TRIGGERS................................................................................................................................................... 243
3.3.71 MY_USERS.......................................................................................................................................................... 243
3.3.72 MY_VIEWS.......................................................................................................................................................... 244
3.3.73 MY_VIEW_COLUMNS.......................................................................................................................................245
3.4 Dynamic Performance Views..................................................................................................................................... 245
3.4.1 NLS_SESSION_PARAMETERS........................................................................................................................... 248
3.4.2 DV_ALL_TRANS...................................................................................................................................................249
3.4.3 DV_ARCHIVED_LOGS........................................................................................................................................ 249
3.4.4 DV_ARCHIVE_DEST_STATUS........................................................................................................................... 253
3.4.5 DV_ARCHIVE_GAPS........................................................................................................................................... 254
3.4.6 DV_ARCHIVE_THREADS................................................................................................................................... 255
3.4.7 DV_BACKUP_PROCESSES................................................................................................................................. 255
3.4.8 DV_BUFFER_POOLS............................................................................................................................................256
3.4.9 DV_BUFFER_POOL_STATS................................................................................................................................ 257
3.4.10 DV_CONTROL_FILES........................................................................................................................................ 258
3.4.11 DV_DATABASE................................................................................................................................................... 258
3.4.12 DV_DATA_FILES................................................................................................................................................ 260
3.4.13 DV_OBJECT_CACHE......................................................................................................................................... 261
3.4.14 DV_DC_POOLS................................................................................................................................................... 262
3.4.15 DV_DYNAMIC_VIEWS......................................................................................................................................263
3.4.16 DV_DYNAMIC_VIEW_COLS............................................................................................................................263
3.4.17 DV_FREE_SPACE................................................................................................................................................264
3.4.18 DV_HA_SYNC_INFO..........................................................................................................................................265
3.4.19 DV_HBA............................................................................................................................................................... 267
3.4.20 DV_INSTANCE.................................................................................................................................................... 267
3.4.21 DV_RUNNING_JOBS..........................................................................................................................................267
3.4.22 DV_LATCHS........................................................................................................................................................ 268
3.4.23 DV_LIBRARY_CACHE.......................................................................................................................................268
3.4.24 DV_LOCKS.......................................................................................................................................................... 269
3.4.25 DV_LOCKED_OBJECTS.................................................................................................................................... 270
3.4.26 DV_LOG_FILES...................................................................................................................................................270
3.4.27 DV_LONG_SQL...................................................................................................................................................272
3.4.28 DV_STANDBYS...................................................................................................................................................274
3.4.29 DV_ME................................................................................................................................................................. 275
3.4.30 DV_OPEN_CURSORS.........................................................................................................................................275
3.4.31 DV_PARAMETERS............................................................................................................................................. 276

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. viii


GaussDB 100
Database Reference (Standalone) Contents

3.4.32 DV_PL_MANAGER.............................................................................................................................................277
3.4.33 DV_PL_REFSQLS................................................................................................................................................278
3.4.34 DV_REACTOR_POOLS...................................................................................................................................... 279
3.4.35 DV_REPL_STATUS............................................................................................................................................. 280
3.4.36 DV_RESOURCE_MAP........................................................................................................................................ 280
3.4.37 DV_SEGMENT_STATS....................................................................................................................................... 280
3.4.38 DV_SESSIONS..................................................................................................................................................... 281
3.4.39 DV_SESSION_EVENTS...................................................................................................................................... 285
3.4.40 DV_SESSION_SHARED_LOCKS...................................................................................................................... 285
3.4.41 DV_SESSION_WAITS......................................................................................................................................... 286
3.4.42 DV_GMA.............................................................................................................................................................. 287
3.4.43 DV_GMA_STATS.................................................................................................................................................287
3.4.44 DV_SPINLOCKS..................................................................................................................................................289
3.4.45 DV_SQLS..............................................................................................................................................................290
3.4.46 DV_SQL_POOL................................................................................................................................................... 293
3.4.47 DV_SYS_STATS...................................................................................................................................................298
3.4.48 DV_SYSTEM........................................................................................................................................................302
3.4.49 DV_SYS_EVENTS...............................................................................................................................................303
3.4.50 DV_TABLESPACES.............................................................................................................................................303
3.4.51 DV_TEMP_POOLS.............................................................................................................................................. 304
3.4.52 DV_TEMP_UNDO_SEGMENT.......................................................................................................................... 305
3.4.53 DV_TRANSACTIONS......................................................................................................................................... 306
3.4.54 DV_UNDO_SEGMENTS.....................................................................................................................................307
3.4.55 DV_USER_ADVISORY_LOCKS........................................................................................................................308
3.4.56 DV_USER_ASTATUS_MAP............................................................................................................................... 308
3.4.57 DV_USER_PARAMETERS................................................................................................................................. 309
3.4.58 DV_VERSION...................................................................................................................................................... 309
3.4.59 DV_VM_FUNC_STACK......................................................................................................................................310
3.4.60 DV_WAIT_STATS................................................................................................................................................ 310
3.4.61 DV_XACT_LOCKS............................................................................................................................................. 310
3.4.62 DV_XACT_SHARED_LOCKS............................................................................................................................311
3.5 View Descriptions.......................................................................................................................................................311

4 Monitoring Alarms....................................................................................................................315
5 Interface Mapping (Basic Packages vs. Compatible Packages)........................................ 321
5.1 Data Dictionary Tables............................................................................................................................................... 321
5.2 DBA Views.................................................................................................................................................................323
5.3 User Views..................................................................................................................................................................325
5.4 Dynamic Performance Views..................................................................................................................................... 328
5.5 Configuration Parameters........................................................................................................................................... 330

6 Glossary....................................................................................................................................... 332

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ix


GaussDB 100
Database Reference (Standalone) 1 About This Document

1 About This Document

GaussDB 100 is an enterprise-level relational database engine developed by Huawei. It


features high performance, high availability, high scalability, and easy O&M; and can run
stably and efficiently on the x86 open architecture. GaussDB 100 supports SQL standards and
the syntax of mainstream commercial databases, facilitating application development and
migration. Using the secure, reliable storage provided by GaussDB 100 for relational and
structured data, you can develop and manage highly available, high-performance service
applications in finance, telecom, cloud, and industry digitalization fields.
The framework of GaussDB 100 is component-based and can be used for a standalone
database or a cluster. This document provides reference information about parameters, data
dictionaries, views, and wait events in GaussDB 100.
GaussDB 100 software packages are classified into basic and compatible packages. They
differ in the names of various interfaces. A compatible package is used to offer compatibility
with the usage habits of mainstream databases in the industry. The interfaces mentioned in
this document use names from basic packages. If you have installed compatible packages, you
can use either the interface names of basic packages or those of compatible packages by
referring to Interface Mapping (Basic Packages vs. Compatible Packages). For details
about how to install the basic and compatible packages, see "Installation and Deployment" in
GaussDB 100 V300R001C00 User Guide (Standalone).

Intended Audience
This document is intended for GaussDB 100 database users to help them obtain the database
information.
Before reading this document, you should be familiar with:
l Knowledge about a relational database. The theory helps you get familiar with GaussDB
100 and its usage.
l Knowledge about OSs. You will need it when you configure and run GaussDB 100.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Database Reference (Standalone) 1 About This Document

Change History
Version Change Description Date

03 Added: 2019-06-06
l Data dictionary tables WSR_LONGSQL
and WSR_SQL_LIST_PLAN
l Dynamic performance view in
DV_XACT_LOCKS
l HIGH_WATER_MARK column in
DV_DATA_FILES
l BLOCK_REPAIR_ENABLE in HA
l BLOCK_REPAIR_TIMEOUT in HA
l Time Zone
l Monitoring Alarms
Modified:
l Configuration suggestions of
VARIANT_MEMORY_AREA_SIZE,
LARGE_VARIANT_MEMORY_AREA
_SIZE, and
_VMP_CACHES_EACH_SESSION in
SGA
l Added field OPEN_INCONSISTENCY in
section DV_DATABASE.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Database Reference (Standalone) 1 About This Document

Version Change Description Date

02 Added: 2019-04-05
l HA
l TYPE_MAP_FILE in Data Type Control
Parameters
l SSL_EXPIRE_ALERT_THRESHOLD
and SSL_PERIOD_DETECTION in
Parameter Descriptions
l ZSQL_SSL_QUIET and
ZSQL_INTERACTION_TIMEOUT in
zsql Parameters
l LOG_REPLAY_PROCESSES in
Background Process
l TEMP_POOL_NUM in SGA
l _SERIALIZED_COMMIT in
Transactions
l _PRIVATE_KEY_LOCKS and
_PRIVATE_ROW_LOCKS in Session
Control Parameters
l UNDO_RESERVE_SIZE in
Transactions
l ARCH_CLEAN_IGNORE_STANDBY
in Archive Logs
l Data dictionary tables WSR_LATCH,
WSR_LIBRARYCACHE,
WSR_SEGMENT, WSR_SQL_LIST and
WSR_WAITSTAT
l Modified:
l Moved 32 ALL_* views from DBA Views
to User Views
l Moved the ROLE_SYS_PRIVS view from
DBA Views to User Views
l Moved NLS_SESSION_PARAMETERS
from DBA Views to Dynamic
Performance Views
Deleted:
l DBA_HIST_WAITSTAT view
l DBA_HIST_SEGMENT view
l DBA_HIST_LIBRARYCACHE view
l DBA_HIST_LATCH view
l 3.12.14 Debugging and Restriction
Information
l V$LOG_HISTORY view

01 This issue is the first official release. 2018-10-30

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Database Reference (Standalone) 2 Parameters

2 Parameters

GaussDB 100 provides parameters to control database system behavior. Do your best not to
modify these parameters after a database is installed. If the parameters require modification,
fully understand the impacts on GaussDB 100 before modifying them. Otherwise, unexpected
results may be generated.

To optimize a database, use the parameters provided in Advanced Optimization.

Precautions
l If the value range of a parameter is a string, the string should comply with the naming
conventions of the path and file name in the OS running the target database.
l If the maximum value of a parameter is INT_MAX, this value will vary by OS.
l If the maximum value of a parameter is DBL_MAX, this value will vary by OS.

Viewing Parameters
You can view a single parameter or all parameters of GaussDB 100, including their values,
and other details.

l You can run the SHOW command to check the parameters and their values.
For details about the SHOW command, see "Client Tools > zsql" in the GaussDB 100
V300R001C00 Operation Guide to Tools.
-- View a single parameter and its value:
SHOW PARAMETER parameter_name;

-- View all parameters and their values:


SHOW PARAMETER;

l You can query the DV_PARAMETERS view to check the configured values, default
values, value ranges, and data types of parameters, and check whether the parameters can
be modified.
For details about the DV_PARAMETERS view, see DV_PARAMETERS.
-- View a single parameter and its value:
SELECT parameter_name FROM DV_PARAMETERS;

-- View all parameters and their values:


SELECT * FROM DV_PARAMETERS;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Database Reference (Standalone) 2 Parameters

Modifying Parameters
You can modify the values and attributes of parameters in GaussDB 100.

l Modify a parameter value.


ALTER SYSTEM SET parameter_name = value;

l Modify a parameter attribute.


SET attr_name value;

For details about the attributes and modification commands of parameters, see "Managing the
Database System > Configuring the Database System" in GaussDB 100 V300R001C00 User
Guide (Standalone).

2.1 Databases
This section describes basic database parameters. You can adjust the parameters based on
service scenarios and data volume. Common users do not have permission to view database
parameters. Only user SYS is authorized to do so.

2.1.1 Parameter Overview

Table 2-1 Parameter overview

Parameter Default Database- Instance- Session- Dynamic


Value level level level Validation
Modificati Modificati Modificatio
on on n

CONTROL_F - Not Not Not supported Not


ILES supported supported supported

PAGE_SIZE 8K Supported Not Not supported Not


supported supported

DEFAULT_E 8 Supported Supported Not supported Supported


XTENTS

MAX_COLU 1024 Supported Supported Not supported Not


MN_COUNT supported

MAX_ARCH 16G Supported Supported Not supported Supported


_FILES_SIZE

ARCH_CLE FALSE Supported Supported Not supported Supported


AN_IGNORE
_BACKUP

ARCH_CLE FALSE Supported Supported Not supported Supported


AN_IGNORE
_STANDBY

ARCHIVE_D - Supported Supported Not supported Supported


EST_n

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Database- Instance- Session- Dynamic


Value level level level Validation
Modificati Modificati Modificatio
on on n

ARCHIVE_D ENABLE Supported Supported Not supported Supported


EST_STATE_
n

ARCHIVE_F arch_%r_ Supported Supported Not supported Not


ORMAT %s.arc supported

_UNDO_SEG 32 Supported Not Not supported Not


MENTS supported supported

_UNDO_ACT 32 Supported Supported Not supported Supported


IVE_SEGME
NTS

_UNDO_AUT TRUE Supported Supported Not supported Supported


O_SHRINK

UNDO_RESE 1024 Supported Supported Not supported Supported


RVE_SIZE

_TX_ROLLB 2 Supported Supported Not supported Not


ACK_PROC_ supported
NUM

PAGE_CHEC TYPICAL Supported Supported Not supported Not


KSUM supported

2.1.2 Control Files

CONTROL_FILES
Parameter description: Specifies the path of a control file, which is automatically generated
by the system and cannot be changed.

The file records the metadata information of a database, such as the database name, creation
timestamp, and names and locations of data files and redo files. You are advised to multiplex
a control file on different nodes or mirror it at the OS level.

Value range: a string

Default value: N/A

2.1.3 Page Management

PAGE_SIZE
Parameter description: Specifies the size of a page.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Database Reference (Standalone) 2 Parameters

This parameter can be set only when a database is created. In other cases, do not set or modify
this parameter.
After a database is started, this parameter becomes read-only. To modify the parameter, stop
the database and modify the configuration file. The modification takes effect after the
database is rebuilt.
Value range: 8K, 16K, 32K (unit: byte)
Default value: 8K

DEFAULT_EXTENTS
Parameter description: Specifies the number of pages in an extent.
If you do not specify the number of pages in an extent when creating a tablespace, the default
value will be used.
Value range: 8, 16, 32, 64, and 128
Default value: 8

2.1.4 Maximum Number of Columns Allowed


MAX_COLUMN_COUNT
Parameter description: Specifies the maximum number of columns allowed by a table.
l The value of this parameter can only be increased, but cannot be decreased. Any
modification takes effect only after a database is restarted.
l In HA mode, if this parameter is configured on a primary database, you need to
synchronize it to the standby. Otherwise, the build of the standby may fail.
Valid value: 1024, 2048, 3072, and 4096
Default value: 1024

In HA scenarios, the value of this parameter must be the same on the primary and standby
databases. Otherwise, a core dump will occur on the standby database.

2.1.5 Archive Logs


MAX_ARCH_FILES_SIZE
Parameter description: Specifies the maximum space that can be occupied by archive logs
generated by the current database. When the size of archive logs exceeds the maximum space,
the system clears the logs in time sequence.
Value range: an integer, in the range [0, 32 TB] (unit: byte) (Value 0 indicates that the
automatic archive clearance function is disabled and the space for storing archive logs is not
limited.)
Default value: 16G

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Database Reference (Standalone) 2 Parameters

ARCH_CLEAN_IGNORE_BACKUP
Parameter description: Specifies whether to ignore archive log backup during automatic
archive deletion.

Valid value:

l TRUE: An archive log meeting deletion conditions will be deleted no matter whether it
has been backed up.
l FALSE: An archive log meeting deletion conditions will not be deleted if it has not been
backed up.

Default value: FALSE

ARCH_CLEAN_IGNORE_STANDBY
Parameter description: Specifies whether to ignore standby nodes during automatic archive
deletion.

Valid value:

l TRUE: During archive deletion, standby nodes are ignored. Only rcy_point of the
primary node is used to determine whether archive files can be deleted.
l FALSE: During archive deletion, standby nodes are considered. The minimum
rcy_point among all the primary standby nodes is used to determine whether archive
files can be deleted.

Default value: FALSE

ARCHIVE_DEST_n
Parameter description: Specifies the destination for log archiving.

Value range: a string, in the following format:

l ARCHIVE_DEST_[1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ]={ LOCATION=path_name }


l ARCHIVE_DEST_[2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ]={ SERVICE=ip:port [SYNC |
ASYNC] [PRIMARY_ROLE | STANDBY_ROLE | ALL_ROLES] [LOCAL_HOST=ip]
| [AFFIRM | NOAFFIRM] }

Detailed parameter descriptions are as follows:

l LOCATION: Specifies the log archive address of the local host. For
ARCHIVE_DEST_1, only LOCATION can be used.
l SERVICE: Specifies the IP addresses, port numbers, and log synchronization modes of
the peer end. For ARCHIVE_DEST_2 to ARCHIVE_DEST_10, only SERVICE can
be used. Only in HA deployment or when one primary node has multiple standby nodes
are parameters ARCHIVE_DEST_2 to ARCHIVE_DEST_10 required.
l SYNC | ASYNC: Specifies the transmission mode of redo logs between primary and
standby databases. This parameter is optional. If it is not specified, the default value
SYNC will be used.
– SYNC: Redo logs are transmitted in synchronous mode.
– ASYNC: Redo logs are transmitted in asynchronous mode.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Database Reference (Standalone) 2 Parameters

l PRIMARY_ROLE | STANDBY_ROLE | ALL_ROLES: Specifies the scenario where


LOG_ARCHIVE_DEST_n takes effect. This parameter is optional. If it is not
specified, the default value ALL_ROLES will be used.
– PRIMARY_ROLE: ARCHIVE_DEST_n takes effect only when an instance is
primary.
– STANDBY_ROLE: ARCHIVE_DEST_n takes effect only when an instance is
standby.
– ALL_ROLES: ARCHIVE_DEST_n takes effect no matter whether an instance is
primary or standby.
l LOCAL_HOST: Specifies the IP address bound to the primary database if there are
multiple NICs on the host where the primary database resides or if a NIC has multiple IP
addresses. In other cases, this parameter is optional. If it is not set, no IP address is
bound by default.
l AFFIRM | NOAFFIRM: Specifies whether the primary database waits for the response
from the standby database before committing a transaction. This parameter is optional. If
this parameter is not specified, the default value NOAFFIRM is used.
– AFFIRM: Before committing a transaction, the primary database waits for the
standby database to receive logs and respond. This setting takes effect only if
SYNC is specified. If ASYNC is specified, AFFIRM is ignored.
– NOAFFIRM: Before committing a transaction, the primary database does not wait
for the standby database to receive logs or respond.
l ZSTD | LZ4: Specifies the compression algorithm used for link compression between
primary and standby databases. It can be left empty. If empty, the compression algorithm
is disabled by default.
– ZSTD: The zstd compression algorithm is used for link compression.
– LZ4: The lz4 compression algorithm is used for link compression.
Default value: N/A

ARCHIVE_DEST_STATE_n
Parameter description: Specifies the availability state of the corresponding destination,
ARCHIVE_DEST_n.
DV_ARCHIVE_DEST_STATUS, a dynamic performance view, displays the value used by
the current session. The DEST_ID column in this view corresponds to the suffix n.
Valid value:
ARCHIVE_DEST_STATE_[1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ]=
{ ENABLE | DEFER | ALTERNATE }
ENABLE means that a destination can be used for a subsequent archiving operation. DEFER
and ALTERNATE mean that a destination does not take effect.
Default value: ENABLE

ARCHIVE_FORMAT
Parameter description: Specifies the file format used when redo logs are archived.
Value range: a string

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Database Reference (Standalone) 2 Parameters

The value must contain %s (or %S) and %r (or %R), and cannot contain other % symbols
except %s, %ARCHIVE_FORMAT, %t, %T, %r, and %R.
ARCHIVE_FORMAT
l %s and %S: archive sequence number
l %t and %T: thread ID
l %r and %R: reset log ID
Default value: arch_%r_%s.arc

2.1.6 Transactions

_UNDO_SEGMENTS
Parameter description: Specifies the number of undo segments, which determines the
concurrency capability and total number of transactions.
This parameter can be set only when a database is created. In other cases, do not modify this
parameter.
After a database is started, this parameter becomes read-only. To modify the parameter, stop
the database and modify the configuration file. The modification takes effect after the
database is rebuilt.
Value range: an integer, in the range (0, 1024]
Default value: 32

_UNDO_ACTIVE_SEGMENTS
Parameter description: Specifies the number of active undo segments that can be used
currently.
Value range: an integer, in the range (0, 1024]. The value must be less than or equal to the
value of _UNDO_SEGMENTS.
Default value: 32

_UNDO_AUTO_SHRINK
Parameter description: Specifies whether to enable the automatic SHRINK UNDO
SEGMENT function.
Valid value:
l TRUE: Enable.
l FALSE: Do not enable.
Default value: TRUE

UNDO_RESERVE_SIZE
Parameter description: Specifies the number of undo pages reserved for an undo segment.
Value range: an integer, in the range [64, 1024]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Database Reference (Standalone) 2 Parameters

Default value: 1024

_TX_ROLLBACK_PROC_NUM
Parameter description: Specifies the number of background threads for rolling back residual
transactions.

Value range: an integer, in the range [1, 2]

Default value: 2

2.1.7 Data Correctness Verification

PAGE_CHECKSUM
Parameter description: Specifies whether to enable checksum verification for databases.

Valid value:

l OFF: Checksum verification is disabled.


l TYPICAL: Checksum verification is enabled. Checksums are calculated when pages are
exchanged between a disk and memory.
l FULL: Checksum verification is enabled. Pages require checksum calculation before
being modified in memory, and the modification can be made in real time.

Default value: TYPICAL

2.2 Instances
You can set database instance parameters to modify the number or size of buffers, logs,
sessions, and transactions.

2.2.1 Parameter Overview

Table 2-2 Parameter overview

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

LSNR_ADDR 127.0.0.1 Supporte Support Not Not


d ed supporte support
d ed

LSNR_PORT 1611 Supporte Support Not Not


d ed supporte support
d ed

REACTOR_THREADS 1 Supporte Support Not Not


d ed supporte support
d ed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

DATA_BUFFER_SIZE 128M Supporte Support Not Not


d ed supporte support
d ed

SHARED_POOL_SIZE 128M Supporte Support Not Not


d ed supporte support
d ed

_SQL_POOL_FACTOR 0.5 Supporte Support Not Not


d ed supporte support
d ed

VARIANT_MEMORY_AREA_ 32M Supporte Support Not Not


SIZE d ed supporte support
d ed

LARGE_VARIANT_MEMOR 32M Supporte Support Not Not


Y_AREA_SIZE d ed supporte support
d ed

_VMP_CACHES_EACH_SESS 8 Supporte Support Not Suppor


ION d ed supporte ted
d

LARGE_POOL_SIZE 32M Supporte Support Not Not


d ed supporte support
d ed

LOG_BUFFER_SIZE 4M Supporte Support Not Not


d ed supporte support
d ed

LOG_BUFFER_COUNT 4 Supporte Support Not Not


d ed supporte support
d ed

TEMP_BUFFER_SIZE 32M Supporte Support Not Not


d ed supporte support
d ed

TEMP_POOL_NUM 1 Supporte Support Not Not


d ed supporte support
d ed

USE_LARGE_PAGES TRUE Supporte Support Not Not


d ed supporte support
d ed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

_MAX_VM_FUNC_STACK_C 0 Supporte Support Not Suppor


OUNT d ed supporte ted in
d specific
scenari
os

CR_POOL_SIZE 32M Supporte Support Not Not


d ed supporte support
d ed

CR_POOL_COUNT 1 Supporte Support Not Not


d ed supporte support
d ed

SESSIONS 200 Supporte Support Not Suppor


d ed supporte ted in
d specific
scenari
os

AUTONOMOUS_SESSIONS 8 Supporte Support Not Not


d ed supporte support
d ed

KNL_AUTONOMOUS_SESSI 8 Supporte Support Not Not


ONS d ed supporte support
d ed

COMMIT_MODE IMMEDI Supporte Support Support Not


ATE d ed ed support
ed

COMMIT_WAIT_LOGGING WAIT Supporte Support Support Not


d ed ed support
ed

LOCK_WAIT_TIMEOUT 0 Supporte Support Support Suppor


d ed ed ted

DB_ISOLEVEL RC Supporte Support Not Suppor


d ed supporte ted
d

_SERIALIZED_COMMIT FALSE Supporte Support Not Not


d ed supporte support
d ed

TC_LEVEL 0 Supporte Support Not Suppor


d ed supporte ted
d

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

CHECKPOINT_PERIOD 300 Supporte Support Not Not


d ed supporte support
d ed

CHECKPOINT_PAGES 10000 Supporte Support Not Not


d ed supporte support
d ed

SQL_STAT TRUE Supporte Support Not Suppor


d ed supporte ted
d

TIMED_STATS TRUE Supporte Support Not Suppor


d ed supporte ted
d

STATISTICS_SAMPLE_SIZE 128M Supporte Support Not Suppor


d ed supporte ted
d

STATS_LEVEL TYPICA Supporte Support Not Not


L d ed supporte support
d ed

_MAX_CONNECT_BY_LEVE 256 Supporte Support Not Suppor


L d ed supporte ted
d

DBWR_PROCESSES 1 Supporte Support Not Not


d ed supporte support
d ed

LOG_REPLAY_PROCESSES 1 Supporte Support Not Not


d ed supporte support
d ed

UNDO_RETENTION_TIME 100 Supporte Support Not Suppor


d ed supporte ted
d

7.1.2.11-REPL_ADDR - Supporte Support Not Not


d ed supporte support
d ed

REPL_PORT 0 Supporte Support Not Not


d ed supporte support
d ed

REPL_WAIT_TIMEOUT 10 Supporte Support Not Suppor


d ed supporte ted
d

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

REPL_TRUST_HOST - Supporte Support Not Suppor


d ed supporte ted
d

FILE_OPTIONS NONE Supporte Support Not Not


d ed supporte support
d ed

ALARM_LOG_DIR - Supporte Support Not Not


d ed supporte support
d ed

INSTANCE_NAME zenith Supporte Support Not Not


d ed supporte support
d ed

DB_FILE_NAME_CONVERT - Supporte Support Not Not


d ed supporte support
d ed

LOG_FILE_NAME_CONVER - Supporte Support Not Not


T d ed supporte support
d ed

RECYCLEBIN TRUE Supporte Support Not Suppor


d ed supporte ted
d

BUF_POOL_NUM 1 Supporte Support Not Not


d ed supporte support
d ed

SQL_COMPAT GSDB Supporte Support Not Not


d ed supporte support
d ed

CR_MODE PAGE Supporte Support Not Not


d ed supporte support
d ed

DROP_NOLOGGING FALSE Supporte Support Support Suppor


d ed ed ted

_AUTO_INDEX_RECYCLE ON Supporte Support Not Not


d ed supporte support
d ed

_LNS_WAIT_TIME 3 Supporte Support Not Suppor


d ed supporte ted
d

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

ENABLE_RAFT FALSE Supporte Support Not Not


d ed supporte support
d ed

RAFT_START_MODE 0 Supporte Support Not Not


d ed supporte support
d ed

RAFT_NODE_ID - Supporte Support Not Not


d ed supporte support
d ed

RAFT_PEER_IDS - Supporte Support Not Not


d ed supporte support
d ed

RAFT_LOCAL_ADDR - Supporte Support Not Not


d ed supporte support
d ed

RAFT_PEER_ADDRS - Supporte Support Not Not


d ed supporte support
d ed

RAFT_LOG_LEVEL 2 Supporte Support Not Not


d ed supporte support
d ed

RAFT_KUDU_DIR - Supporte Support Not Not


d ed supporte support
d ed

RAFT_PRIORITY_TYPE External Supporte Support Not Not


d ed supporte support
d ed

RAFT_PRIORITY_LEVEL '0' Supporte Support Not Not


d ed supporte support
d ed

RAFT_LAYOUT_INFO - Supporte Support Not Not


d ed supporte support
d ed

RAFT_PENDING_CMDS_BU '1000' Supporte Support Not Not


FFER_SIZE d ed supporte support
d ed

RAFT_SEND_BUFFER_SIZE '100' Supporte Support Not Not


d ed supporte support
d ed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

RAFT_RECEIVE_BUFFER_SI '100' Supporte Support Not Not


ZE d ed supporte support
d ed

RAFT_RAFT_ENTRY_CACH '2147483 Supporte Support Not Not


E_MEMORY_SIZE 648' d ed supporte support
d ed

RAFT_MAX_SIZE_PER_MSG '1342177 Supporte Support Not Not


28' d ed supporte support
d ed

RAFT_LOG_ASYNC_BUF_N 16 Supporte Support Not Not


UM d ed supporte support
d ed

MAX_TEMP_TABLES 256 Supporte Support Not Not


d ed supporte support
d ed

LOCAL_TEMPORARY_TABL FALSE Supporte Support Not Suppor


E_ENABLED d ed supporte ted
d

TYPE_MAP_FILE - Supporte Not Not Not


d supporte supporte support
d d ed

USE_NATIVE_DATATYPE TRUE Supporte Support Not Not


d ed supporte support
d ed

CBO (Cost-Based-Optimize) OFF Supporte Support Not Suppor


d ed supporte ted
d

JOB_THREADS 100 Supporte Support Not Suppor


d ed supporte ted
d

TABLESPACE_USAGE_ALA 80 Supporte Support Not Suppor


RM_THRESHOLD d ed supporte ted
d

_RCY_CHECK_PCN TRUE Supporte Support Not Suppor


d ed supporte ted
d

DB_TIMEZONE 00:00 Supporte Support Support Suppor


d ed ed ted

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Databas Instanc Session Dyna


Value e-level e-level -level mic
Modific Modifi Modifi Valida
ation cation cation tion

BLOCK_REPAIR_ENABLE FALSE Supporte Support Support Suppor


d ed ed ted

BLOCK_REPAIR_TIMEOUT 60 Supporte Support Support Suppor


d ed ed ted

2.2.2 Server Listening

LSNR_ADDR
Parameter description: Specifies the listening IP address of the server.
Value range: a valid IPv4 or IPv6 address
Default value: 127.0.0.1

LSNR_PORT
Parameter description: Specifies the listening port of the server.
Value range: an integer, in the range [1024, 65535]
Default value: 1611

2.2.3 Separation Between Sessions and Worker Threads

REACTOR_THREADS
Parameter description: Specifies the number of threads for I/O listening.
l The recommended value is OPTIMIZED_WORKER_THREADS divided by 50.
l If this parameter is set too large, more CPU, memory, and thread resources will be
occupied. When resources are insufficient, database exceptions may occur.
Value range: a positive integer, in the range [1, 30000]
Default value: 1

2.2.4 SGA

CR_POOL_SIZE
Parameter description: Specifies the size of a consistency read page buffer (that is, a CR
pool).
Set this parameter based on the actual memory size. A larger value can accelerate data access
in concurrency scenarios.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: an integer, in the range [16 MB, 32 TB] (unit: byte)
Default value: 32M
Remarks: In concurrent access scenarios, the current data page may not be visible to the
current session, and a visible page needs to be constructed by using a transaction, called a
consistency read page.

CR_POOL_COUNT
Parameter description: Specifies the number of consistency read page sub-buffers (that is,
CR sub-pools).
Set this parameter based on the actual memory size. A larger value can release the
competition between sessions and accelerate data access in concurrency scenarios.
Value range: an integer, in the range [1, 256]
Default value: 1

DATA_BUFFER_SIZE
Parameter description: Specifies the size of a data buffer, which is used for recently
accessed data.
Value range: an integer, in the range [64 MB, 32 TB] (unit: byte)
Set this parameter based on the actual memory size. A larger value can accelerate data access.
Default value: 128M

SHARED_POOL_SIZE
Parameter description: Specifies the size of a shared pool.
A shared pool contains space shared by Lock, SQL, and DC pools.
Value range: an integer, in the range [82 MB, 32 TB] (unit: byte)
Set this parameter based on the actual memory size. A larger value can accelerate data access.
Default value: 128M

_SQL_POOL_FACTOR
Parameter description: Specifies the maximum proportion of SQL pools in a shared pool.
l The maximum proportion of DC pools in the shared pool is 1 minus
_SQL_POOL_FACTOR.
l When DC pools are insufficient (record the number of all pages in the DC pools as B),
use dv_gma_stats to check the number of pages in the SQL pools and record it as A.
The recommended ratio is 0.8A:B. In special scenarios, you need to test different
configurations to determine the optimal choice.
Value range: a number, in the range [0.001, 0.999]
Default value: 0.5
Remarks:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Database Reference (Standalone) 2 Parameters

VARIANT_MEMORY_AREA_SIZE
Parameter description: Specifies the size of the virtual memory area (VMA) that is used to
store variables (such as bind parameters) less than 16 KB during execution. The size of a page
in the area is 16 KB. The setting takes effect only after a restart.

Value range: a number, in the range [4 MB, 32 TB]

Default value: 32M

Setting notes: For database installation, you are advised to set this parameter to 16 KB x
_VMP_CACHES_EACH_SESSION x SESSIONS x 1.1. For database upgrade, you are
advised to set this parameter to _VARIANT_AREA_SIZE x SESSIONS x 0.8.

LARGE_VARIANT_MEMORY_AREA_SIZE
Parameter description: Specifies the size of the large VMA that is used to store variables
(such as bind parameters) less than 256 KB during execution. The size of a page in the area is
256 KB. The setting takes effect only after a restart.

Value range: a number, in the range [1 MB, 32 TB]

Default value: 32M

Setting notes: For database installation, retain the default value of this parameter. For database
upgrade, you are advised to set this parameter to _VARIANT_AREA_SIZE x SESSIONS x
0.2.

NOTE

If there are too many bind parameters (for example, more than 1000) and frequent statement executions,
you are advised to increase the value of LARGE_VARIANT_MEMORY_AREA_SIZE.

_VMP_CACHES_EACH_SESSION
Parameter description: Specifies the number of 16 KB VMA pages that can be cached in
each session (256 KB pages are not cached). When the remaining memory of VMA is less
than 10%, the pages of some sessions are not cached. Try to maintain over 10% remaining
memory. The setting takes effect immediately.

Value range: a number, in the range [0, 4294967295]

Default value: 8

Setting notes: For database installation, retain the default value of this parameter. For database
upgrade, you can also use the default value. However, if the result of
_VMP_CACHES_EACH_SESSION x SESSIONS x 16 K is much greater than the value of
VARIANT_MEMORY_AREA_SIZE, you are advised to reduce the value of
_VMP_CACHES_EACH_SESSION. A value greater than 4 is recommended for
performance purposes.

NOTE

An improper memory configuration does not affect statement functionality but does affect statement
performance and OS memory stability (there may be continuous application to the OS for memory
resources and frequent memory release operations).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Database Reference (Standalone) 2 Parameters

LARGE_POOL_SIZE
Parameter description: Specifies the size of a large pool.

Value range: an integer, in the range [4 MB, 32 TB] (unit: byte)

Set this parameter based on the actual memory size. A larger value can accelerate data access.

Default value: 32M

LOG_BUFFER_SIZE
Parameter description: Specifies the size of a log buffer, which is used for redo logs.

Value range: an integer, in the range [1 MB, 128 MB] (unit: byte)

Set this parameter based on the actual memory size. A larger value can accelerate data access.

Default value: 4M

LOG_BUFFER_COUNT
Parameter description: Specifies the number of log buffers.

Value range: an integer, in the range (0, 16]

Default value: 4

TEMP_BUFFER_SIZE
Parameter description: Specifies the size of a temporary buffer.

Value range: an integer, in the range [32 MB, 21 TB] (unit: byte)

Set this parameter based on the actual memory size. A larger value can accelerate data access.

Default value: 32M

TEMP_POOL_NUM
Parameter description: Specifies the number of temporary pools (or temporary buffer
partitions).

Each session is mapped to a temporary pool based on its ID during startup. Later, a session
will be allocated VM pages from the temporary pool.

Value range: an integer, in the range [1, 128]

Default value: 1

USE_LARGE_PAGES
Parameter description: Specifies how to manage the database's use of large pages for SGA
memory.

Valid value:

l TRUE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Database Reference (Standalone) 2 Parameters

Specifies that the instance can use large pages if large pages are configured on the
system.
l FALSE
Specifies that the instance will not use large pages. This value is not recommended
because it can cause severe performance degradation on the instance.
Default value: TRUE

_MAX_VM_FUNC_STACK_COUNT
Parameter description: Records the stack information about applying for VMs in the range
[vmid = 0, _MAX_VM_FUNC_STACK_COUNT – 1] in a temporary pool. This
parameter is used with the DV_VM_FUNC_STACK view. If this parameter is set to 0, the
stack information will not be recorded. If the initial value of
_MAX_VM_FUNC_STACK_COUNT is 0 upon startup, you have one chance to change it
to a non-0 value during system runtime and make the change take effect immediately.
Otherwise, the change takes effect only after a startup.
Value range: an integer, in the range [0, 4294967295]
Default value: 0

2.2.5 Sessions
SESSIONS
Parameter description: Specifies the upper limit of concurrent sessions in the system.
Value range: an integer, in the range [64,8192] by default
Default value: 200
Note:
1. The value of SESSIONS is the upper limit of concurrent sessions. It contains 64 sessions
reserved for the system and sessions available to users.
2. The system reserves the number of sessions set by
SUPER_USER_RESERVED_SESSIONS user sys. The sum of SESSIONS and
SUPER_USER_RESERVED_SESSIONS cannot exceed 8192.
3. The minimum value of SESSIONS is 64. The system reserves 64 sessions
(AUTONOMOUS_SESSIONS + KNL_AUTONOMOUS_SESSIONS + 32 internal
sessions used for resource reclamation and checkpoints + 16 sessions for the SQL
parallel framework).
– If the sum of AUTONOMOUS_SESSIONS and
KNL_AUTONOMOUS_SESSIONS is less than or equals 16, the minimum value
of SESSIONS is 64.
– If the sum of AUTONOMOUS_SESSIONS and
KNL_AUTONOMOUS_SESSIONS is greater than 16, the value of SESSIONS
must be greater than or equal AUTONOMOUS_SESSIONS +
KNL_AUTONOMOUS_SESSIONS + 32 + 16. If the values of SESSIONS,
AUTONOMOUS_SESSIONS and KNL_AUTONOMOUS_SESSIONS are
modified and do not meet the preceding requirements, the database cannot be
restarted.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Database Reference (Standalone) 2 Parameters

4. You are advised to set SESSIONS to OPTIMIZED_WORKER_THREADS x 1.2.


5. The modification of SESSIONS can take effect immediately or after restart. The initial
parameter SESSIONS=init_count is takes effect for each startup of the database,
reserving 50% of the space for table-level locks (1.5 x init_count ≤ 8192).
– The modification takes effect immediately if the value of SESSIONS is greater
than the minimum default value but less than 1.5 x init_count.
– The modification takes effect after restart if the value of SESSIONS is greater than
1.5 x init_count but less than 8192.

AUTONOMOUS_SESSIONS
Parameter description: Specifies the maximum number of concurrent sessions in an
autonomous transaction.

Value range: an integer, in the range (0, 256]

Default value: 8

KNL_AUTONOMOUS_SESSIONS
Parameter description: Specifies the maximum number of concurrent sessions in an
autonomous transaction of a storage engine.

Value range: an integer, in the range (0, 256]

Default value: 8

2.2.6 Transactions

COMMIT_MODE
Parameter description: Specifies how logs are written to disks. It is an advanced parameter.

Valid value:

l IMMEDIATE: immediate processing. Transactions are not buffered and will be written
to disks immediately once received. This method reduces transaction throughput.
l BATCH: buffering before batch processing. Redo records of transactions are logged and
will be batch written to disks after reaching a certain number.

Default value: IMMEDIATE

COMMIT_WAIT_LOGGING
Parameter description: Specifies whether to wait for relevant redo logs to be written to disks
in a transaction.

Valid value:

l WAIT: Perform a transaction after relevant redo logs are written to disks.
l NOWAIT: Perform a transaction without waiting for relevant redo logs to be written to
disks.

Default value: WAIT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Database Reference (Standalone) 2 Parameters

LOCK_WAIT_TIMEOUT
Parameter description: Specifies a transaction waiting threshold. If the waiting time exceeds
the threshold, an error will be reported.
Value range: an integer, in the range [0, 2^32 – 1] (unit: ms)
Default value: 0, which means infinite waiting

DB_ISOLEVEL
Parameter description: Specifies the transaction isolation level to ensure that no dirty data is
read.
Valid value:
l RC: It is short for Read Committed. At this level, data read by an SQL statement is the
data of the same snapshot.
l CC: It is short for Current Committed. At this level, data read by an SQL statement is
the latest committed data at the read time. All read data is no longer of the same
snapshot.
Default value: RC

_SERIALIZED_COMMIT
Parameter description: Specifies whether to commit a transaction in serialization mode.
Valid value: TRUE, FALSE
Default value: FALSE

TC_LEVEL
Parameter description: Specifies a transaction compensation level. If the value is greater
than 0, a pending transaction generated when there is a network fault can be automatically
handled after the fault is fixed.
Value range: an integer, in the range [0, 2^32 – 1]
Default value: 0

2.2.7 Checkpoints
CHECKPOINT_PERIOD
Parameter description: Specifies an interval between every two checkpoints. When an
interval reaches this value, an incremental checkpoint will be triggered.
Value range: an integer, in the range [1, 2^32 – 1] (unit: second)
Default value: 300

CHECKPOINT_PAGES
Parameter description: Specifies the number of redo logs between two checkpoints. When
the number reaches this value, a checkpoint is triggered.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: an integer, in the range [1, 2^32 – 1]


Default value: 100000

2.2.8 Performance Statistics


SQL_STAT
Parameter description: Specifies whether to enable the SQL performance statistics view.
This parameter takes effect on an entire instance.
Valid value: TRUE, FALSE
Default value: TRUE

TIMED_STATS
Parameter description: Specifies whether to collect time-related statistics.
Valid value:
l TRUE: The statistics are collected and stored in trace files or displayed in the dynamic
performance view DV_SYS_STATS.
l FALSE: The values of all time-related statistics are set to zero.
Default value: TRUE

STATISTICS_SAMPLE_SIZE
Parameter description: Specifies a default sample size for gathering and analyzing statistics
related to database tables.
Value range: an integer, in the range [32 MB, 4 GB) (unit: byte)
Default value: 128M

STATS_FORCE_SAMPLE
Parameter description: Specifies whether to enable the function of limiting the maximum
sampling size for collecting statistics.
Valid value:
l TRUE: The system checks whether the size of table data to be analyzed exceeds the
default sampling size (specified by STATISTICS_SAMPLE_SIZE) during statistics
collection. If it does, only the specified size of data will be analyzed.
l FALSE: Statistics collection is not limited by the default sampling size, and a user-
defined sampling size can be used.
Default value: FALSE

STATS_LEVEL
Parameter description: Specifies whether to collect statistics about DML operations on the
table level.
Valid value:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Database Reference (Standalone) 2 Parameters

l TYPICAL/ALL:
Table monitoring is enabled. Statistics about the DML operations on tables will be
collected and displayed in the system catalog SYS_DML_STATS 15 minutes later.
l BASIC: Table monitoring is disabled.

Default value: TYPICAL

STATS_COST_LIMIT
Parameter description: Specifies the number of pages for collecting statistics in flow control
mode.

Value range: an integer, in the range [0, 2^32 – 1]

Default value: 0

STATS_COST_DELAY
Parameter description: Specifies the I/O wait time for collecting statistics in flow control
mode.

Value range: an integer, in the range [0, 2^32 – 1]

Default value: 0

2.2.9 SQL Resource Limit

_MAX_CONNECT_BY_LEVEL
Parameter description: Specifies the upper limit of CONNECT BY LEVEL. If the value of
CONNECT BY LEVEL in a SQL statement exceeds this limit, an error will be reported.

This parameter restricts the depth of recursion for CONNECT BY. If its value is too large,
memory overflow may occur in the thread stack. Determine its value based on the OS
parameter RLIMIT_STACK and the zengine parameter _THREAD_STACK_SIZE. The
thread stack size depends on RLIMIT_STACK. If RLIMIT_STACK is not configured, the
size depends on _THREAD_STACK_SIZE.

l If the thread stack size is 512K, the maximum value of


_MAX_CONNECT_BY_LEVEL is 2150.
l If the size of the thread stack is 1M, the maximum value of
_MAX_CONNECT_BY_LEVEL is 4300.
l If the thread stack size is 2M, the maximum value of _MAX_CONNECT_BY_LEVEL
is 8600.

So on and so forth.

Value range: an integer, in the range [0, 2^32 – 1]

Default value: 256

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.2.10 Background Process

DBWR_PROCESSES
Parameter description: Specifies the number of background threads for writing dirty pages.
A larger value of this parameter helps improve concurrency performance but causes more
resources to be consumed.
Value range: an integer, in the range [1, 36]
Default value: 1

LOG_REPLAY_PROCESSES
Parameter description: Specifies the number of redo log replay threads.
A larger value of this parameter helps improve concurrency performance but causes more
resources to be consumed.
Value range: an integer, in the range [1, 8]
Default value: 1

2.2.11 HA

REPL_ADDR
Parameter description: Specifies the listening IP address of the server for primary/standby
communication. If this parameter is specified, the IP address will be used for primary/standby
replication. Otherwise, LSNR_ADDR will be used.
Value range: a valid IPv4 or IPv6 address
Default value: none

REPL_PORT
Parameter description: Specifies a port on a standby node for primary-standby
communication.
Value range: 0, or in the range [1024, 65535]
Default value: 0, indicating that the port is not listened and no lsnr thread is started on it. To
listen to the port, select a value from the range [1024, 65535].

REPL_WAIT_TIMEOUT
Parameter description: If no message is exchanged between primary and standby nodes
within the period specified by REPL_WAIT_TIMEOUT, the primary-standby link will be
considered abnormal, and the primary or standby node will proactively disconnect from each
other.
Value range: an integer, in the range [3, 2^32 – 1] (unit: second)
Default value: 10

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Database Reference (Standalone) 2 Parameters

REPL_TRUST_HOST
Parameter description: Specifies the whitelist of primary and standby nodes for connection.
If the IP address bound to the connection initiator is included in REPL_TRUST_HOST, the
peer end will receive the connection request.

Value range: 0 to 8 valid IP addresses, separated by commas (,)

Default value: an empty string

DB_FILE_NAME_CONVERT
Parameter description: Specifies mapping relationships between data file paths on primary
and standby nodes.

After this parameter is set, a standby node will modify its data file paths based on the
mapping relationships. This parameter does not take effect on the primary node, except when
it is demoted to standby.

Value range: Data file paths of primary and standby nodes. The format is as follows (with
one primary node and two standby nodes as an example):

Primary node A: data file path on standby node B, data file path on primary node A, data file
path on standby node C, data file path on primary node A ... (A maximum of 10 mapping
relationships are supported.)

Standby node B: data file path on primary node A, data file path on standby node B, data file
path on standby node C, data file path on standby node B ... (A maximum of 10 mapping
relationships are supported.)

Standby node C: data file path on primary node A, data file path on standby node C, data file
path on standby node B, data file path on standby node C ... (A maximum of 10 mapping
relationships are supported.)

You need to configure all the relationships between the local and peer nodes. However, only
those between the primary and standby nodes take effect. Each mapping relationship has the
peer path coming first and then the local path. Multiple data file paths can be configured, and
they all take effect.

Default value: N/A, indicating that the data file paths on a standby node are consistent with
those on the primary node

LOG_FILE_NAME_CONVERT
Parameter description: Specifies mapping relationships between redo log file paths on
primary and standby nodes.

After this parameter is set, a standby node will modify its log file paths based on the mapping
relationships. This parameter does not take effect on the primary node, except when it is
demoted to standby.

Value range: Log file paths of primary and standby nodes. The format is as follows (with one
primary node and two standby nodes as an example):

Primary node A: log file path on standby node B, log file path on primary node A, log file
path on standby node C, log file path on primary node A ... (A maximum of 10 mapping
relationships are supported.)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Database Reference (Standalone) 2 Parameters

Standby node B: log file path on primary node A, log file path on standby node B, log file
path on standby node C, log file path on standby node B ... (A maximum of 10 mapping
relationships are supported.)

Standby node C: log file path on primary node A, log file path on standby node C, log file
path on standby node B, log file path on standby node C ... (A maximum of 10 mapping
relationships are supported.)

You need to configure all the relationships between the local and peer nodes. However, only
those between the primary and standby nodes take effect. Each mapping relationship has the
peer path coming first and then the local path. Multiple log file paths can be configured, and
they all take effect.

Default value: N/A, indicating that the redo log file paths on a standby node are consistent
with those on the primary node

_LNS_WAIT_TIME
Parameter description: Specifies the interval at which an lns thread needs to wait before
sending logs. Value 0 indicates no wait.

Value range: an integer, in the range [0, 2^32 – 1] (unit: ms)

Default value: 3

BLOCK_REPAIR_ENABLE
Parameter description: Specifies whether to enable the function of automatically repairing
fault data pages by using a standby node.

Valid value:

l TRUE: When a disk page of a primary node is damaged, the system automatically
obtains the correct disk page from a standby node and repairs the damaged disk page.
l FALSE: The function is disabled on a primary node.

Default value: FALSE

BLOCK_REPAIR_TIMEOUT
Parameter description: Specifies the timeout period for the system to obtain a correct page
from a standby node when the automatic data page repair function is enabled on the primary
node.

Value range: an integer, in the range [1, 3600] (unit: second)

Default value: 60

2.2.12 GS-Paxos Replication


Note that GS-Paxos replication is unavailable in standalone deployment and related
parameters do not take effect.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Database Reference (Standalone) 2 Parameters

ENABLE_RAFT
Parameter description: Specifies whether to enable the GS-Paxos replication function. In a
standalone database, if ENABLE_RAFT is set to TRUE, the RAFT function becomes
unavailable, and restarting a process will cause an error.

Valid value:

l TRUE: Enable.
l FALSE: Do not enable.

Default value: FALSE

RAFT_START_MODE
Parameter description: Specifies a GS-Paxos startup mode.

Valid value:

l 0: It means a normal mode. GS-Paxos or Kudu metadata must have been initialized.
l 1: GS-Paxos or Kudu metadata is initialized.
l 2: An existing GS-Paxos cluster is joined.
l 3: It means a forcible startup of a single node. GS-Paxos or Kudu metadata will be re-
initialized.

Default value: 0

RAFT_NODE_ID
Parameter description: Specifies the ID of a local node, used for a GS-Paxos cluster to
identify each member node.

Value range: an integer, in the range [1, 2^32 – 1]

Default value: N/A

RAFT_PEER_IDS
Parameter description: Specifies a string consisting of IDs of all nodes in a cluster.

Active nodes are separated by commas (,). If there are passive nodes, they are separated from
active nodes by semicolons (;) and from other passive nodes by commas (,).

Value range: a string

Default value: N/A

RAFT_LOCAL_ADDR
Parameter description: Specifies IP:Port of a local node.

Value range: an IP address. The port is the one used for each member in a GS-Paxos cluster
to communicate.

Default value: N/A

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Database Reference (Standalone) 2 Parameters

RAFT_PEER_ADDRS
Parameter description: Specifies a string consisting of addresses of all nodes in a cluster,
separated by commas (,). These addresses must be in one-to-one mapping with the IDs in
RAFT_PEER_IDS.
Value range: a string
Default value: N/A

RAFT_LOG_LEVEL
Parameter description: Specifies the level for printing GS-Paxos logs.
Value range: [0, 6]
l 0: No logs are printed.
l 1: Logs of the debug level are printed.
l 2: Logs of the info level are printed.
l 3: Logs of the warning level are printed.
l 4: Logs of the error level are printed.
l 5: Logs of the fatal level are printed.
l 6: Logs of the panic level are printed.
Default value: 2

RAFT_KUDU_DIR
Parameter description: Specifies the storage directory of Kudu, storing GS-Paxos or Kudu
metadata.
Value range: a string
Default value: N/A

RAFT_PRIORITY_TYPE
Parameter description: Specifies the GS-Paxos self-quorum type. The options are as
follows:
Valid value:
l External: external quorum mode
l Random: RANDOM quorum mode
l Static: static quorum mode based on priority
l AZFirst: dynamic quorum mode based on AZ priority
Default value: External

RAFT_PRIORITY_LEVEL
Parameter description: Specifies the priority of selecting a primary node in a self-quorum.
This parameter is valid only if RAFT_PRIORITY_TYPE=Static is set.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: a string from '0' to '16'. The value can only be an integer enclosed in single
quotation marks (' ').
The value 0 indicates that no selection is performed. Among other values, the smaller the
value is, the higher the priority is. You are advised to set this parameter to a value less than or
equal to 3.
Default value: '0'

RAFT_LAYOUT_INFO
Parameter description: Path of the cluster topology information file
This parameter is valid only if RAFT_PRIORITY_TYPE=AZFirst is set.
Value range: a string
Default value: N/A

RAFT_PENDING_CMDS_BUFFER_SIZE
Parameter description: Specifies the length of a write or callback queue in Paxos.
A large value indicates high tolerance during performance or network jitter but will increase
memory usage. Do not modify this parameter unless absolutely necessary.
Value range: a string from '1' to '2^32–1'. The value can only be an integer enclosed in
single quotation marks (' '). The unit is byte.
Default value: '1000'

RAFT_SEND_BUFFER_SIZE
Parameter description: Specifies the length of the message sending queue in Paxos.
A large value indicates high tolerance during performance or network jitter but will increase
memory usage. Do not modify this parameter unless absolutely necessary.
Value range: a string from '1' to '10000'. The value can only be an integer enclosed in single
quotation marks (' '). The unit is byte.
Default value: '100'

RAFT_RECEIVE_BUFFER_SIZE
Parameter description: Specifies the length of the message receiving queue in Paxos.
A large value indicates high tolerance during performance or network jitter but will increase
memory usage. Do not modify this parameter unless absolutely necessary.
Value range: a string from '1' to '10000'. The value can only be an integer enclosed in single
quotation marks (' '). The unit is byte.
Default value: '100'

RAFT_RAFT_ENTRY_CACHE_MEMORY_SIZE
Parameter description: Specifies the size of the log cache in Paxos.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Database Reference (Standalone) 2 Parameters

A large value indicates high tolerance during performance or network jitter but will increase
memory usage. Do not modify this parameter unless absolutely necessary.
Value range: a string from '1' to '2^32–1'. The value can only be an integer enclosed in
single quotation marks (' '). The unit is byte.
Default value: '2147483648'

RAFT_MAX_SIZE_PER_MSG
Parameter description: Specifies the maximum size of a message in Paxos.
Value range: a string from '67108864' to '2^32–1'. The value can only be an integer
enclosed in single quotation marks (' '). The unit is byte.
Default value: '134217728'

RAFT_LOG_ASYNC_BUF_NUM
Parameter description: Specifies the number of asynchronous buffers in the Raft protocol.
Value range: an integer, in the range [1, 128]
Default value: 16

2.2.13 Local Temporary Tables


MAX_TEMP_TABLES
Parameter description: Specifies the maximum number of temporary tables that can be
opened by a session, including global temporary tables and local temporary tables.
Value range: a positive integer, in the range [64, 8192]
Default value: 256

LOCAL_TEMPORARY_TABLE_ENABLED
Parameter description: Specifies whether local temporary tables can be created.
Valid value:
l TRUE: Local temporary tables can be created.
l FALSE: Local temporary tables cannot be created.
Default value: FALSE

2.2.14 Data Type Control Parameters


USE_NATIVE_DATATYPE
Parameter description: Maps some confused numeric keywords to definite numeric data
types. GaussDB 100 provides this parameter to meet the compatibility requirements of
different databases and enrich the data types in databases. To be compatible with original
keywords, some keywords are directly mapped to the corresponding types regardless of the
USE_NATIVE_DATATYPE setting.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Database Reference (Standalone) 2 Parameters

l Any modification of the USE_NATIVE_DATATYPE parameter will take effect after a


restart. For objects created before parameter validation, the system retains their original
definitions and will not modify them to adapt to the new parameter setting. For tables
created after parameter validation, the system generates table definitions according to the
latest parameter configuration.
l To export table definitions from a logic backup, use only the keywords that are not
affected by USE_NATIVE_DATATYPE.

Valid value:
A keyword will be mapped to different data types when USE_NATIVE_DATATYPE is set
to TRUE or FALSE. For details, see Table 2-3.
l TRUE: Confused keywords are mapped to the primitive data types of C-like languages.
This mode is compatible with MySQL and PostgreSQL data types.
l FALSE: All keywords of numeric data types are mapped to NUMBER. This mode is
compatible with Oracle data types.
In principle, some keywords are not affected by the USE_NATIVE_DATATYPE
parameter, including BINARY_BIGINT, BINARY_INTEGER, and
BINARY_DOUBLE.

Table 2-3 Data type mapping


Data Type Keyword Data Type After Data Type After Conversion
Conversion for Value for Value TRUE
FALSE

BIGINT NUMBER(38) BINARY_BIGINT

DOUBLE NUMBER BINARY_DOUBLE

FLOAT NUMBER BINARY_DOUBLE

INT NUMBER(38) BINARY_INTEGER


INTEGER

REAL NUMBER BINARY_DOUBLE

SMALLINT NUMBER(38) BINARY_INTEGER

TINYINT NUMBER(38) BINARY_INTEGER

Default value: TRUE

TYPE_MAP_FILE
Parameter description: Specifies the directory of type mapping files. This parameter is read-
only.
This parameter is valid only when USE_NATIVE_DATATYPE is set to TRUE.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: a string, no more than 256 bytes


Default value: N/A

2.2.15 Cost-based Optimization

CBO (Cost-Based-Optimize)
Parameter description: Specifies the switch for the cost-based optimizer (CBO). Value ON
means the switch is turned on, and value OFF means the switch is turned off.
If CBO is set to ON and there are table statistics, SQL execution plans will be generated
based on CBO rules. Otherwise, the SQL execution plans will be generated based on RBO
rules.
If there is a CBO switch switchover, all execution plans buffered in a SQL pool will be
invalidated.
Valid value:
ON: The switch is enabled.
OFF: The switch is disabled.
Default value: OFF

2.2.16 Maximum Number of Concurrent Jobs

JOB_THREADS
Parameter description: Specifies the maximum number of jobs that can be concurrently
executed.
When the number of concurrent jobs reaches the maximum, the system waits for ongoing jobs
to be completed even if there is a job reaching the next execution time. That is, the system
executes jobs only when the number of concurrent jobs is less than the maximum.
Value range: [0, 200]
Default value: 100

2.2.17 Other Instance Parameters

UNDO_RETENTION_TIME
Parameter description: Specifies the undo retention period. If this parameter is set to an
overly small value, the error "snapshot too old" will be reported.
Value range: an integer, in the range (0, 2^32 – 1] (unit: second)
Default value: 100

FILE_OPTIONS
Parameter description: Specifies whether to enable the Direct I/O or asynchronous I/O
feature for file systems on supported platforms.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Database Reference (Standalone) 2 Parameters

Valid value:

l NONE: Direct I/O and asynchronous I/O are disabled.


l DIRECTIO: Direct I/O is enabled for redo files.
l FULLDIRECTIO: DIRECT I/O is enabled for all files.
l ASYNCH: Asynchronous I/O is enabled.
l SETALL: Direct I/O and asynchronous I/O are enabled.

Default value: NONE

ALARM_LOG_DIR
Parameter description: Specifies the directory of alarm logs.

Value range: any available directory in systems

Default value: N/A

INSTANCE_NAME
Parameter description: Specifies the name of an instance.

Value range: a string

Default value: zenith

RECYCLEBIN
Parameter description: Specifies whether to enable the recycle bin function in real time.

Valid value: TRUE, FALSE

Default value: TRUE

BUF_POOL_NUM
Parameter description: Specifies the number of partitions for the data buffer.

Value range: a positive integer, in the range [1, 128]

Default value: 1

SQL_COMPAT
Parameter description: Specifies a supported database type.

Value range: Only GSDB is supported.

Default value: GSDB

CR_MODE
Parameter description: Specifies an MVCC mechanism for tables or indexes.

Valid value:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Database Reference (Standalone) 2 Parameters

l ROW: Row-level MVCC is enabled.


l PAGE: Page-level MVCC is enabled.
Default value: PAGE

DROP_NOLOGGING
Parameter description: Specifies whether to delete the definition of a NOLOGGING table
when a database is restarted, a primary node is demoted to standby, or a standby node is
promoted to primary.
Valid value:
TRUE: All NOLOGGING tables (including table definitions and table data) are deleted.
When a standby node accesses a NOLOGGING table, an error indicating that the table does
not exist is reported.
FALSE: NOLOGGING tables are cleared, and table definitions are reserved.
Default value: FALSE

_AUTO_INDEX_RECYCLE
Parameter description: Specifies whether to create a background thread to reclaim empty
pages of indexes.
Valid value:
ON: The thread is created.
OFF: The thread is not created.
Default value: ON

_RCY_CHECK_PCN
Parameter description: Specifies whether to enable the PCN verification function during log
replay. The function checks whether the PCN values between data pages and redo logs are
consistent.
Valid value: TRUE, FALSE
Default value: TRUE

TABLESPACE_USAGE_ALARM_THRESHOLD
Parameter description: Specifies the alarm threshold of the tablespace usage.
Value range: an integer, in the range [0,100] (unit: percentage)
Default value: 80

2.2.18 Time Zone


DB_TIMEZONE
Parameter description: Specifies the time zone of a database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Database Reference (Standalone) 2 Parameters

The time zone is used as the time reference of the database. Any time point of other time
zones is automatically converted to a point of the local time zone. In this way, global time is
unified. In a client query, the record time is converted into a point of the time zone where the
client is located when the query result is returned.

You are advised not to modify this parameter after it is set during system initialization.
Otherwise, data storage of the TIMESTAMP WITH LOCAL TIME ZONE type will be
affected.

Value range: [-12:00, [+]14:00], string type

Default value: 00:00

2.3 Sessions

2.3.1 Parameter Overview

Table 2-4 Parameter overview


Parameter Defa Database- Instance- Session- Dynam
ult level level level ic
Value Modificati Modifica Modificati Validat
on tion on ion

COMMIT_ON_DISCON FALS Supported Supported Not Not


NECT E supported support
ed

_PREFETCH_ROWS 100 Supported Supported Not Support


supported ed

OPEN_CURSORS 2000 Supported Supported Not Support


supported ed

ENABLE_SQL_MAP FALS Supported Supported Not Support


E supported ed

_SQL_MAP_BUCKETS 1000 Supported Supported Not Not


supported support
ed

2.3.2 Cursors

COMMIT_ON_DISCONNECT
Parameter description: Specifies whether autocommit is enabled when there is a
disconnection.

Valid value: TRUE, FALSE

Default value: FALSE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Database Reference (Standalone) 2 Parameters

_PREFETCH_ROWS
Parameter description: Specifies the number of prefetch rows.
Value range: an integer, in the range [1, 2^32 – 1]
Default value: 100

OPEN_CURSORS
Parameter description: Specifies the maximum number of cursors that can be opened in a
session at a time. This parameter can be used to prevent sessions from opening too many
cursors.
Value range: an integer, in the range [1, 16384]
Default value: 2000

2.3.3 SQL Mapping


ENABLE_SQL_MAP
Parameter description: Specifies whether to enable the SQL mapping function.
Valid value: TRUE, FALSE
Default value: FALSE

_SQL_MAP_BUCKETS
Parameter description: When the SQL mapping function is enabled, SQL mapping
relationships are recorded in the hash structure on database buffers. This parameter is used to
adjust the number of hash buckets.
Value range: an integer, in the range [1, 1000000]
Default value: 1000

2.4 Tools

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.4.1 Parameter Overview


Table 2-5 Parameter overview
Parameter Defaul Proces Databas Instance- Session- Dynami
t s- e-level level level c
Value level Modific Modifica Modific Validati
Modif ation tion ation on
icatio
n

ZSQL_SSL_QUIE FALSE Suppor Not Not Not Not


T ted supporte supported supported supported
d

ZSQL_INTERAC 5 Suppor Not Not Not Not


TION_TIMEOUT ted supporte supported supported supported
d

2.4.2 zsql Parameters


ZSQL_SSL_QUIET
Parameter description: Specifies whether zsql connects to a server in silent mode without
notifying users of SSL security interaction information when there is no SSL CA certificate
configured.
Valid value:
TRUE: zsql connects to a server in silent mode without the notification.
FALSE: Users are not notified of SSL security interaction information.
Default value: FALSE

ZSQL_INTERACTION_TIMEOUT
Parameter description: Specifies the timeout period during which zsql waits for user input
after notifying the users of SSL security interaction information.
Value range: a positive integer
Default value: 5

2.5 Advanced Optimization

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.5.1 Parameter Overview


Table 2-6 Parameter overview
Parameter Default Database- Instance- Session- Dynamic
Value level level level Validatio
Modificati Modificati Modifica n
on on tion

_ENABLE_QOS FALSE Supported Supported Not Supported


supported

_QOS_CTRL_FAC 0.75 Supported Supported Not Not


TOR supported supported

_QOS_SLEEP_TIM 20 Supported Supported Not Not


E supported supported

_QOS_RANDOM_R 64 Supported Supported Not Not


ANGE supported supported

_DISABLE_SOFT_ FALSE Supported Supported Not Not


PARSE supported supported

_HINT_FORCE 0 Supported Supported Not Supported


supported

STRING_AS_HEX_ FALSE Supported Supported Not Not


FOR_BINARY supported supported

_THREAD_STACK 512K Supported Supported Not Not


_SIZE supported supported

_AGENT_STACK_S 1M Supported Supported Not Not


IZE supported supported

_VARIANT_AREA_ 256K Supported Supported Not Not


SIZE supported supported

OPTIMIZED_WOR 100 Supported Supported Not Not


KER_THREADS supported supported

_SPIN_COUNT 1000 Supported Supported Not Not


supported supported

_INDEX_BUFFER_ 8M Supported Supported Not Not


SIZE supported supported

_PRIVATE_KEY_L 8 Supported Supported Not Not


OCKS supported supported

_PRIVATE_ROW_L 8 Supported Supported Not Not


OCKS supported supported

_DOUBLEWRITE TRUE Supported Supported Not Supported


supported

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Database- Instance- Session- Dynamic


Value level level level Validatio
Modificati Modificati Modifica n
on on tion

_INIT_CURSORS 32 Supported Supported Not Not


supported supported

MERGE_SORT_BA 100000 Supported Supported Not Supported


TCH_SIZE supported

LONGSQL_TIMEO 10 Supported Supported Not Supported


UT supported

ENABLE_ERR_SU FALSE Not Not Not Supported


PERPOSED supported supported supported

EMPTY_STRING_ TRUE Supported Supported Supported Not


AS_NULL supported

ZERO_DIVISOR_A FALSE Not Not Not Not


CCEPTED supported supported supported supported

INTERACTIVE_TI 1800 Supported Supported Not Supported


MEOUT supported

UPPER_CASE_TAB TRUE Supported Supported Not Not


LE_NAMES supported supported

MAX_CONNECTI 200 Supported Supported Not Not


ON_POOL_SIZE supported supported

MIN_CONNECTIO 10 Supported Supported Not Not


N_POOL_SIZE supported supported

SUPER_USER_RES 5 Supported Supported Not Not


ERVED_SESSIONS supported supported

RESOURCE_LIMI FALSE Supported Supported Not Supported


T supported

_SQL_CURSORS_E 8 Supported Supported Not Supported


ACH_SESSION supported

_RESERVED_SQL_ 80 Supported Supported Not Supported


CURSORS supported

MAX_ALLOWED_ 64M Supported Supported Not Supported


PACKET supported

MAX_REMOTE_P 300 Supported Supported Not Supported


ARAMS supported

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.5.2 Flow Control Switch

_ENABLE_QOS
Parameter description: Specifies whether to turn on the flow control switch. When there are
high requirements for concurrency performance, turning on the flow control switch optimizes
the performance of databases.

Valid value:

TRUE: The flow control switch is turned on.

FALSE: The flow control switch is turned off.

Default value: FALSE

_QOS_CTRL_FACTOR
Parameter description: Specifies the maximum number of concurrent threads for a single
CPU. If the number of concurrent threads reaches this parameter value, additional threads will
enter the sleep state, queuing up to get activated.

The maximum number of concurrent threads is calculated as follows: FACTOR x Number of


CPU cores. This parameter is valid only when the flow control switch is turned on.

Value range: a floating point number, in the range (0, 5]

Default value: 0.75

_QOS_SLEEP_TIME
Parameter description: Specifies the fixed time coefficient for threads to sleep. If the
number of concurrent threads reaches the maximum, additional threads will enter the sleep
state. The sleeping time is calculated as follows: _QOS_SLEEP_TIME x 1 ms +
_QOS_SLEEP_TIME x (TRANSACTION_ID % _QOS_RANDOM_RANGE) x 1 μs.
This parameter is valid only when the flow control switch is turned on.

Value range: a positive integer, in the range [1, 2^32)

Default value: 20

_QOS_RANDOM_RANGE
Parameter description: Specifies the random time coefficient for threads to sleep. If the
number of concurrent threads reaches the maximum, additional threads will enter the sleep
state. The sleeping time is calculated as follows: _QOS_SLEEP_TIME x 1 ms +
_QOS_SLEEP_TIME x (TRANSACTION_ID % _QOS_RANDOM_RANGE) x 1 μs.
This parameter is valid only when the flow control switch is turned on.

Value range: a positive integer, in the range [1, 2^32)

Default value: 64

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.5.3 Soft Parse Switch


_DISABLE_SOFT_PARSE
Parameter description: Specifies whether to disable the soft parse function.
Valid value:
l TRUE: The soft parse function is disabled. In this case, the DV_SQLS view becomes
unavailable.
l FALSE: The soft parse function is enabled. In this case, an SQL parse tree will be
buffered to speed up the execution of the same SQL statement. In addition, the
DV_SQLS view is available.
Default value: FALSE

_HINT_FORCE
Parameter description: Specifies whether to enable optimizer hints.
Value range: an integer
0: All optimizer hints are disabled.
1: The ordered hint is enabled.
2: The nested loop hint is enabled.
4: The merge hint is enabled.
8: The hash hint is enabled.
If you need to enable multiple hints at the same time, set this parameter to a sum of them. For
example, if both the ordered and hash hints need to be enabled, set this parameter to 9.
Default value: 0

STRING_AS_HEX_FOR_BINARY
Parameter description: Specifies whether to process the BINARY type as the RAW type.
Valid value:
l TRUE: The BINARY type is processed as the RAW type.
l FALSE: The BINARY type is processed as it is.
Default value: FALSE

2.5.4 Thread Processing


_THREAD_STACK_SIZE
Parameter description: Specifies the size of a thread stack.
Value range: a positive integer, in the range [256 KB, 7.5 MB] (unit: byte)
Default value: 512K

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
Database Reference (Standalone) 2 Parameters

_AGENT_STACK_SIZE
Parameter description: Specifies the size of a thread data stack, which is used to buffer
messages. The maximum size of a message that can be buffered is half of this parameter
value.
Value range: a positive integer, in the range [512 KB, 4 GB) (unit: byte)
Default value: 1MB

_VARIANT_AREA_SIZE
Parameter description: This parameter has been abandoned. If it is configured for
compatibility purposes, no error will be reported when the service is started.
Value range: an integer, in the range [256 KB, 64 MB] (unit: byte)
Default value: 256K

OPTIMIZED_WORKER_THREADS
Parameter description: Specifies the most proper number of work threads.
l When the number of sessions exceeds the value of this parameter, the session and thread
separation mode will be enabled. Otherwise, the binding mode will be used.
l It is recommended that this parameter value be less than or equal to the value of
SESSIONS. Otherwise, additional thread resources will be wasted.
l If this parameter is set to an overly large value, more CPU and thread resources will be
occupied. When resources are insufficient, database exceptions may occur.
l Each thread occupies over 0.5 MB memory.
Value range: a positive integer, in the range [2, 30000]
Default value: 100

2.5.5 Session Control Parameters


_SPIN_COUNT
Parameter description: Specifies the number of times spent waiting to obtain a spinlock.
This parameter is an internal advanced parameter. If there are severe conflicts in service
concurrency, increasing this number helps reduce the probability of failures in concurrent
transactions.
Value range: an integer, in the range [0, 2^32 – 1]
Default value: 1000

_INDEX_BUFFER_SIZE
Parameter description: Specifies the size of an index buffer on a single session. Increasing
this size helps reduce the number of times that indexes are read from a disk.
Number of pages in an index buffer = _INDEX_BUFFER_SIZE/PAGE_SIZE
Value range: a positive integer, in the range [16 KB, 32 TB] (unit: byte)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
Database Reference (Standalone) 2 Parameters

Default value: 8M

_PRIVATE_KEY_LOCKS
Parameter description: Specifies the maximum number of key locks that can be held by
each session.
When a transaction ends, the session can hold a maximum of key locks no greater than
_PRIVATE_KEY_LOCKS, and needs to release remaining locks to the global lock area for
later reuse.
Value range: an integer, in the range [8, 128]
Default value: 8

_PRIVATE_ROW_LOCKS
Parameter description: Specifies the maximum number of row locks that can be held by
each session.
When a transaction ends, the session can hold a maximum of row locks no greater than
_PRIVATE_ROW_LOCKS, and needs to release remaining locks to the global lock area for
later reuse.
Value range: an integer, in the range [8, 128]
Default value: 8

_DOUBLEWRITE
Parameter description: Specifies whether to turn on the doublewrite switch. After this
switch is turned on, reliability will be improved.
Valid value:
TRUE: The doublewrite switch is turned on.
FALSE: The doublewrite switch is turned off.
Default value: TRUE

_INIT_CURSORS
Parameter description: Specifies the number of initial cursors in a session.
A cursor opens a table. When the number of tables opened at the same time exceeds this
initial number, cursors will be dynamically allocated to the current session. The dynamic
allocation may reduce SQL performance.
Value range: an integer, in the range [0, 256]
Default value: 32

MERGE_SORT_BATCH_SIZE
Parameter description: Specifies the number of records involved in a sort operation in the
merge join algorithm.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: a positive integer, in the range [100000, 2^32 – 1]


Default value: 100000

LONGSQL_TIMEOUT
Parameter description: Specifies time threshold for slow queries. This parameter is valid
only when slow query logging is enabled. If the execution time of a DML statement exceeds
the value of this parameter, the statement will be recorded in a slow query log.
Value range: an integer, in the range [0, 2^32 – 1] (unit: second)
Default value: 10

ENABLE_ERR_SUPERPOSED
Parameter description: Specifies whether to turn on the SQL error superposition switch.
After the switch is turned on, error information will be superposed when being output. After
the switch is turned off, only bottom-layer error information will be output.
Valid value:
TRUE: The SQL error superposition switch is turned on.
FALSE: The SQL error superposition switch is turned off.
Default value: FALSE

EMPTY_STRING_AS_NULL
Parameter description: Specifies whether to consider an empty string null. This parameter is
read-only.
Valid value:
TRUE: An empty string is considered null.
FALSE: An empty string is not considered null, and is processed differently.
Default value: TRUE

ZERO_DIVISOR_ACCEPTED
Parameter description: Specifies whether to turn on the switch of allowing for a zero
divisor. After the switch is turned on, calculation results will be NULL when a zero divisor is
used. After the switch is turned off, an exception will be thrown when a zero divisor is used.
Valid value:
TRUE: A divisor can be 0.
FALSE: No divisor can be 0.
Default value: FALSE

INTERACTIVE_TIMEOUT
Parameter description: Specifies a session timeout period. If a session has no operation
within the timeout duration, it will be closed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: a positive integer, in the range [1, 2^32 – 1] (unit: second)

Default value: 1800

UPPER_CASE_TABLE_NAMES
Parameter description: Specifies whether to convert letters in object names to uppercase.
This parameter is read-only.

Objects names include table, column, view, stored procedure, customized function, trigger,
tablespace, index, and constraint names.

Valid value:

TRUE: The letters are converted to uppercase. In this case, SQL statements are case-
insensitive.

FALSE: The letters are not converted to uppercase. In this case, SQL statements are case-
sensitive.

Default value: TRUE

MAX_CONNECTION_POOL_SIZE
Parameter description: Specifies the maximum number of connections in a connection pool
for z-sharding. This parameter is valid only on z-sharding nodes.

Value range: a positive integer, in the range (0, 4000]

Default value: 200

MIN_CONNECTION_POOL_SIZE
Parameter description: Specifies the minimum number of connections in a connection pool
for z-sharding. This parameter is valid only on z-sharding nodes.

Value range: a positive integer, no greater than MAX_CONNECTION_POOL_SIZE

Default value: 10

SUPER_USER_RESERVED_SESSIONS
Parameter description: Specifies the number of sessions reserved for user SYS.

Value range: a positive integer, in the range (0, 32]

Default value: 5

RESOURCE_LIMIT
Parameter description: Specifies whether to turn on the resource restriction switch.

Valid value:

TRUE: The resource restriction switch is turned on. In this case, the maximum number of
sessions each user can connect to is limited by the SESSIONS_PER_USER parameter and
also the SESSIONS parameter, which specifies the total number of sessions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
Database Reference (Standalone) 2 Parameters

FALSE: The resource restriction switch is turned off. In this case, the maximum number of
sessions each user can connect to is limited only by the total number of sessions.
Default value: FALSE

_SQL_CURSORS_EACH_SESSION
Parameter description: Specifies the number of initial SQL cursors in a session.
An SQL cursor opens a table, either a physical table or a materialized table. After the number
of opened tables exceeds this initial number, the system will allocate cursors from the global
SQL cursor pool until resources there are used up. Then, the system dynamically allocates
cursors, which affects SQL performance.
Value range: an integer, in the range [0, 300]
Default value: 8

_RESERVED_SQL_CURSORS
Parameter description: Specifies the number of reserved global SQL cursors.
When a database is started, a global SQL cursor pool is initialized. When a session is created,
it is allocated a cursor from the global pool. When the number of sessions is large and the
initial global SQL cursors are insufficient, the system automatically expands the global SQL
cursor pool. The number of global SQL cursors is increased by 80 each time until the number
reaches _SQL_CURSORS_EACH_SESSION x SESSIONS +
_RESERVED_SQL_CURSORS.
This parameter can be set dynamically. In this case, however, the value can only be increased,
instead of being reduced. To reduce value, you must modify the configuration file and restart
the database.
Value range: an integer, in the range [0, 1000]
Default value: 80

MAX_ALLOWED_PACKET
Parameter description: Specifies the maximum packet size allowed for communication.
Value range: [96 KB, 64 MB] (unit: byte)
Default value: 64M

MAX_REMOTE_PARAMS
Parameter description: Specifies the maximum number of bind parameters. In distribution
scenarios, IN subqueries cannot be pushed down to a DN for execution, and therefore need to
be rewritten to IN bind parameters for pushdown purposes.
Value range: [0, 32768]
Default value: 300

2.6 Security and Audit

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
Database Reference (Standalone) 2 Parameters

2.6.1 Parameter Overview


Table 2-7 Parameter overview
Parameter Defaul Databas Instance- Session- Dynamic
t e-level level level Validatio
Value Modific Modifica Modifica n
ation tion tion

_ENCRYPTION_ALG SCRA Supporte Supported Not Not


M_SH d supported supported
A256

_SYS_PASSWORD thuMm Supporte Supported Not Not


QYA0 d supported supported
AcykV
YBVtu
BJRxec
J3in8X
VsZb2s
HORA
gOqnCr
POTvm
7VYtv3
RoPbW
MKRd
uMKrH
Z3dlC
Vih0o0
at1KvH
7t8VZ
HLGpa
+n1kJl
TP6iLr
YGRN
BXA=
=

AUDIT_LEVEL 3 Supporte Supported Not Supported


d supported

_AUDIT_MAX_FILE_SI 10M Supporte Supported Not Supported


ZE d supported

_AUDIT_BACKUP_FILE 10 Supporte Not Not Supported


_COUNT d supported supported

ENABLE_SYSDBA_LOG TRUE Supporte Supported Supported Not


IN d supported

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Defaul Databas Instance- Session- Dynamic


t e-level level level Validatio
Value Modific Modifica Modifica n
ation tion tion

LOCAL_KEY UTiYl Supporte Not Not Supported


BoTC7 d supported supported
1MvTy
BvWh
VDodc
0VAop
1GMe1
35ZCo
v8Pv4x
snlEHn
9Bs/
pjRo7Z
NM1B
Xq8Z4
XuyRjf
aNpY/
7McEQ
==

_FACTOR_KEY dc4hoQ Supporte Supported Not Not


WGQs d supported supported
7/
Uv3Aih
erFw==

TCP_VALID_NODE_CH FALSE Supporte Not Not Supported


ECKING d supported supported

TCP_INVITED_NODES - Supporte Not Not Supported


d supported supported

TCP_EXCLUDED_NODE - Supporte Not Not Supported


S d supported supported

UNAUTH_SESSION_EX 60 Supporte Supported Not Supported


PIRE_TIME d supported

SSL_VERIFY_PEER FALSE Supporte Supported Not Not


d supported supported

SSL_CERT - Supporte Supported Not Not


d supported supported

SSL_KEY - Supporte Supported Not Not


d supported supported

SSL_CA - Supporte Supported Not Not


d supported supported

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Defaul Databas Instance- Session- Dynamic


t e-level level level Validatio
Value Modific Modifica Modifica n
ation tion tion

SSL_CRL - Supporte Supported Not Not


d supported supported

SSL_CIPHER - Supporte Supported Not Not


d supported supported

SSL_KEY_PASSWORD - Supporte Supported Not Not


d supported supported

SSL_EXPIRE_ALERT_T 30 Supporte Supported Not Not


HRESHOLD d supported supported

SSL_PERIOD_DETECTI 7 Not Not Not Not


ON supporte supported supported supported
d

HAVE_SSL FALSE Not Not Not Not


supporte supported supported supported
d

_ENCRYPTION_ITERAT 2000 Supporte Supported Not Supported


ION d supported

2.6.2 Parameter Descriptions


_ENCRYPTION_ALG
Parameter description: Specifies the encryption algorithm for user passwords. Currently,
only the SCRAM_SHA256 encryption algorithm is supported. Upgrades are compatible the
original PBKDF2 algorithm.
Value range: a string
Default value: SCRAM_SHA256

_SYS_PASSWORD
Parameter description: Specifies a preset password of user SYS for a standalone database.
The password is stored in install.py after undergoing an irreversible encryption. You are not
advised to change the password online. After the value of this parameter is changed, the
password will only be used as a temporary password of user SYS when the database is in
NOMOUNT mode.
Setting method:
When running install.py to install a database, use -C to specify the value of
_SYS_PASSWORD. The format is as follows: -C _SYS_PASSWORD=new_password
Value range: a string

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
Database Reference (Standalone) 2 Parameters

Default value:
thuMmQYA0AcykVYBVtuBJRxecJ3in8XVsZb2sHORAgOqnCrPOTvm7VYtv3RoPb
WMKRduMKrHZ3dlCVih0o0at1KvH7t8VZHLGpa+n1kJlTP6iLrYGRNBXA==

AUDIT_LEVEL
Parameter description: Specifies an audit level.

Value range: an integer [0,255]

Table 2-8 lists the audit objects and the corresponding open flags. To audit multiple objects,
set AUDIT_LEVEL to a sum. For example, if DDL, DCL, and DML operations need to be
audited at the same time, set AUDIT_LEVEL to 7.

Table 2-8 Values of AUDIT_LEVEL for different audit logging types

Type AUDIT_LEVEL Value (Decimal)

DDL 1

DCL 2

DML 4

PL 8

ALL 255

l If AUDIT_LEVEL is greater than 0, requests such as login, logout, cancellation, and


FREE statement requests, in addition to the corresponding operations, will be audited.
l If AUDIT_LEVEL is 0, audit logging will be disabled.

For functional syntax, set AUDIT_LEVEL based on its types to record required audit logs.

l For EXP, IMP, LOAD, and DUMP syntax that consists of multiple types of SQL
statements, the value of AUDIT_LEVEL must cover the corresponding SQL types.
l For other syntax, the value of AUDIT_LEVEL must cover the DCL type.

Default value: 3

_AUDIT_MAX_FILE_SIZE
Parameter description: Specifies the size of a single audit log file.

If the size of an audit log file reaches this parameter value, the system will back up the log
file. If the log file name is zengine.aud, the backup log file name will be
zengine_yyyymmddhhmissfff.aud.

Note that this parameter does not dynamically take effect on existing audit log files.

Value range: an integer, in the range [1 MB, 4 GB] (unit: byte)

Default value: 10M

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
Database Reference (Standalone) 2 Parameters

_AUDIT_BACKUP_FILE_COUNT
Parameter description: Specifies the maximum number of backup audit log files.

If the number of backup audit log files reaches this parameter value, the earliest backup audit
log file will be first deleted. Only the number, specified by this parameter, of backup audit log
files will be retained.

Value range: an integer, in the range [0, 128]

Default value: 10

ENABLE_SYSDBA_LOGIN
Parameter description: Specifies whether to support password-free login. If this parameter is
not set, password-free login will be supported.

To log in to a standalone database with no password, run zsql / as SYSDBA or conn / as


SYSDBA.

This parameter specifies whether to enable password-free login during installation. You are
not advised to change the value online during database use. If you need to change the value
online, run the python zctl.py -t kill command to stop the database first.

Valid value:

l TRUE: Password-free login is supported.


l FALSE: Password-free login is not supported.

Default value: TRUE

LOCAL_KEY
Parameter description: Specifies a working key, which is used to encrypt SSL private key
passwords and the data for local password-free login, providing confidentiality and integrity
protection for locally stored sensitive data.

Such a working key can be generated by running the zencrypt -g command. The command
actually generates a pair of a working key (specified by LOCAL_KEY) and a root key factor
(specified by _FACTOR_KEY) at the same time. They must be used in pairs.

Value range: an 88-byte ciphertext, which is generated by encrypting a 128-bit (16-byte)


random number using the corresponding key factor

Default value: UTiYlBoTC71MvTyBvWhVDodc0VAop1GMe135ZCov8Pv4xsnlEHn9Bs/


pjRo7ZNM1BXq8Z4XuyRjfaNpY/7McEQ==

_FACTOR_KEY
Parameter description: Specifies a root key factor, which is located at the bottom layer of
key management and is used to protect the confidentiality of upper-layer keys (a working
key).

Such a root key factor can be generated by running the zencrypt -g command. The command
actually generates a pair of a working key (specified by LOCAL_KEY) and a root key factor
(specified by _FACTOR_KEY) at the same time. They must be used in pairs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
Database Reference (Standalone) 2 Parameters

Value range: a 24-byte value, which is generated by encoding a 128-bit (16-byte) random
number using Base64

Default value: dc4hoQWGQs7/Uv3AiherFw==

TCP_VALID_NODE_CHECKING
Parameter description: Specifies whether to enable the IP address whitelist checking
function. A server can control client access based on a whitelist or blacklist.

Before enabling the IP address whitelist checking function, ensure that at least one of
TCP_INVITED_NODES and TCP_EXCLUDED_NODES has been configured.
Otherwise, the following error will be reported:
GS-00254 : For invited and excluded nodes is both empty, ip whitelist function
can't be enabled

Setting method:

l Add TCP_VALID_NODE_CHECKING = TRUE in the zengine.ini configuration file


and restart the database for the modification to take effect. The zengine.ini file is stored
in {GSDB_DATA}/cfg/zengine.ini.
l Run the ALTER SYSTEM statement to enable the IP address whitelist checking
function. The configuration takes effect immediately after the statement is executed.
ALTER SYSTEM SET TCP_VALID_NODE_CHECKING = TRUE;

Valid value:

l TRUE: The IP address whitelist checking function is enabled.


l FALSE: The IP address whitelist checking function is disabled.

Default value: FALSE

TCP_INVITED_NODES
Parameter description: Specifies an IP address whitelist.

After the IP address whitelist checking function is enabled and an IP address whitelist is
configured, only whitelisted clients can access databases. Such a whitelist allows for IPv4 and
IPv6 addresses, as well as a specified subnet mask length, which indicates a subnet segment.
Multiple addresses or network segments can be separated by commas (,).

When the IP address whitelist detection function is enabled, you are not allowed to change
both the whitelist and blacklist to be empty. Otherwise, the following error will be reported:
GS-00255: Ip whitelist function is enabled, invited and excluded nodes can't set
to both empty

Setting method:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
Database Reference (Standalone) 2 Parameters

l Set the TCP_INVITED_NODES parameter in the zengine.ini configuration file and


restart the database for the setting to take effect. The zengine.ini file is stored in
{GSDB_DATA}/cfg/zengine.ini.
TCP_INVITED_NODES = (127.0.0.1/32,10.134.175.142/32,20ab::
9217:acff:feab:fcd0/64)

l Run the ALTER SYSTEM statement to configure an IP address whitelist. The


configuration takes effect immediately after the statement is executed.
ALTER SYSTEM SET TCP_INVITED_NODES = '(127.0.0.1/32,10.134.175.142/32,20ab::
9217:acff:feab:fcd0/64)';

Value range: N/A


Default value: N/A

TCP_EXCLUDED_NODES
Parameter description: Specifies an IP address blacklist.
After the IP address whitelist checking function is enabled and an IP address blacklist is
configured, those blacklisted clients cannot access databases. Such a blacklist allows for IPv4
and IPv6 addresses, as well as a specified subnet mask length, which indicates a subnet
segment. Multiple addresses or network segments can be separated by commas (,).

When the IP address whitelist detection function is enabled, you are not allowed to change
both the whitelist and blacklist to be empty. Otherwise, the following error will be reported:
GS-00255: Ip whitelist function is enabled, invited and excluded nodes can't set
to both empty

Setting method:
l Set the TCP_EXCLUDED_NODES parameter in the zengine.ini configuration file and
restart the database for the setting to take effect. The zengine.ini file is stored in
{GSDB_DATA}/cfg/zengine.ini.
TCP_EXCLUDED_NODES = (10.134.175.142/32,20ab::9217:acff:feab:fcd0/64)

l During database instance running, use the ALTER SYSTEM statement to configure an
IP address blacklist.
ALTER SYSTEM SET TCP_EXCLUDED_NODES = '(10.134.175.142/32,20ab::
9217:acff:feab:fcd0/64)';

Value range: N/A


Default value: N/A

UNAUTH_SESSION_EXPIRE_TIME
Parameter description: Specifies the connection authentication time.
If a connection is not authenticated within the configured authentication time, the server
forcibly breaks the connection and releases the session resources occupied by the connection.
This avoids the exhaustion of connection sessions caused by malicious TCP connections. This
parameter effectively prevents DoS attacks, and any modification of it will take effect
immediately.
Value range: an integer, in the range [0, 2^32 – 1] (unit: second)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
Database Reference (Standalone) 2 Parameters

Default value: 60

SSL_VERIFY_PEER
Parameter description: Specifies whether to verify a client certificate.
Valid value:
TRUE: The client certificate is verified. When creating an SSL connection, a client must
provide a valid certificate.
FALSE: No client certificate is verified. When creating SSL connection, a client is allowed to
not provide a certificate.
Default value: FALSE

SSL_CERT
Parameter description: Specifies the path of a server certificate.
A server certificate is used to indicate the validity of the server identity. A certificate file
contains the public key of a server. The public key will be sent to a peer end to encrypt data.
Value range: a string. You are advised to set this parameter to the absolute path of a device
certificate. Otherwise, loading the certificate may fail.
Default value: N/A, indicating no server certificate

SSL_KEY
Parameter description: Specifies the path of a server's private key file.
A private key is used to decrypt the ciphertext generated by using a public key.
Value range: a string. You are advised to set this parameter to the absolute path of a private
key file. Otherwise, loading the private key may fail.
Default value: N/A, indicating no private key

SSL_CA
Parameter description: Specifies the path of a root certificate on a CA server.
This parameter is valid only when SSL_VERIFY_PEER is enabled.
Value range: a string. You are advised to set this parameter to the absolute path of a root
certificate on a CA server. Otherwise, loading the certificate may fail.
Default value: N/A, indicating no root certificate on a CA server

SSL_CRL
Parameter description: Specifies a certificate revocation list (CRL). If a client certificate is
on the list, it will be regarded as an invalid certificate.
Value range: a string. You are advised to set this parameter to the absolute path of a revoked
certificate. Otherwise, loading the certificate may fail.
Default value: N/A, indicating no CRL

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
Database Reference (Standalone) 2 Parameters

SSL_CIPHER
Parameter description: Specifies an encryption algorithm for SSL communication.
Valid value:

Table 2-9 Encryption algorithms


Encryption Security Encryption Algorithm Description
Strength

stronger high DHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-RSA-AES128-GCM- using the RSA
SHA256 encryption
algorithm

stronger high ECDHE-ECDSA-AES256- Suitable for


GCM-SHA384 certificates
generated by
stronger high ECDHE-ECDSA-AES128- using the
GCM-SHA256 ECDSA
encryption
algorithm

stronger high ECDHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high ECDHE-RSA-AES128-GCM- using the RSA
SHA256 encryption
algorithm

stronger high DHE-DSS-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-DSS-AES128-GCM- using the DSA
SHA256 encryption
algorithm

stronger medium DHE-RSA-AES256-SHA256 Suitable for


certificates
stronger medium DHE-RSA-AES128-SHA256 generated by
using the RSA
encryption
algorithm

stronger medium DHE-DSS-AES256-SHA256 Suitable for


certificates
stronger medium DHE-DSS-AES128-SHA256 generated by
using the DSA
encryption
algorithm

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
Database Reference (Standalone) 2 Parameters

Encryption Security Encryption Algorithm Description


Strength

stronger high DHE-RSA-AES256-CCM Suitable for


certificates
stronger high DHE-RSA-AES128-CCM generated by
using the RSA
encryption
algorithm

Default value: N/A, indicating that all encryption algorithms supported by GaussDB 100 can
be used on a peer end

SSL_KEY_PASSWORD
Parameter description: Specifies the ciphertext of the password for a server's private key. To
encrypt a private key before storing it, set this parameter specify the password ciphertext.
Value range: a string
Default value: N/A, indicating that a private key file is not encrypted

SSL_EXPIRE_ALERT_THRESHOLD
Parameter description: Specifies the threshold for alarming SSL certificate expiration. If
SSL has been enabled, there will be a log reminder when the expiration time is less than the
threshold. After a database is started, it periodically checks for SSL certificate expiration
based on SSL_PERIOD_DETECTION.
Value range: an integer, in the range [7, 180] (unit: day)
Default value: 30

SSL_PERIOD_DETECTION
Parameter description: Specifies the period for detecting SSL certificate expiration. If SSL
has been started, the system will periodically check the time before SSL expiration after an
instance is started. If the time is less than the value of
SSL_EXPIRE_ALERT_THRESHOLD, a log reminder will be reported.
Value range: unconfigurable (unit: day)
Default value: 7

HAVE_SSL
Parameter description: Specifies whether the current database instance supports SSL
connection creation. This parameter is read-only.
Valid value:
TRUE: The current database instance supports SSL connection creation.
FALSE: The current database instance does not support SSL connection creation.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
Database Reference (Standalone) 2 Parameters

Default value: FALSE. When a database is started, the SSL status is detected and the
parameter is automatically updated. Manual configuration is not supported.

_ENCRYPTION_ITERATION
Parameter description: Specifies the number of iterations of an encryption algorithm.
Value range: an integer, in the range [1000, 50000]
Default value: 2000

2.7 Logs

2.7.1 Parameter Overview


Table 2-10 Parameter overview
Parameter Default Datab Instanc Session- Dynami
Value ase- e-level level c
level Modific Modific Validati
Modifi ation ation on
cation

LOG_HOME $GSDB_D Support Not Not Not


ATA/log ed supporte supporte supporte
d d d

ALARM_LOG_DIR None Support Not Not Not


ed supporte supporte supporte
d d d

_LOG_LEVEL 7 Support Supporte Not Supporte


ed d supporte d
d

_LOG_MAX_FILE_SIZE 10M Support Supporte Not Supporte


ed d supporte d
d

_LOG_BACKUP_FILE_CO 10 Support Not Not Supporte


UNT ed supporte supporte d
d d

_LOG_FILE_PERMISSION 600 Support Not Not Supporte


S ed supporte supporte d
d d

_LOG_PATH_PERMISSIO 700 Support Not Not Supporte


NS ed supporte supporte d
d d

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100
Database Reference (Standalone) 2 Parameters

Parameter Default Datab Instanc Session- Dynami


Value ase- e-level level c
level Modific Modific Validati
Modifi ation ation on
cation

_BLACKBOX_STACK_DE 30 Support Supporte Not Not


PTH ed d supporte supporte
d d

2.7.2 Parameter Descriptions


LOG_HOME
Parameter description: Specifies the root directory of logs.
When the root log directory is changed, the directories of RUN logs, DEBUG logs, AUDIT
logs, and LONGSQL logs will change accordingly. For example, if LOG_HOME = /home/
gaussdba/data/log, the RUN log directory will be /home/gaussdba/data/log/run, the
DEBUG log directory will be /home/gaussdba/data/log/debug, the AUDIT log directory
will be /home/gaussdba/data/log/audit, and the LONGSQL log directory will be /home/
gaussdba/data/log/longsql. However, ALARM logs are stored in a separate log directory
(specified by ALARM_LOG_DIR), which is not affected by changes in the root log
directory.
Value range: a string, no greater than 163
Default value: $GSDB_DATA/log

ALARM_LOG_DIR
Parameter description: Specifies the directory of alarm logs.
Value range: a string, no greater than 163
Default value: none

_LOG_LEVEL
Parameter description: Specifies a level for logging.
If this parameter is set, audit logging will be disabled. Audit logging is controlled by
AUDIT_LEVEL.
Value range: an integer
Table 2-11 lists supported log levels and the corresponding open flags. To record logs of
different levels, set _LOG_LEVEL to a sum. For example, if the RUN ERROR and
DEBUG ERROR logs need to be recorded, set _LOG_LEVEL to 17, that is, 0x00000001(1)
+ 0x00000010(16). RUN logs and DEBUG logs are classified as follows: INFORMATION,
WARNING, and ERROR. INFORMATION: Normal information, such as SQL statements,
is printed. WARNING: Alarm information is printed, without affecting operations. ERROR:
Error information, for example, causes of SQL parse errors, is printed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100
Database Reference (Standalone) 2 Parameters

Table 2-11 Run and debug log types (_LOG_LEVEL)


Type Hexadecimal Value Decimal Value

RUN ERROR 0x00000001 1

RUN WARNING 0x00000002 2

RUN 0x00000004 4
INFORMATION

DEBUG ERROR 0x00000010 16

DEBUG 0x00000020 32
WARNING

DEBUG 0x00000040 64
INFORMATION

LONGSQL LOG 0x00000100 256

When _LOG_LEVEL is set to 0, run logging, debug logging, and LONGSQL logging are all
disabled.
Default value: 7 (RUN logs are recorded.)

_LOG_MAX_FILE_SIZE
Parameter description: Specifies the size of a single log file. This parameter applies only to
RUN logs, DEBUG logs, OPER logs, ALARM logs, and LONGSQL logs.
If the size of a log file reaches this parameter value, the system will back up the log file. If the
log file name is zengine.rlog, the backup log file name will be
zengine_yyyymmddhhmissfff.rlog.
Note that this parameter does not dynamically take effect on existing log files.
Value range: an integer, in the range [1 MB, 4 GB] (unit: byte)
Default value: 10M

_LOG_BACKUP_FILE_COUNT
Parameter description: Specifies the maximum number of backup log files. This parameter
applies only to RUN logs, DEBUG logs, OPER logs, ALARM logs, and LONGSQL logs.
If the number of backup log files reaches this parameter value, the earliest backup log file will
be first deleted. Only the number, specified by this parameter, of backup log files will be
retained.
Value range: an integer, in the range [0, 128]
Default value: 10

_LOG_FILE_PERMISSIONS
Parameter description: Specifies permissions for log files.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100
Database Reference (Standalone) 2 Parameters

The write permission of log owners, owner groups, and other users for backup log files can be
automatically deleted. This parameter does not dynamically take effect on existing log files.
Value range: an integer, in the range [600, 777]
Default value: 600

_LOG_PATH_PERMISSIONS
Parameter description: Specifies permissions for a log directory.
This parameter can be used to set permissions for the directories of RUN, DEBUG, and
AUDIT logs, their upper-layer directories, and the ALARM log directory.
When a log file is backed up or a log file is created, _LOG_PATH_PERMISSIONS
dynamically takes effect to control the directory permissions.
Value range: an integer, in the range [700, 777]
Default value: 700

_BLACKBOX_STACK_DEPTH
Parameter description: Specifies the depth of the stack called for printing logs when the
database program crashes.
Value range: an integer, in the range [2, 40]
Default value: 30

2.8 Reserved Parameters


The following table lists reserved parameters, which are not supported currently.

Table 2-12 Reserved parameters


Type Parameter

Database ARCHIVE_CONFIG

ARCHIVE_MAX_THREADS

ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE

Instance COVERAGE_ENABLE

ENABLE_IDX_CONFS_NAME_DUPL

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3 Data Dictionary and Views

GaussDB 100 provides static data dictionary tables and views for users to view system
information. The information is updated only when the data dictionary is changed (for
example, when a table is created or new permissions are granted to users). GaussDB 100 also
provides dynamic performance views for database administrators to monitor systems.

3.1 Data Dictionary Tables


Table 3-1 lists the system catalogs supported by GaussDB 100.

Table 3-1 Data dictionary tables

Data Dictionary Definition


Name

SYS_BACKUP_SETS Records information about backup sets from physical backup


files.

SYS_COLUMNS Records information about the columns of all tables in the


system.

SYS_COMMENTS Records information about all comments in the system.

SYS_CONSTRAINT_ Records information about all constraints in the system.


DEFS

SYS_DATA_NODES Records information about all database nodes.

EXP_TAB_ORDERS Records the export sequence of tables. This system catalog is a


temporary table used by the EXP tool.

EXP_TAB_RELATIO Records the dependencies of tables. This system catalog is a


NS temporary table used by the EXP tool.

SYS_DEPENDENCIE Records information about dependencies between all objects in


S the system.

SYS_DISTRIBUTE_R Records distribution rules.


ULES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Data Dictionary Definition


Name

SYS_DISTRIBUTE_S Records information about table distribution.


TRATEGIES

SYS_DUMMY Records the constants of an expression.

SYS_EXTERNAL_TA Records information about external tables in the system.


BLES

SYS_GARBAGE_SEG Records information about garbage segments in the system.


MENTS

SYS_HISTGRAM_AB Records information about the headers of histograms in the


STR system.

SYS_HISTGRAM Records information about histograms in the system.

SYS_INDEXES Records information about all indexes in the system.

SYS_INDEX_PARTS Records information about all partitioned indexes in the system.

SYS_JOBS Records information about scheduled jobs in the system.

SYS_LINKS A reserved function view, with no data.

SYS_LOBS Records information about large objects in the system.

SYS_LOB_PARTS Records information about large partitioned objects in the


system.

SYS_LOGIC_REPL Records information about tables where the logical replication


service is enabled.

SYS_DML_STATS Records statistics about operations on tables in the system.

SYS_OBJECT_PRIVS Records the object authorization information about non-SYS


users and all roles in the system.

SYS_PART_COLUMN Records information about partition columns in the system.


S

SYS_PART_OBJECTS Records information about partitioned objects in the system.

SYS_PART_STORES Records information about partition storage in the system.

SYS_PENDING_DIST Records information about distributed two-phase transactions.


_TRANS

SYS_PENDING_TRA Records information about pending, two-phase transactions in


NS the system.

SYS_PROCS Records information about stored procedures, user-defined


functions, and triggers in system catalogs.

SYS_PROC_ARGS Records information about the parameters of stored procedures


and user-defined functions in system catalogs. The system
catalogs are available only when there are parameters.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Data Dictionary Definition


Name

SYS_PROFILE Records information about profiles in the system.

SYS_RECYCLEBIN Records information about the recycle bin in the system.

SYS_ROLES Records information about roles in the system.

SYS_SEQUENCES Records information about all sequences in the system.

SYS_SHADOW_INDE Records information about shadow indexes in the system.


XES

SYS_SHADOW_INDE Records information about shadow partitioned indexes in the


X_PARTS system.

SYS_SQL_MAPS Records all SQL mapping relationships in the system.

SYS_SYNONYMS Records information about all synonyms in the system.

SYS_PRIVS Records information about all system permissions granted to


users and roles in the system.

SYS_TABLES Records information about all tables (including all system


catalogs and user tables) in the system.

SYS_TABLE_PARTS Records information about partitioned tables in the system.

SYS_TMP_SEG_STAT Records statistics about temporary segments in the system.


S

SYS_USERS Records information about all users in the system.

SYS_USER_HISTORY Records the historical passwords of users.

SYS_USER_ROLES Records information about the roles of users.

SYS_VIEWS Records information about all views in the system, except for
dynamic views.

SYS_VIEW_COLS Records column information about views in the system.

WSR_PARAMETER Records parameter values in each snapshot of the database.

WSR_SQLAREA Records DML execution information in each snapshot of the


database.

WSR_SYS_STAT Records statistics in each snapshot of the database.

WSR_SYSTEM Records statistics in each snapshot of the database.

WSR_SYSTEM_EVE Records event information in each snapshot of the database.


NT

WSR_SNAPSHOT Records snapshot information in the database.

WSR_CONTROL Records parameters about snapshot generation in the database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Data Dictionary Definition


Name

WSR_DBA_SEGMEN Records information about ADM_SEGMENTS in snapshots.


TS

WSR_LATCH Records information about DV_LATCHS in snapshots.

WSR_LIBRARYCAC Records information about WSR_LIBRARYCACHE in


HE snapshots.

WSR_LONGSQL Records information about DV_LONG_SQL in snapshots.

WSR_SEGMENT Records snapshot information about DV_SEGMENT_STATS

WSR_SQL_LIST A global temporary table, records mappings between SQL_ID


and SQL_TEXT saved when the WSR report is generated.

WSR_SQL_LIST_PLA A global temporary table, records mappings between SQL_ID


N and SQL execution plans saved when the WSR report is
generated.

WSR_WAITSTAT Records information about DV_XACT_LOCKS in snapshots.

3.1.1 SYS_BACKUP_SETS
Records information about backup sets from physical backup files.

Table 3-2 SYS_BACKUP_SETS columns


No. Column Name Data Type Description

0 RECID BINARY_BIGINT Backup set record ID

1 TYPE BINARY_INTEG Backup set type


ER

2 STAGE BINARY_INTEG Backup set backup stage


ER

3 STATUS BINARY_INTEG Backup status


ER

4 INCREMENTA BINARY_INTEG Backup level


L_LEVEL ER

5 TAG VARCHAR(64) Backup tag

6 SCN BINARY_BIGINT Backup set SCN

7 LSN BINARY_BIGINT Backup set LSN

8 DEVICE_TYPE BINARY_INTEG Backup media type


ER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 BASE_TAG VARCHAR(64 Tag of the depended baseline backup


BYTE) set

10 DIR VARCHAR(256 Backup set directory


BYTE)

11 RESETLOGS BINARY_INTEG Database RESETLOG value


ER

12 POLICY VARCHAR(128 Backup media policy. This column is


BYTE) invalid for backup to disk.

13 RCY_ASN BINARY_INTEG No. of the backup set log file at the


ER start replay point

14 RCY_OFFSET BINARY_BIGINT Offset of the backup set log file at the


start replay point

15 RCY_LFN BINARY_BIGINT LSN of the backup set log file at the


start replay point

16 LRP_ASN BINARY_INTEG ASN of the backup set log file at the


ER minimum replay point

17 LRP_OFFSET BINARY_BIGINT Offset of the backup set log file at the


minimum replay point

18 LRP_LFN BINARY_BIGINT LSN of the backup set log file at the


minimum replay point

19 START_TIME TIMESTAMP(6) Backup start time

20 COMPLETION TIMESTAMP(6) Backup completion time


_TIME

3.1.2 SYS_COLUMNS
Records information about the columns of all tables in the system.

Table 3-3 SYS_COLUMNS columns

No. Column Data Type Description


Name

0 USER# BINARY_INTEG User ID


ER

1 TABLE# BINARY_INTEG Table ID


ER

2 ID BINARY_INTEG Column ID
ER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

3 NAME VARCHAR(64 Column name


BYTE)

4 DATATYPE BINARY_INTEG Column data type


ER

5 BYTES BINARY_INTEG Column size


ER

6 PRECISION BINARY_INTEG Precision of a NUMBER type column


ER

7 SCALE BINARY_INTEG Scale of a NUMBER type column


ER

8 NULLABLE BINARY_INTEG Whether a column can be empty


ER

9 FLAGS BINARY_INTEG Column attribute flag


ER Code description:
0x00000001 (hidden)
0x00000002 (deleted)
0x00000004 (compressed)
0x00000008 (sequence)
0x00000010 (updated by default)
0x00000020 (character)
0x00000040 (virtual column)
0x00000080 (auto-decrement)
0x00000100 (double quotation mark)

10 DEFAULT_TE VARCHAR(1024 Default column value (text)


XT BYTE)

11 DEFAULT_DA RAW(4096) Default column value (expression)


TA

12 NUM_DISTIN BINARY_INTEG Number of distinct values in the


CT ER column

13 LOW_VALUE VARCHAR(64 Minimum value in the column


BYTE)

14 HIGH_VALUE VARCHAR(64 Maximum value in the column


BYTE)

15 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

16 OPTIONS RAW(16) Reserved column

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.3 SYS_COMMENTS
Records information about all comments in the system.

Table 3-4 SYS_COMMENTS columns

No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 COLUMN# BINARY_INTEGE Column ID


R

3 TEXT VARCHAR(4000 Comment


BYTE) information of a
column

3.1.4 SYS_CONSTRAINT_DEFS
Records information about all constraints in the system.

Table 3-5 SYS_CONSTRAINT_DEF columns

No. Column Data Type Description


Name

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 CONS_NAM VARCHAR(64 Constraint name


E BYTE)

3 CONS_TYPE BINARY_INTEGE Constraint type


R Note:
0: primary
1: unique
2: reference
3: check

4 COLS BINARY_INTEGE Number of columns on which a


R constraint is created

5 COL_LIST VARCHAR(128 Sequence number of a column on which


BYTE) a constraint is created

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 70


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

6 IND# BINARY_INTEGE Index sequence


R

7 REF_USER# BINARY_INTEGE User ID of the table referenced by a


R foreign key constraint

8 REF_TABLE BINARY_INTEGE ID of the table referenced by a foreign


# R key constraint

9 REF_CONS BINARY_INTEGE ID of the index corresponding to the


R primary key or unique constraint
referenced by a foreign key constraint

10 COND_TEX VARCHAR(2048 Condition text for a check constraint


T BYTE)

11 COND_DAT BINARY(4096) Serialized content of a check constraint


A condition

12 FLAGS BINARY_INTEGE Constraint status, a combination of


R masks:
l 0: Disable indexes, constraints, data
validation, and anonymization.
l 1: Use indexes.
l 2: Enable constraints.
l 4: Validate existing data.
l 8: Anonymize the constraint.
l 1024: encode flag
If multiple states are enabled, FLAGS is
the sum of the corresponding identifiers.
For example, if constraints and data
validation are enabled, the value of
FLAGS is 6 (4+2).

13 REFACT BINARY_INTEGE Cascading deletion attribute. This


R parameter is valid only for foreign key
constraints and is empty for non-foreign
key constraints.
l 0: Deletion is not allowed.
l 1: ON DELETE CASCADE
l 2: ON DELETE SET NULL

3.1.5 SYS_DATA_NODES
Records information about all database nodes.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 71


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-6 SYS_DATA_NODES columns

No. Column Name Data Type Description

0 NODE_ID BINARY_INTEGE Node ID


R

1 NODE_NAME VARCHAR(128 Node name


BYTE)

2 NODE_TYPE VARCHAR(128 Node type


BYTE)

3 NODE_HOST VARCHAR(64 Service IP address


BYTE) of the node

4 NODE_PORT BINARY_INTEGE Service port of the


R node

5 GROUP_ID BINARY_INTEGE ID of the replication


R group to which the
node belongs

6 IS_PRIMARY BINARY_INTEGE Whether the node is


R primary in its
replication group

7 WEIGHT BINARY_INTEGE Weight


R

8 NODE_USER VARCHAR(128 Name of the


BYTE) connection user

9 NODE_PASSWORD VARCHAR(512 Encrypted password


BYTE) of the connection
user

10 MIN_CONN BINARY_INTEGE Minimum number of


R connections

11 MAX_CONN BINARY_INTEGE Maximum number


R of connections

3.1.6 EXP_TAB_ORDERS
Records the export sequence of tables. This system catalog is a temporary table used by the
EXP tool.

Table 3-7 EXP_TAB_ORDERS columns

No. Column Name Data Type Description

0 TBL_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 72


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 TBL_LEVEL BINARY_INTEGE Sequence number of


R the table. The value
starts from 1. A
smaller value of
TBL_LEVEL
indicates a higher
priority for export.

3.1.7 EXP_TAB_RELATIONS
Records the dependencies of tables. This system catalog is a temporary table used by the EXP
tool.

Table 3-8 EXP_TAB_RELATIONS columns

No. Column Name Data Type Description

0 TBL_NAME VARCHAR(64 Table name


BYTE)

1 TBL_PARENT VARCHAR(64 Name of the parent


BYTE) table that the table
depends on

3.1.8 SYS_DEPENDENCIES
Records information about dependencies between all objects in the system.

Table 3-9 SYS_DEPENDENCIES columns

No. Column Name Data Type Description

0 D_OWNER# BINARY_INTEGER User ID

1 D_OBJ# BINARY_BIGINT Object ID

2 D_TYPE# BINARY_INTEGER Object type ID

3 D_SCN BINARY_BIGINT Object SCN

4 ORDER# BINARY_INTEGER Dependency No.

5 P_OWNER# BINARY_INTEGER Referenced object user ID

6 P_OBJ# BINARY_BIGINT Referenced object ID

7 P_TYPE# BINARY_INTEGER Referenced object type ID

8 P_SCN BINARY_BIGINT Referenced object SCN

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 73


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 D_NAME VARCHAR(64 BYTE) Object name

10 P_NAME VARCHAR(64 BYTE) Referenced object name

Note:
The values of D_TYPE# and P_TYPE# are enumerated integers. 0 indicates a table. 1
indicates a view, 2 indicates a sequence, 3 indicates a stored procedure, 7 indicates a noun, 8
indicates a function, 9 indicates a trigger, 10 indicates an index, 11 indicates a LOB, 12
indicates a partitioned table, 13 indicates a partitioned index, and 14 indicates a LOB in a
partition.

3.1.9 SYS_DISTRIBUTE_RULES
Records distribution rules. (If GaussDB 100 is deployed in distributed mode, you can query
this system catalog for data. In standalone deployment, this system catalog has no data.)

Table 3-10 SYS_DISTRIBUTE_RULES columns


No. Column Name Data Type Description

0 UID BINARY_INTEGE User ID


R

1 ID BINARY_INTEGE Distribution rule ID


R

2 DIST_DATA VARCHAR(1024 Distribution data


BYTE)

3 BUCKETS BLOB Hash bucket (valid


when hash
distribution is used)

4 NAME VARCHAR(64 Distribution rule


BYTE) name

5 ORG_SCN BINARY_BIGINT SCN when a


distribution rule
table is created

6 CHG_SCN BINARY_BIGINT SCN of the last


DDL operation on a
distribution rule
table

7 COLUMNS VARCHAR(1024 Reserved column


BYTE)

8 COLUMN_COUNT BINARY_INTEGE Number of columns


R in a distribution rule

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 74


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.10 SYS_DISTRIBUTE_STRATEGIES
Records information about table distribution.

Table 3-11 SYS_DISTRIBUTE_STRATEGIES columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE Username


R

1 TABLE# BINARY_INTEGE Table name


R

2 DIST_DATA VARCHAR(1024 Table distribution


BYTE)

3 BUCKETS BLOB Hash bucket (valid


when hash
distribution is used)

3.1.11 SYS_DUMMY
Records the constants of an expression.

Table 3-12 SYS_DUMMY columns


No. Column Name Data Type Description

0 DUMMY VARCHAR(1) Expression constant

3.1.12 SYS_EXTERNAL_TABLES
Records information about external tables in the system.

Table 3-13 SYS_EXTERNAL_TABLES columns


No. Column Name Data Type Description

0 TABLE# BINARY_INTEGE Table ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 75


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 TYPE BINARY_INTEGE Type of the external


R table. Value 0
indicates an external
table of the LODER
type, with data read
from files. Value 1
indicates an external
table of the
DATAPUMP type,
with data written
into files.

2 DIRECTORY VARCHAR(256 Directory of the file


BYTE) associated with the
external table

3 LOCATION VARCHAR(30 Name of the file


BYTE) associated with the
external table

4 RECORDS_DEL VARCHAR(1 Delimiter of rows in


BYTE) the file

5 FIELDS_DEL VARCHAR(1 Delimiter of


BYTE) columns in the file

3.1.13 SYS_GARBAGE_SEGMENTS
Records information about garbage segments in the system.

Table 3-14 SYS_GARBAGE_SEGMENTS columns


No. Column Name Data Type Description

0 UID BINARY_INTEGE ID of the user to


R which the sequence
belongs

1 OID BINARY_INTEGE Table ID


R

2 INDEX_ID BINARY_INTEGE Index ID


R

3 COLUMN_ID BINARY_INTEGE Column ID


R

4 SPACE BINARY_INTEGE ID of the tablespace


R where the index is
created

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 76


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 ENTRY BINARY_BIGINT ID of the entry page


for the index

6 ORG_SCN BINARY_BIGINT Original SCN

7 SEG_SCN BINARY_BIGINT SCN when the


segment is created

8 INITRANS BINARY_INTEGE Initial number of


R transactions

9 PCTFREE BINARY_INTEGE Percentage of


R minimum reserved
space

10 OP_TYPE BINARY_INTEGE Segment operation


R type

11 REUSE BINARY_INTEGE Whether to reuse the


R segment

12 SERIAL BINARY_BIGINT Session sequence


number, used to
uniquely identify a
session object

13 SPARE2 BINARY_INTEGE Reserved column


R

14 SPARE3 BINARY_INTEGE Reserved column


R

3.1.14 SYS_HISTGRAM_ABSTR
Records information about the headers of histograms in the system.

Table 3-15 SYS_HISTGRAM_ABSTR columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TAB# BINARY_INTEGE Table ID


R

2 COL# BINARY_INTEGE Column ID


R

3 BUCKET_NUM BINARY_INTEGE Number of buckets in the


R histogram

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 77


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 ROW_NUM BINARY_INTEGE Number of rows


R

5 NULL_NUM BINARY_INTEGE Number of NULL values in


R the column

6 ANALYZE_TIME DATE Time point when column


statistics are obtained

7 MINVALUE VARCHAR(4000 Minimum value of the


BYTE) column

8 MAXVALUE VARCHAR(4000 Maximum value of the


BYTE) column

9 DIST_NUM BINARY_INTEGE Number of distinct values in


R the column

10 DENSITY BINARY_DOUBLE Column density (1/


DIST_NUM)

11 SPARE1 BINARY_BIGINT Reserved column

12 SPARE2 BINARY_BIGINT Reserved column

13 SPARE3 BINARY_BIGINT Reserved column

14 SPARE4 BINARY_BIGINT Reserved column

3.1.15 SYS_HISTGRAM
Records information about histograms in the system.

Table 3-16 SYS_HISTGRAM columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGER User ID

1 TABLE# BINARY_INTEGER Table ID

2 COL# BINARY_INTEGER Column ID

3 BUCKET VARCHAR(4000 Column value measured


BYTE) after data distribution

4 ENDPOINT BINARY_INTEGER Total number of rows


with a value less than
the corresponding
column value

5 PART# BINARY_INTEGER Partition ID

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 78


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 EPVALUE VARCHAR(1000 Histogram endpoint


BYTE) value

4 SPARE1 BINARY_BIGINT Reserved column

5 SPARE2 BINARY_BIGINT Reserved column

6 SPARE3 BINARY_BIGINT Reserved column

3.1.16 SYS_INDEXES
Records information about all indexes in the system.

Table 3-17 SYS_INDEXES columns

No. Column Name Data Type Description

0 USER# INTEGER User ID

1 TABLE# INTEGER Table ID

2 ID INTEGER Index ID

3 NAME VARCHAR(64) Index name

4 SPACE# INTEGER ID of the tablespace where the


index is created

5 SEQUENCE# BIGINT SCN when the index is created

6 ENTRY BIGINT ID of the entry page for the index

7 IS_PRIMARY INTEGER Whether the index is a primary


key

8 IS_UNIQUE INTEGER Whether the index is unique

9 TYPE INTEGER Index type (Currently, only B-tree


indexes are supported.)

10 COLS INTEGER Number of columns within an


index

11 COL_LIST VARCHAR(128) ID list of columns within an index

12 INITRANS INTEGER Number of initial ITL entries on a


page

13 CR_MODE INTEGER Consistent read of a page (row-


level or page-level)

14 FLAGS INTEGER Index attribute flag (valid or not)

15 PARTITIONED INTEGER Partitioned or not

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 79


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

16 PCTFREE INTEGER Percentage of minimum reserved


space

17 BLEVEL INTEGER Index tree level

18 LEVEL_BLOCKS INTEGER Number of leaf node pages

19 DISTINCT_KEYS INTEGER Number of distinct keys

20 AVG_LEAF_BLO REAL Average number of leaf nodes for


CKS_PER_KEY each key

21 AVG_DATA_BLO REAL Average number of data blocks for


CKS_PER_KEY each key

22 ANALYZETIME TIMESTAMP Time when statistics were


collected last time

23 EMPTY_LEAF_B INTEGER Number of empty leaf blocks


LOCKS

24 OPTIONS RAW(16) Reserved column

25 CLUFAC INTEGER Index clustering factor (for


viewing index-specific data
distribution)

26 SAMPLESIZE INTEGER Sample size of statistics

27 OBJ# INTEGER Object ID (globally unique)

28 COMB_COLS_2_ BINARY_INTE Number of unique key values in


NDV GER two joined columns

29 COMB_COLS_3_ BINARY_INTE Number of unique key values in


NDV GER three joined columns

30 COMB_COLS_4_ BINARY_INTE Number of unique key values in


NDV GER four joined columns

3.1.17 SYS_INDEX_PARTS
Records information about all partitioned indexes in the system.

Table 3-18 SYS_INDEX_PARTS columns

No. Column Name Data Type Description

0 USER# BINARY_INTEGER User ID

1 TABLE# BINARY_INTEGER Table ID

2 INDEX# BINARY_INTEGER Index ID

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 80


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 PART# BINARY_INTEGER Index partition ID

4 NAME VARCHAR(64 Index partition name


BYTE)

5 HIBOUNDLEN BINARY_INTEGER Length of a partition


boundary string

6 HIBOUNDVAL VARCHAR(4000 Partition boundary string


BYTE)

7 SPACE# BINARY_INTEGER Tablespace ID

8 ORG_SCN BINARY_BIGINT Creation SCN

9 ENTRY BINARY_BIGINT Entry address

10 INITRANS BINARY_INTEGER Initial number of


transactions

11 PCTFREE BINARY_INTEGER Percentage of minimum


reserved space

12 FLAGS BINARY_INTEGER Index attribute flag (valid


or not)

13 BHIBOUNDVAL BINARY(4000) Partition boundary value

14 BLEVEL BINARY_INTEGER Index tree level

15 LEVEL_BLOCKS BINARY_INTEGER Number of leaf node


pages

16 DISTKEY BINARY_INTEGER Number of distinct keys

17 LBLKKEY BINARY_DOUBLE Average number of leaf


nodes for each key

18 DBLKKEY BINARY_DOUBLE Average number of data


blocks for each key

19 ANALYZETIME DATE Time when statistics were


collected last time

20 EMPTY_LEAF_BLO BINARY_INTEGER Number of empty leaf


CKS blocks

21 CLUFAC BINARY_INTEGER Index aggregation factor

22 SAMPLESIZE BINARY_INTEGER Sample size

23 COMB_COLS_2_ND BINARY_INTEGER Number of unique key


V values in two joined
columns

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 81


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

24 COMB_COLS_3_ND BINARY_INTEGER Number of unique key


V values in three joined
columns

25 COMB_COLS_4_ND BINARY_INTEGER Number of unique key


V values in four joined
columns

3.1.18 SYS_JOBS
Records information about scheduled jobs in the system.

Table 3-19 SYS_JOBS columns


No. Column Name Data Type Description

0 JOB BINARY_BIGINT Job ID

1 LOWNER VARCHAR(64 User who submits


BYTE) the job

2 POWNER VARCHAR(64 User granted with


BYTE) the job permission

3 COWNER VARCHAR(64 User who performs


BYTE) syntax analysis on
the job

4 LAST_DATE DATE Time when the job


was successfully
executed last time

5 THIS_DATE DATE Start time of a


running job. If there
is no job running,
the value will be
null.

6 NEXT_DATE DATE Time when the


scheduled job will
be executed next
time

7 TOTAL BINARY_INTEGE Total time required


R for running the job
(unit: second)

8 INTERVAL# VARCHAR(200 Expression for


BYTE) calculating the next
time for job running

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 82


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 FAILURES BINARY_INTEGE Number of times the


R job consecutively
fails

10 BROKEN BINARY_INTEGE Status (blocked or


R not)

11 WHAT VARCHAR(4000 PL/SQL block to be


BYTE) executed in the job

12 CREATE_DATE DATE Job creation time

13 INSTANCE BINARY_INTEGE Instance ID (default:


R 0)

3.1.19 SYS_LINKS
A reserved function view, with no data.

Table 3-20 SYS_LINKS columns


No. Column Name Data Type Description

0 OWNER# BINARY_INTEGE User ID


R

1 NAME VARCHAR(128 Database connection


BYTE) name

2 CTIME DATE Creation date

3 NODE_ID BINARY_INTEGE Node ID


R

4 HOST VARCHAR(2000 IP address and port


BYTE) number of the node
for connection

5 USERID VARCHAR(64 Username for


BYTE) connection

6 PASSWORD VARCHAR(512 Password of the user


BYTE) for connection

3.1.20 SYS_LOBS
Records information about large objects in the system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 83


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-21 SYS_LOBS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 COLUMN# BINARY_INTEGE Column ID


R

3 SPACE# BINARY_INTEGE Tablespace ID


R

4 ENTRY BINARY_BIGINT ID of the entry page


for a LOB column

5 ORG_SCN BINARY_BIGINT Creation SCN

6 CHG_SCN BINARY_BIGINT Modification SCN

7 CHUNK BINARY_INTEGE LOB page size


R

8 PCTVERSION BINARY_INTEGE Number of pages


R that can be reserved
for a deleted LOB
page. If the actual
number exceeds the
column value, the
page will be reused.

9 RETENSION BINARY_INTEGE Number of seconds


R that can be reserved
for a deleted LOB
page. If the actual
time exceeds this
parameter value, the
page will be reused.

10 FLAGS BINARY_INTEGE LOB type (inline or


R out-of-line, reserved
column, only the
out-of-line mode
supported currently)

3.1.21 SYS_LOB_PARTS
Records information about large partitioned objects in the system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 84


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-22 SYS_LOB_PARTS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 COLUMN# BINARY_INTEGE Column ID


R

3 PART# BINARY_INTEGE LOB partition ID


R

4 SPACE# BINARY_INTEGE Tablespace ID


R

5 ORG_SCN BINARY_BIGINT Creation SCN

6 ENTRY BINARY_BIGINT Entry address

7 FLAGS BINARY_INTEGE Attribute flag of a


R large partitioned
object. This is a
reserved system
interface.

3.1.22 SYS_LOGIC_REPL
Records information about tables where the logical replication service is enabled.

Table 3-23 SYS_LOGIC_REPL columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 STATUS BINARY_INTEGE Status of the logical


R replication service
for the table.
Currently, value 1
(enabled) is
supported.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 85


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 INDEX# BINARY_INTEGE ID of the index for


R determining the
uniqueness of a
record in the logical
replication process.
Currently, only the
primary key can be
used to determine
the uniqueness.
Therefore, the index
ID actually is the ID
of the unique index
used by the primary
key constraint.

3.1.23 SYS_DML_STATS
Records statistics about operations on tables in the system.

Table 3-24 SYS_DML_STATS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEG User ID


ER

1 TABLE# BINARY_INTEG Table ID


ER

2 INSERTS BINARY_INTEG Number of times the


ER INSERT operation is
performed since the
ANALYZE statement
was performed last
time

3 UPDATES BINARY_INTEG Number of times the


ER UPDATE operation is
performed since the
ANALYZE statement
was performed last
time

4 DELETES BINARY_INTEG Number of times the


ER DELETE operation is
performed since the
ANALYZE statement
was performed last
time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 86


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 MODIFY_TIME TIMESTAMP(6) Table update time

6 FLAGS BINARY_INTEG Reserved column


ER

7 DROP_SEGMENT BINARY_INTEG Number of segments


S ER deleted from
partitions and
subpartitions since the
ANALYZE statement
was performed last
time

8 PARTED BINARY_INTEG Indicates whether a


ER table is partitioned. 1:
partitioned table; 0:
non-partitioned table

9 PART# BINARY_INTEG Partition ID of a


ER partitioned table

3.1.24 SYS_OBJECT_PRIVS
Records the object authorization information about non-SYS users and all roles in the system.

Table 3-25 SYS_OBJECT_PRIVS columns


No. Column Name Data Type Description

0 GRANTEE BINARY_INTE ID of an authorized


GER user

1 GRANTEE_TYPE BINARY_INTE Type of an authorized


GER user. Value 0 indicates
a user, and value 1
indicates a role.

2 OBJECT_OWNER BINARY_INTE Object owner ID


GER

3 OBJECT_NAME VARCHAR(64 Object name


BYTE)

4 OBJECT_TYPE BINARY_INTE ID of the object type


GER (table, view, function,
index, or sequence)
0: table
1: view
2: sequence
3: procedure

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 87


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 PRIVILEGE BINARY_INTE ID of the object


GER permission
l 0: ALTER
l 1: DELETE
l 2: EXECUTE
l 3: INDEX
l 4: INSERT
l 5: READ
l 6: REFERENCES
l 7: SELECT
l 8: UPDATE

6 GRANTABLE BINARY_INTE Whether the current


GER user can grant the
object permission to
another user or role.
Values are:
0: no
1: yes

7 GRANTOR INTEGER Authorization user

3.1.25 SYS_PART_COLUMNS
Records information about partition columns in the system.

Table 3-26 SYS_PART_COLUMNS columns

No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 COLUMN# BINARY_INTEGE Column ID


R

3 POSITION# BINARY_INTEGE Column on which


R the nth partition key
is created

4 DATATYPE BINARY_INTEGE Column data type


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 88


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.26 SYS_PART_OBJECTS
Records information about partitioned objects in the system.

Table 3-27 SYS_PART_OBJECTS columns

No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 INDEX# BINARY_INTEGE Index ID


R

3 PARTTYPE BINARY_INTEGE Partitioning type


R

4 PARTCNT# BINARY_INTEGE Number of partitions


R

5 PARTKEYS# BINARY_INTEGE Partition key


R

6 FLAGS BINARY_INTEGE Reserved column


R

7 INTERVAL VARCHAR(1000 Partition boundary


BYTE) string

8 BINTERVAL BINARY(200) Partition boundary


value

3.1.27 SYS_PART_STORES
Records information about partition storage in the system.

Table 3-28 SYS_PART_STORES columns

No. Column Data Type Description


Name

0 USER# BINARY_INTEGER User ID

1 TABLE# BINARY_INTEGER Table ID

2 INDEX# BINARY_INTEGER Index ID

3 POSITION BINARY_INTEGER Position number of each tablespace


# in the tablespace list. The value
starts from 0.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 89


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

4 SPACE# BINARY_INTEGER Tablespace ID

3.1.28 SYS_PENDING_DIST_TRANS
Records information about distributed two-phase transactions.

Table 3-29 SYS_PENDING_DIST_TRANS columns


No. Column Name Data Type Description

0 GLOBAL_TRAN_I VARCHAR(256 Global transaction


D BYTE) ID (unique index)

1 TRAN_COMMIT_ TIMESTAMP(6) Time point when a


TIME transaction is
commit

2 TRX_STATUS BINARY_INTEGE Transaction commit


R status
0: prepared; 1:
committed

3 NEED_CLEAN BINARY_INTEGE Whether data needs


R to be deleted
0: no
1: yes

3.1.29 SYS_PENDING_TRANS
Records information about pending, two-phase transactions in the system.

Table 3-30 SYS_PENDING_TRANS columns


No. Column Name Data Type Description

0 GLOBAL_TRAN_I VARCHAR(256 Global transaction


D BYTE) ID (unique index)

1 LOCAL_TRAN_ID BINARY_BIGINT Local transaction ID

2 TLOCK_LOBS BINARY(4000) Table lock held by a


transaction and the
corresponding LOB
information

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 90


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 TLOCK_LOBS_EX BLOB Table lock held by a


T transaction and the
corresponding LOB
information when
the TLOCK_LOBS
column has
insufficient space

3.1.30 SYS_PROCS
Records information about stored procedures, user-defined functions, and triggers in system
catalogs.

Table 3-31 SYS_PROCS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEG User ID


ER

1 OBJ# BINARY_BIGIN Object ID


T

2 NAME VARCHAR(128 Object name (stored procedure,


BYTE) user-defined function, or trigger)

3 CLASS BINARY_INTEG Classification. Value 1 indicates a


ER stored procedure or user-defined
function, and value 2 indicates a
trigger.

4 TYPE CHAR(1) Type:


P: stored procedure
F: user-defined function
T: trigger

5 SOURCE CLOB Source code

6 AGGREGATE BINARY_INTEG Not used currently


ER

7 PIPELINED BINARY_INTEG Not used currently


ER

8 TRIG_TABLE_USE VARCHAR(128 Username of a trigger table


R BYTE)

9 TRIG_TABLE VARCHAR(128 Name of a trigger table


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 91


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

10 ORG_SCN BINARY_BIGIN SCN when an object is created


T

11 CHG_SCN BINARY_BIGIN SCN when an object is modified


T

12 TRIG_STATUS VARCHAR(16 Trigger status. Value ENABLE


BYTE) indicates that the trigger takes
effect, and value DISABLED
indicates that the trigger does not
work.

13 STATUS BINARY_INTEG Validity status. 0: invalid; 1: valid;


ER 2: unknown

3.1.31 SYS_PROC_ARGS
Records information about the parameters of stored procedures and user-defined functions in
system catalogs. The system catalogs are available only when there are parameters.

Table 3-32 SYS_PROC_ARGS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEG User ID


ER

1 OBJECT_NAME VARCHAR(128 Object name (stored procedure or


BYTE) user-defined function)

2 ARGUMENT_NAM VARCHAR(128 Parameter name of a stored


E BYTE) procedure or customized function.
Note that the return value of a
customized function is also used
as a parameter, but the parameter
name is null.

3 POSITION BINARY_INTEG Position of all parameters at the


ER same DATA_LEVEL, starting
from 0

4 SEQUENCE BINARY_INTEG Sequence of all parameters for the


ER same object, starting from 1

5 DATA_LEVEL BINARY_INTEG Level of parameters for an object,


ER supporting only 0 currently

6 DATA_TYPE BINARY_INTEG Data type


ER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 92


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

7 DEFAULTED BINARY_INTEG Whether the parameter has a


ER default value

8 DEFAULT_VALUE VARCHAR(128 Default value, a reserved system


BYTE) interface

9 DEFAULT_LENGTH VARCHAR(128 Default value length, a reserved


BYTE) system interface

10 IN_OUT BINARY_INTEG Direction of a parameter. IN:


ER input parameter; OUT: output
parameter; IN OUT: both input
and output parameters

11 DATA_LENGTH BINARY_INTEG Data length


ER

12 DATA_PRECISION BINARY_INTEG Data precision, valid for numbers


ER

13 DATA_SCALE BINARY_INTEG Data scale, valid for numbers


ER

14 TYPE# BINARY_BIGIN ID of a customized complex type,


T a reserved system interface

15 RESERVERD VARCHAR(128 Extension bit, which is


BYTE) meaningless

3.1.32 SYS_PROFILE
Records information about profiles in the system.

Table 3-33 SYS_PROFILE columns


No. Column Name Data Type Description

0 NAME VARCHAR(64 Profile name


BYTE)

1 PROFILE# BINARY_INTEGE Profile ID


R

2 RESOURCE# BINARY_INTEGE Attribute ID


R

3 THRESHOLD BINARY_BIGINT Threshold

3.1.33 SYS_RECYCLEBIN
Records information about the recycle bin in the system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 93


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-34 SYS_RECYCLEBIN columns


No. Column Name Data Type Description

1 ID BINARY_BIGINT ID of an object in
the recycle bin

2 NAME VARCHAR(30 Name of an object in


BYTE) the recycle bin

3 USER# BINARY_INTEGE ID of a user


R corresponding to the
recycle bin

4 ORG_NAME VARCHAR(64 Original object


BYTE) name

5 PARTITION_NAM VARCHAR(64 Object partition


E BYTE) name

6 TYPE# BINARY_INTEGE Object type


R 0: table; 1: index; 2:
LOB; 3: partitioned
table; 4: partitioned
index; 5: partitioned
LOB

7 OPERATION# BINARY_INTEGE Operation type


R

8 SPACE# BINARY_INTEGE Tablespace ID


R

9 ENTRY BINARY_BIGINT Entry page ID

10 FLAGS BINARY_INTEGE Note: 32 bits are


R used as a mask.
Currently, only four
bits are used.
0x0001: flashback
or not
0x0010: purge or not
0x0100: constraint
or not
0x1000: encode or
not

11 ORG_SCN BINARY_BIGINT SCN when an object


is created

12 REC_SCN BINARY_BIGINT SCN when an object


is moved to the
recycle bin

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 94


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

13 TCHG_SCN BINARY_BIGINT SCN when an object


definition is
modified

14 BASE_ID BINARY_BIGINT Base object ID

15 PURGE_ID BINARY_BIGINT Object ID

3.1.34 SYS_ROLES
Records information about roles in the system.

Table 3-35 SYS_ROLES columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE Role ID
R

1 OWNER_UID BINARY_INTEGE Owner user ID


R

2 NAME VARCHAR(64 Role name


BYTE)

3 PASSWORD VARCHAR(256 Role password


BYTE)

3.1.35 SYS_SEQUENCES
Records information about all sequences in the system.

Table 3-36 SYS_SEQUENCES columns

No. Column Name Data Type Description

0 UID BINARY_INTEGE ID of the user to


R which the sequence
belongs

1 ID BINARY_INTEGE Sequence ID
R

2 NAME VARCHAR(64 Sequence name


BYTE)

3 MINVAL BINARY_BIGINT Minimum value of


the sequence

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 95


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 MAXVAL BINARY_BIGINT Maximum value of


the sequence

5 STEP BINARY_BIGINT Step length

6 CACHESIZE BINARY_BIGINT Cache size

7 CYCLE_FLAG BINARY_INTEGE Whether the


R sequence wraps
around on reaching
the limit

8 ORDER_FLAG BINARY_INTEGE Whether sequence


R numbers are
generated in order

9 ORG_SCN BINARY_BIGINT Creation SCN

10 CHG_SCN BINARY_BIGINT Modification SCN

11 LAST_NUMBER BINARY_BIGINT Last sequence


number written to
disk

3.1.36 SYS_SHADOW_INDEXES
Records information about shadow indexes in the system.

Table 3-37 SYS_SHADOW_INDEXES columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 ID BINARY_INTEGE Index ID
R

3 NAME VARCHAR(64 Index name


BYTE)

4 SPACE# BINARY_INTEGE ID of the tablespace


R where the index is
created

5 SEQUENCE# BINARY_BIGINT SCN when the index


is created

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 96


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 ENTRY BINARY_BIGINT ID of the entry page


for the index

7 IS_PRIMARY BINARY_INTEGE Whether the index is


R a primary key

8 IS_UNIQUE BINARY_INTEGE Whether the index is


R unique

9 TYPE BINARY_INTEGE Index type


R (Currently, only B-
tree indexes are
supported.)

10 COLS BINARY_INTEGE Number of columns


R within an index

11 COL_LIST VARCHAR(128 ID list of columns


BYTE) within an index

12 INITRANS BINARY_INTEGE Number of initial


R ITL entries on a
page

13 CR_MODE BINARY_INTEGE Consistent read of a


R page (row-level or
page-level)

14 FLAGS BINARY_INTEGE Index attribute flag


R (valid or not)

15 PARTED BINARY_INTEGE Partitioned or not


R

16 PCTFREE BINARY_INTEGE Percentage of


R minimum reserved
space

3.1.37 SYS_SHADOW_INDEX_PARTS
Records information about shadow partitioned indexes in the system.

Table 3-38 SYS_SHADOW_INDEX_PARTS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 97


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 INDEX# BINARY_INTEGE Index ID


R

3 PART# BINARY_INTEGE Table partition ID


R

4 NAME VARCHAR(64 Index name


BYTE)

5 HIBOUNDLEN BINARY_INTEGE Length of a partition


R boundary string

6 HIBOUNDVAL VARCHAR(4000 Partition boundary


BYTE) string

7 SPACE# BINARY_INTEGE ID of the tablespace


R where the index is
created

8 ORG_SCN BINARY_BIGINT Creation SCN

9 ENTRY BINARY_BIGINT ID of the entry page


for the index

10 INITRANS BINARY_INTEGE Number of initial


R ITL entries on a
page

11 PCTFREE BINARY_INTEGE Percentage of


R minimum reserved
space

12 FLAGS BINARY_INTEGE Index attribute flag


R (valid or not)

13 BHIBOUNDVAL BINARY(4000) Partition boundary


value

3.1.38 SYS_SQL_MAPS
Records all SQL mapping relationships in the system.

Table 3-39 SYS_SQL_MAPS columns

No. Column Name Data Type Description

0 SRC_HASHCODE BINARY_INTEGE Hash value of the


R source SQL
statement

1 SRC_TEXT CLOB Source SQL


statement

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 98


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 DST_TEXT CLOB Target SQL


statement

3 USER# BINARY_INTEGE User ID


R

3.1.39 SYS_SYNONYMS
Records information about all synonyms in the system.

Table 3-40 SYS_SYNONYMS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 ID BINARY_INTEGE Synonym ID
R

2 ORG_SCN BINARY_BIGINT Creation SCN

3 CHG_SCN BINARY_BIGINT Modification SCN

4 SYNONYM_NAM VARCHAR(64 Synonym name


E BYTE)

5 TABLE_OWNER VARCHAR(64 Name of the user


BYTE) owning the synonym
object

6 TABLE_NAME VARCHAR(64 Synonym object


BYTE) name

7 FLAGS BINARY_INTEGE Synonym


R invalidation flag. 0:
invalid; 1: valid; 2:
unknown

3.1.40 SYS_PRIVS
Records information about all system permissions granted to users and roles in the system.

Table 3-41 SYS_PRIVS columns


No. Column Name Data Type Description

0 GRANTEE_ID BINARY_INTEGE ID of an authorized


R user or role

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 99


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 GRANTEE_TYPE BINARY_INTEGE Type of a grantee. 0:


R user; 1: role

2 PRIVILEGE BINARY_INTEGE Permission ID


R

3 ADMIN_OPTION BINARY_INTEGE Whether a grantee


R has permission to
grant the permission
to other users or
roles

3.1.41 SYS_TABLES
Records information about all tables (including all system catalogs and user tables) in the
system.

Table 3-42 SYS_TABLES columns


No. Column Name Data Type Description

0 USER# BINARY_INT User ID


EGER

1 ID BINARY_INT Table ID
EGER

2 NAME VARCHAR(64 Table name


BYTE)

3 SPACE# BINARY_INT ID of the tablespace where the table


EGER is stored

4 ORG_SCN BINARY_BIGI SCN when the table is created


NT

5 CHG_SCN BINARY_BIGI SCN of the last DDL operation on


NT the table

6 TYPE BINARY_INT Table type


EGER

7 COLS BINARY_INT Number of columns in the table


EGER

8 INDEXES BINARY_INT Number of indexes on the table


EGER

9 PARTITIONED BINARY_INT Whether the table is a partitioned


EGER table

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 100


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

10 ENTRY BINARY_BIGI Entry page ID for the table


NT

11 INITRANS BINARY_INT Number of ITL entries initially


EGER allocated to a page

12 PCTFREE BINARY_INT Percentage of minimum reserved


EGER space for future update operations on
a page

13 CR_MODE BINARY_INT Consistent read of the table (row-


EGER level or page-level)

14 RECYCLED BINARY_INT Whether the table is in the recycle


EGER bin

15 APPENDONLY BINARY_INT Whether the table is in append-only


EGER mode

16 NUM_ROWS BINARY_INT Number of rows in the table


EGER

17 BLOCKS BINARY_INT Number of blocks in the table


EGER

18 EMPTY_BLOC BINARY_INT Number of empty blocks in the table


KS EGER

19 AVG_ROW_LE BINARY_BIGI Average row length (Collection is


N NT triggered after analyze table
table_name compute statistics is
issued.)

20 SAMPLESIZE BINARY_INT Number of rows for sampling in


EGER statistics collection

21 ANALYZETIME TIMESTAMP( Time when statistics were collected


6) last time

22 SERIAL_START BINARY_BIGI Start value of an auto-increment


NT column

23 OPTIONS RAW(16) Reserved column

24 OBJ# BINARY_INT Object ID


EGER

3.1.42 SYS_TABLE_PARTS
Records information about partitioned tables in the system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 101


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-43 SYS_TABLE_PARTS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 TABLE# BINARY_INTEGE Table ID


R

2 PART# BINARY_INTEGE Table partition ID


R

3 NAME VARCHAR(64 Table partition name


BYTE)

4 HIBOUNDLEN BINARY_INTEGE Length of a partition


R boundary string

5 HIBOUNDVAL VARCHAR(4000 Partition boundary


BYTE) string

6 SPACE# BINARY_INTEGE ID of the tablespace


R where the partition
is stored

7 ORG_SCN BINARY_BIGINT Creation SCN

8 ENTRY BINARY_BIGINT Entry address

9 INITRANS BINARY_INTEGE Initial number of


R transactions

10 PCTFREE BINARY_INTEGE Reserved space


R

11 FLAGS BINARY_INTEGE Flag


R

12 BHIBOUNDVAL BINARY(4000) Partition boundary


value

13 ROWCNT BINARY_INTEGE Number of rows


R

14 BLKCNT BINARY_INTEGE Number of blocks


R

15 EMPCNT BINARY_INTEGE Number of empty


R blocks

16 AVGRLN BINARY_INTEGE Average row length


R

17 SAMPLESIZE BINARY_INTEGE Sample size


R

18 ANALYZETIME DATE Analysis time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 102


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.43 SYS_TMP_SEG_STATS
Records statistics about temporary segments in the system.

Table 3-44 SYS_TMP_SEG_STATS columns

No. Column Name Data Type Description

0 ORG_SCN BINARY_BIGINT Creation SCN

1 UID BINARY_INTEGE User ID


R

2 OID BINARY_INTEGE Table ID


R

3 LOGIC_READS BINARY_BIGINT Number of logical


reads

4 PHYSICAL_WRIT BINARY_BIGINT Number of physical


ES writes

5 PHYSICAL_READ BINARY_BIGINT Number of physical


S reads

6 ITL_WAITS BINARY_BIGINT Number of ITL


waits

7 BUF_BUSY_WAIT BINARY_BIGINT Number of waits


S because the buffer is
busy

3.1.44 SYS_USERS
Records information about all users in the system.

Table 3-45 SYS_USERS columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE User ID
R

1 NAME VARCHAR(64 Username


BYTE)

2 PASSWORD RAW(512) User password

3 DATA_SPACE# BINARY_INTEGE ID of the tablespace


R of a user

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 103


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 TEMP_SPACE# BINARY_INTEGE ID of the temporary


R tablespace of a user

5 CTIME DATE Time when a user is


created

6 PTIME DATE Password change


time

7 EXPTIME DATE User expiry time

8 LTIME DATE User lock time

9 PROFILE# BINARY_INTEGE User profile ID


R

10 ASTATUS BINARY_INTEGE User status


R

11 LCOUNT BINARY_INTEGE Number of login


R failures due to
incorrect passwords

12 OPTIONS RAW(16) Reserved column

3.1.45 SYS_USER_HISTORY
Records the historical passwords of users.

Table 3-46 SYS_USER_HISTORY columns


No. Column Data Type Description
Name

0 USER# BINARY_INTEGER User ID

1 PASSWORD BINARY(512) Encrypted password of the user

2 PASSWORD_ DATE Date when the user password is created


DATE

3.1.46 SYS_USER_ROLES
Records information about the roles of users.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 104


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-47 SYS_USER_ROLES columns

No. Column Data Type Description


Name

0 GRANTEE_I BINARY_INTEGER ID of the role or user to which the role is


D granted

1 GRANTEE_T BINARY_INTEGER Type of an authorized user. Value 0


YPE indicates a user, and value 1 indicates a
role.

2 GRANTED_ BINARY_INTEGER ID of the role granted


ROLE_ID

3 ADMIN_OPT BINARY_INTEGER Administrator option


ION

4 DEFAULT_R BINARY_INTEGER ID of the default role granted to a user


OLE

3.1.47 SYS_VIEWS
Records information about all views in the system, except for dynamic views.

Table 3-48 SYS_VIEWS columns

No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 ID BINARY_INTEGE View ID
R

2 NAME VARCHAR(64 View name


BYTE)

3 COLS BINARY_INTEGE Total number of


R columns in a view

4 FLAGS BINARY_INTEGE Column attribute


R flag

5 ORG_SCN BINARY_BIGINT Creation SCN

6 CHG_SCN BINARY_BIGINT Modification SCN

7 TEXT_LENGTH BINARY_INTEGE Length of a view


R text

8 TEXT CLOB View text

9 SQL_TYPE BINARY_INTEGE SQL type


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 105


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

10 OBJ# BINARY_INTEGE View object


R

3.1.48 SYS_VIEW_COLS
Records column information about views in the system.

Table 3-49 SYS_VIEW_COLSSYS_VIEW_COLS columns


No. Column Name Data Type Description

0 USER# BINARY_INTEGE User ID


R

1 VIEW# BINARY_INTEGE View ID


R

2 ID BINARY_INTEGE Column ID
R

3 NAME VARCHAR(128 Column name


BYTE)

4 DATATYPE BINARY_INTEGE Column data type


R

5 BYTES BINARY_INTEGE Column size


R

6 PRECISION BINARY_INTEGE Precision of a


R NUMBER type
column

7 SCALE BINARY_INTEGE Scale of a


R NUMBER type
column

8 NULLABLE BINARY_INTEGE Whether a column


R can be empty

9 FLAGS BINARY_INTEGE Column attribute


R flag

3.1.49 WSR_PARAMETER
Records parameter values in each snapshot of the database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 106


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-50 WSR_PARAMETER columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_INTE Snapshot ID


GER

1 NAME VARCHAR(64 Parameter name


BYTE)

2 VALUE VARCHAR(204 Parameter value


8 BYTE)

3 DEFAULT_VALU VARCHAR(204 Default parameter value


E 8 BYTE)

4 ISDEFAULT VARCHAR(20 Whether the parameter is set to its default


BYTE) value (TRUE/FALSE)

5 MODIFIABLE VARCHAR(20 Whether the parameter can be modified


BYTE) (TRUE/FALSE)

6 DESCRIPITION VARCHAR(204 Parameter description


8 BYTE)

7 RANGE VARCHAR(204 Value range


8 BYTE)

8 DATATYPE VARCHAR(20 Data type


BYTE)

9 EFFECTIVE VARCHAR(20 Effective mode


BYTE)

3.1.50 WSR_SQLAREA
Records DML execution information in each snapshot of the database.

Table 3-51 WSR_SQLAREA columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 SQL_ID VARCHA SQL statement ID


R(10
BYTE)

2 SQL_TEXT VARCHA SQL statement content


R(8000
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 107


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 MODULE VARCHA SQL statement channel


R(64
BYTE)

4 EXECUTIONS BINARY_B Number of times the SQL statement is


IGINT executed

5 DISK_READS BINARY_B Number of times the SQL statement is read


IGINT from the disk

6 BUFFER_GETS BINARY_B Number of times the SQL statement is read


IGINT from the buffer

7 SORTS BINARY_B Number of times the sort operation is


IGINT performed for the SQL statement

8 PARSE_CALLS BINARY_B Number of times the SQL statement is parsed


IGINT

9 PROCESSED_RO BINARY_B Number of rows pre-fetched by the SQL


WS IGINT statement

10 IO_WAIT_TIME BINARY_B I/O wait time of the SQL statement (unit: μs)
IGINT

11 CON_WAIT_TIM BINARY_B Lock wait time of the SQL statement (unit:


E IGINT μs)

12 CPU_TIME BINARY_B CPU time of the SQL statement (unit: μs)


IGINT

13 ELAPSED_TIME BINARY_B Execution time of the SQL statement (unit:


IGINT μs)

14 REF_COUNT BINARY_B Number of times the SQL statement is


IGINT referenced

15 IS_FREE BOOLEAN Released or not

16 CLEANED BOOLEAN Deleted or not

17 CR_GETS BINARY_B Number of times an SQL statement searches


IGINT in the CR pool in concurrent transaction
scenarios

18 PARSE_TIME BINARY_B Total time of SQL parsing (unit: microsecond)


IGINT

19 PARSING_USER_ VARCHA Name of the user that performs a hard parse


NAME R(64) operation on the SQL statement for the first
time

20 PROGRAM_ID BINARY_B If the SQL statement is parsed for the first


IGINT time in a stored procedure, UDF, or trigger,
this column will display the corresponding
OID. Otherwise, it will display only 0.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 108


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

21 PROGRAM_LINE BINARY_I If the SQL statement is parsed for the first


# NTEGER time in a stored procedure, UDF, or trigger,
this column will display the corresponding
row number of the SQL statement. Otherwise,
it will display only 0.

3.1.51 WSR_SYS_STAT
Records statistics in each snapshot of the database.

Table 3-52 WSR_SYS_STAT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 STAT_ID BINARY_I Statistical item ID


NTEGER

2 STAT_NAME VARCHA Statistical item name


R(64
BYTE)

3 VALUE BINARY_B Statistical item value


IGINT

3.1.52 WSR_SYSTEM
Records statistics in each snapshot of the database.

Table 3-53 WSR_SYSTEM columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 STAT_ID BINARY_I Statistical item ID


NTEGER

2 STAT_NAME VARCHA Statistical item name


R(64
BYTE)

3 VALUE VARCHA Statistical item value


R(128
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 109


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.53 WSR_SYSTEM_EVENT
Records event information in each snapshot of the database.

Table 3-54 WSR_SYSTEM_EVENT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 EVENT# BINARY_I Event ID


NTEGER

2 EVENT VARCHA Event information


R(64
BYTE)

3 WAIT_CLASS VARCHA Wait event class


R(64
BYTE)

4 TOTAL_WAITS VARCHA Total number of wait events


R(64
BYTE)

5 TIME_WAITED BINARY_B Time of the wait event (unit: μs)


IGINT

6 TIME_WAITED_ BINARY_B Time of the wait event (unit: ms)


MICRO IGINT

7 AVERAGE_WAIT BINARY_D Average time of wait events (unit: μs)


OUBLE

8 AVERAGE_WAIT BINARY_B Average time of wait events (unit: ms)


_MICRO IGINT

3.1.54 WSR_SNAPSHOT
Records snapshot information in the database.

Table 3-55 WSR_SNAPSHOT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_INTEGE Snapshot ID


R

1 DBID BINARY_INTEGE Database ID


R

2 INSTANCE_ID BINARY_INTEGE Instance ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 110


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 STARTUP_TIME TIMESTAMP(3) Database startup time

4 SNAP_TIME TIMESTAMP(3) Snapshot generation time

5 FLUSH_ELAPSE INTERVAL Snapshot generation duration


D DAY(5) TO
SECOND(1)

6 SESSIONS BINARY_INTEGE Number of sessions


R

7 CURSORS BINARY_INTEGE Number of cursors


R

3.1.55 WSR_CONTROL
Records parameters about snapshot generation in the database.

Table 3-56 WSR_CONTROL columns


No. Column Name Data Type Description

0 DBID BINARY_INTEG Database ID


ER

1 SNAP_INTERVAL INTERVAL Snapshot generation interval


DAY(5) TO
SECOND(1)

2 SNAPINT_NUM BINARY_INTEG Snapshot generation interval (unit:


ER second)

3 RETENTION INTERVAL Snapshot retention period


DAY(5) TO
SECOND(1)

4 RETENTION_NU BINARY_INTEG Snapshot retention period (unit:


M ER second)

5 MOST_RECENT_ BINARY_INTEG Latest snapshot ID


SNAP_ID ER

6 MOST_RECENT_ TIMESTAMP(3) Latest snapshot time


SNAP_TIME

7 STATUS VARCHAR(3 Whether the snapshot generation job is


BYTE) enabled (Y/N)

8 MOST_RECENT_ TIMESTAMP(3) Time when expired snapshots were


PURGE_TIME deleted last time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 111


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 TOPNSQL BINARY_INTEG Number of top SQLs in the snapshot


ER

3.1.56 WSR_DBA_SEGMENTS
Records information about ADM_SEGMENTS in snapshots. In standalone scenarios, this
system catalog has data. In distributed scenarios, this system catalog has no data.

Table 3-57 WSR_DBA_SEGMENTS columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_INTEGE Snapshot ID


R

1 OWNER VARCHAR(64 Username


BYTE)

2 SEGMENT_NAME VARCHAR(133 Segment name


BYTE)

3 PARTITION_NAM VARCHAR(145 Partition name


E BYTE)

4 SEGMENT_TYPE CHAR(5 BYTE) Segment type

5 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the
segment

6 BYTES BINARY_BIGINT Segment size

7 PAGES BINARY_BIGINT Number of pages in


a segment

8 EXTENTS BINARY_BIGINT Number of extents


in a segment

3.1.57 WSR_LATCH
Records information about DV_LATCHS in snapshots. In standalone scenarios, this system
catalog has data. In distributed scenarios, this system catalog has no data.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 112


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-58 WSR_LATCH columns


No. Column Data Type Description
Name

0 SNAP_ID BINARY_INTE Snapshot ID


GER

1 ID BINARY_INTE Structure lock ID


GER

2 NAME VARCHAR(64 Structure lock name


BYTE)

3 GETS BINARY_INTE Number of times the latch lock is requested in


GER WAIT mode

4 MISSES BINARY_INTE Number of times the latch is first requested and


GER the requester has to wait

5 SPIN_GETS BINARY_INTE Number of latch requests which miss the first


GER try but succeed while spinning

6 WAIT_TIME BINARY_INTE Wait time for the latch lock (unit: ms)
GER

3.1.58 WSR_LIBRARYCACHE
Records information about WSR_LIBRARYCACHE in snapshots. In standalone scenarios,
this system catalog has data. In distributed scenarios, this system catalog has no data.

Table 3-59 WSR_LIBRARYCACHE columns


No. Column Data Type Description
Name

0 SNAP_ID BINARY_INT Snapshot ID


EGER

1 NAMESP VARCHAR(20 SQL statement type


ACE BYTE)

2 GETS BINARY_BIG Number of times the SQL statement is parsed


INT

3 GETHITS BINARY_BIG Number of times the SQL statement is soft parsed


INT

4 PINS BINARY_BIG Total number of pages used by the SQL statement


INT

5 PINHITS BINARY_BIG Total number of pages used for soft parsing of the
INT SQL statement

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 113


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

6 RELOADS BINARY_BIG Number of times the SQL statement uses pages


INT

7 INVLIDA BINARY_BIG Number of times the SQL statement parsing fails


TIONS INT

3.1.59 WSR_LONGSQL
Records information about DV_LONG_SQL in snapshots. In standalone scenarios, this
system catalog has data. In distributed scenarios, this system catalog has no data.

Table 3-60 WSR_LONGSQL columns


No. Column Data Type Description
Name

0 SNAP_ID BINARY_INT Snapshot ID


EGER

1 CTIME DATE Generation time

2 ELAPSED NUMBER(38, SQL execution time


_TIME 2)

3 SQL_ID VARCHAR(32 SQL ID


BYTE)

4 EXPLAIN VARCHAR(32 Execution plan ID


_ID BYTE)

5 EXPLAIN CLOB Execution plan text


_TEXT

3.1.60 WSR_SEGMENT
Records snapshot information about DV_SEGMENT_STATS In standalone scenarios, this
system catalog has data. In distributed scenarios, this system catalog has no data.

Table 3-61 WSR_SEGMENT columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 BYTE) Object owner

1 OBJECT_NAME VARCHAR(64 BYTE) Object name

2 SUBOBJECT_NAME VARCHAR(64 BYTE) Subobject name, for


example, a partition name

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 114


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 TS# BINARY_INTEGER ID of the tablespace


containing the object

4 OBJECT_TYPE VARCHAR(64 BYTE) Object type, such as a


table or index

5 STATISTIC_NAME VARCHAR(64 BYTE) Statistical type

6 STATISTIC# BINARY_INTEGER Statistical item sequence


number

7 VALUE BINARY_INTEGER Statistical value

3.1.61 WSR_SQL_LIST
A global temporary table, records mappings between SQL_ID and SQL_TEXT saved when
the WSR report is generated. In standalone scenarios, this system catalog has data. In
distributed scenarios, this system catalog has no data.

Table 3-62 WSR_SQL_LIST columns

No. Column Name Data Type Description

0 SQL_ID VARCHAR(100 BYTE) SQL ID

1 SQL_TEXT VARCHAR(8000 BYTE) SQL text

3.1.62 WSR_SQL_LIST_PLAN
A global temporary table, records mappings between SQL_ID and SQL execution plans
saved when the WSR report is generated. In standalone scenarios, this system catalog has
data. In distributed scenarios, this system catalog has no data.

Table 3-63 WSR_SQL_LIST_PLAN columns

No. Column Data Type Description


Name

0 SQL_ID VARCHAR(10 SQL ID


0 BYTE)

1 ELAPSED NUMBER(38, SQL execution time


_TIME 2)

2 EXPLAIN CLOB Execution plan text


_TEXT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 115


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.1.63 WSR_WAITSTAT
Records information about DV_XACT_LOCKS in snapshots. In standalone scenarios, this
system catalog has data. In distributed scenarios, this system catalog has no data.

Table 3-64 WSR_WAITSTAT columns

No. Column Name Data Type Description

0 CLASS VARCHAR(64) Wait event name

1 COUNT BINARY_INTEGER Number of times the wait


event occurs

2 TIME BINARY_INTEGER Total wait time (unit: ms)

3.2 DBA Views


Table 3-65 lists the DBA views supported by GaussDB 100.

Table 3-65 DBA views

View Name Definition

DB_DB_LINKS A reserved function view, with no data.

DB_IND_STATISTICS Displays statistics about partition indexes of all users.

DB_JOBS Displays information about all jobs.

DB_TAB_MODIFICAT Displays table update information.


IONS

DB_USERS Displays information about all users in the database.

DB_USER_SYS_PRIVS Displays system permissions granted to all users in the


database.

ADM_ARGUMENTS Displays the parameters of stored procedures and UDFs that


are available in the database.

ADM_BACKUP_SET Displays the backup set information.

ADM_COL_COMMEN Displays information about comments on the columns of all


TS tables in the database.

ADM_CONSTRAINTS Displays information about constraints on all tables in the


database.

ADM_DATA_FILES Displays the information about all data files in the database.

ADM_DBLINK_TABL Displays information about all tables in the database.


ES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 116


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

ADM_DBLINK_TAB_C Displays information about the columns of all tables in the


OLUMNS database.

ADM_DEPENDENCIE Displays information about dependencies between all objects


S in the system.

ADM_FREE_SPACE Displays the free partitions in all tablespaces in the database.

ADM_HISTOGRAMS Displays information about histograms on all tables in the


database.

ADM_HIST_DBASEG Displays snapshot information about


MENTS ADM_HIST_DBASEGMENTS.

ADM_HIST_LATCH Displays the DV_LATCHS information in historical WSR


snapshots.

ADM_HIST_LIBRARY Displays the DV_LIBRARY_CACHE information in


CACHE historical WSR snapshots.

ADM_HIST_LONGSQ Displays the DV_LONG_SQL information in historical WSR


L snapshots.

ADM_HIST_PARAME Displays parameter values in each snapshot of the database.


TER

ADM_HIST_SEGMEN Displays the DV_SEGMENT_STATS information in


T historical WSR snapshots.

ADM_HIST_SNAPSHO Displays snapshot information in the database.


T

ADM_HIST_SQLARE Displays DML execution information in each snapshot of the


A database.

ADM_HIST_SYSSTAT Displays statistics in each snapshot of the database.

ADM_HIST_SYSTEM Displays OS statistics in each snapshot of the database.

ADM_HIST_SYSTEM_ Displays event information in each snapshot of the database.


EVENT

ADM_HIST_WAITSTA Displays the DV_WAIT_STATS information in historical


T WSR snapshots.

ADM_HIST_WR_CON Displays the parameters of a database snapshot.


TROL

ADM_INDEXES Displays information about indexes on all tables in the


database.

ADM_IND_COLUMNS Displays the indexed columns of all tables in the database.

ADM_IND_PARTITIO Displays information about all partitioned indexes in the


NS database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 117


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

ADM_IND_STATISTIC Displays statistics about partition indexes of all users.


S

ADM_JOBS Displays information about all jobs.

ADM_JOBS_RUNNIN Displays all running job sessions.


G

ADM_OBJECTS Displays information about all objects.

ADM_PART_COL_STA Displays statistics about the columns of all partitioned tables


TISTICS in the database.

ADM_PART_KEY_CO Displays information about the partition columns for all


LUMNS partitioned tables in the database.

ADM_PART_STORE Displays information about the tablespace corresponding to


the STORE clause used for all partitioned tables in the
database.

ADM_PART_TABLES Displays information about all partitioned tables in the


database.

ADM_PROCEDURES Displays information about all stored procedures, functions,


and triggers in the database.

ADM_PROFILES Displays all profiles in the database.

ADM_ROLES Displays information about all roles in the database.

ADM_ROLE_PRIVS Displays the permissions of all users in the database.

ADM_SEGMENTS Displays information about the storage allocated for all tables,
indexes, and LOBs in the database.

ADM_SEQUENCES Displays information about all sequences in the database.

ADM_SOURCE Displays information about all user-defined objects in the


database.

ADM_SYNONYMS Displays information about all synonyms in the database.

ADM_SYS_PRIVS Displays system permissions granted to all users in the


database.

ADM_TABLES Displays information about all tables in the database.

ADM_TABLESPACES Displays information about all tablespaces in the database.

ADM_TAB_COLS Displays information about the columns of all tables in the


database.

ADM_TAB_COLUMNS Displays information about the columns of all tables and


views in the database.

ADM_TAB_COL_STAT Displays statistics about the columns of all tables in the


ISTICS database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 118


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

ADM_TAB_COMMEN Displays information about comments on all tables in the


TS database.

ADM_TAB_DISTRIBU Displays the table distribution information of all users.


TE

ADM_TAB_MODIFIC Displays modifications to all tables in the database, which


ATIONS include insert, delete, and update operations.

ADM_TAB_PARTITIO Displays information about partitions in all tables in the


NS database.

ADM_TAB_PRIVS Displays all user object permissions in the database.

ADM_TAB_STATISTIC Displays statistics about all tables in the database.


S

ADM_TRIGGERS Displays information about all triggers in the database.

ADM_USERS Displays information about all users in the database.

ADM_VIEWS Displays information about all views in the database.

ADM_VIEW_COLUM Displays information about the columns of all views in the


NS database.

3.2.1 DB_DB_LINKS
A reserved function view, with no data.

Table 3-66 DB_DB_LINKS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) database connection

1 DB_LINK VARCHAR(128 Name of the


BYTE) database connection

2 USERNAME VARCHAR(64 Name of the user for


BYTE) logging in

3 HOST VARCHAR(2000 IP address of the


BYTE) database

4 CREATED DATE Creation time of the


database connection

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 119


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.2 DB_IND_STATISTICS
Displays statistics about partition indexes of all users.

Table 3-67 DB_IND_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 TABLE_OWNER VARCHAR(64 Owner of the


BYTE) indexed table

3 TABLE_NAME VARCHAR(64 Name of the indexed


BYTE) table

4 PARTITION_NAM VARCHAR(64 Name of the index


E BYTE) partition

5 PARTITION_POSIT NUMBER Position of the index


ION partition, starting
from 1

6 OBJECT_TYPE CHAR(9 BYTE) Type of the object


corresponding to the
index. Values are
INDEX and
PARTITION.

7 BLEVELS BINARY_INTEGE Index tree level


R

8 LEAF_BLOCKS BINARY_INTEGE Number of leaf


R blocks

9 DISTINCT_KEYS BINARY_INTEGE Number of distinct


R keys

10 AVG_LEAF_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY leaf nodes for each
key

11 AVG_DATA_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY data blocks for each
key

12 CLUSTERING_FA NUMBER Compatibility


CTOR column, with no
value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 120


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

13 NUM_ROWS BINARY_INTEGE Number of rows


R returned when the
index partition was
analyzed last time

14 SAMPLE_SIZE BINARY_INTEGE Number of pages


R sampled when the
index partition was
analyzed last time

15 LAST_ANALYZED TIMESTAMP(6) Time point when the


index partition was
analyzed last time

3.2.3 DB_JOBS
Displays information about all jobs.

Table 3-68 DB_JOBS columns


No. Column Name Data Type Description

0 JOB BINARY_BIGINT Job ID

1 LOG_USER VARCHAR(64 User who submits


BYTE) the job

2 PRIV_USER VARCHAR(64 User granted with


BYTE) the job permission

3 SCHEMA_USER VARCHAR(64 User who performs


BYTE) syntax analysis on
the job

4 LAST_DATE DATE Time when the job


was successfully
executed last time

5 LAST_SEC VARCHAR(48 Timestamp of the


BYTE) last successful job
(including the hour,
minute, and second
information)

6 THIS_DATE DATE Time when the


running job was
started

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 121


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

7 THIS_SEC VARCHAR(48 Timestamp of the


BYTE) running job start
(including the hour,
minute, and second
information)

8 NEXT_DATE DATE Time when the


scheduled job will
be executed next
time

9 NEXT_SEC VARCHAR(48) Time when the


scheduled job will
be executed next
time
(including the hour,
minute, and second
information)

10 BROKEN CHAR(1 BYTE) Status (blocked or


not)

11 INTERVAL_TIME VARCHAR(200 Expression for


BYTE) calculating the next
time for job running

12 FAILURES BINARY_INTEGE Number of times the


R job consecutively
fails

13 WHAT VARCHAR(4000 PL/SQL block to be


BYTE) executed in the job

14 CREATE_DATE DATE Job creation time

3.2.4 DB_TAB_MODIFICATIONS
Displays table update information.

Table 3-69 DB_TAB_MODIFICATIONS columns

No. Column Name Data Type Description

0 TABLE_OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 122


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 SUBPARTITION_N VARCHAR(64 Subpartition name


AME BYTE)

4 INSERTS BINARY_INTEGE Number of inserted


R rows. It will be
cleared after the
ANALYZE
operation.

5 UPDATES BINARY_INTEGE Number of updated


R rows. It will be
cleared after the
ANALYZE
operation.

6 DELETES BINARY_INTEGE Number of deleted


R rows. It will be
cleared after the
ANALYZE
operation.

7 TIMESTAMP TIMESTAMP(6) Timestamp of row


modification last
time

8 DROP_SEGMENT BINARY_INTEGE Number of segments


S R dropped since the
last analysis
operation

1. When STATISTICS_LEVEL, statistics collection level, is set to BASIC, table


modification information is not collected.
2. The table modification information is not synchronized in this view in real time.
According to system settings, there is at least a 15-minute delay before the
synchronization.

3.2.5 DB_USERS
Displays information about all users in the database.

Table 3-70 DB_USERS columns

No. Column Name Data Type Description

0 USER_ID BINARY_INTEGE User ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 123


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 USERNAME VARCHAR(64 Username


BYTE)

2 CREATED DATE Time when the user


is created

3 CRYPTOPERIOD INTERVAL DAY(7) Password expiration


TO SECOND(6) interval

3.2.6 DB_USER_SYS_PRIVS
Displays system permissions granted to all users in the database.

Table 3-71 DB_USER_SYS_PRIVS columns

No. Column Name Data Type Description

0 USERNAME VARCHAR(64 Username


BYTE)

1 PRIVILEGE CHAR(28 BYTE) Permission

2 ADMIN_OPTION CHAR(3 BYTE) Whether the user has


the permission
(YES/NO)

3.2.7 ADM_ARGUMENTS
Displays the parameters of stored procedures and UDFs that are available in the database.

Table 3-72 ADM_ARGUMENTS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 BYTE) Object owner

1 OBJECT_NAME VARCHAR(128 BYTE) Object name

2 ARGUMENT_NA VARCHAR(128 BYTE) Parameter name


ME

3 POSITION BINARY_INTEGER Position of all parameters at


the same DATA_LEVEL,
starting from 0

4 SEQUENCE BINARY_INTEGER Sequence of all parameters for


the same object, starting from
1

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 124


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 DATA_LEVEL BINARY_INTEGER Level of the parameter,


supporting only 0 currently

6 DATA_TYPE VARCHAR(64 BYTE) Data type of the parameter

7 DEFAULTED CHAR(1 BYTE) Whether the parameter has a


default value

8 IN_OUT CHAR(6 BYTE) Direction of the parameter.


IN: input parameter; OUT:
output parameter; IN OUT:
both input and output
parameters

9 DATA_LENGTH BINARY_INTEGER Data length

10 DATA_PRECISION BINARY_INTEGER Data precision, valid for


numbers

11 DATA_SCALE BINARY_INTEGER Data scale, valid for numbers

3.2.8 ADM_BACKUP_SET
Displays the backup set information.

Table 3-73 ADM_BACKUP_SET columns


No. Column Name Data Type Description

0 BACKUP_TYPE CHAR(7 BYTE) Backup type


FULL: full backup
INCR: incremental backup

1 STAGE CHAR(7 BYTE) Backup phase


DATA: Only data has been
backed up.
LOG: Both data and logs
have been backed up.

2 STATUS CHAR(7 BYTE) Backup set status


SUCCESS: Backup succeeds.
DOING: Backup is ongoing.
FAILED: Backup fails.

3 INCREMENTAL_L BINARY_INTEGER Incremental backup level


EVEL

4 TAG VARCHAR(64 BYTE) Backup set tag

5 SCN BINARY_BIGINT Backup set SCN value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 125


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 DEVICE_TYPE CHAR(6 BYTE) Backup media type


DISK: backup to disk
NBU: backup to NBU

7 DIR VARCHAR(256 BYTE) Backup set directory

8 START_TIME TIMESTAMP(6) Backup start time

9 BASE_TAG VARCHAR(64 BYTE) Base backup tag

3.2.9 ADM_COL_COMMENTS
Displays information about comments on the columns of all tables in the database.

Table 3-74 ADM_COL_COMMENTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the column


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(128 Column name


BYTE)

3 COMMENTS VARCHAR(4000 Column comment


BYTE)

3.2.10 ADM_CONSTRAINTS
Displays information about constraints on all tables in the database.

Table 3-75 ADM_CONSTRAINTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Constraint owner


BYTE)

1 CONSTRAINT_NA VARCHAR(64 Constraint name


ME BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 126


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 CONSTRAINT_TY CHAR(1 BYTE) Constraint type.


PE Values are:
P: primary key
constraint
C: check constraint
R: foreign key
constraint
U: unique key
constraint
This view displays
nothing for the NOT
NULL constraint.

3 TABLE_NAME VARCHAR(64 Name of the table on


BYTE) which the constraint
is defined

4 SEARCH_CONDIT VARCHAR(2048 Text of the search


ION BYTE) condition for a
check constraint. For
other constraints, the
value is NULL.

5 R_OWNER VARCHAR(64 Owner of the


BYTE) primary or unique
key constraint
created on the
referenced column if
CONSTRAINT_T
YPE is R

6 R_TABLE_NAME VARCHAR(64 Name of the


BYTE) referenced table if
CONSTRAINT_T
YPE is R

7 R_CONSTRAINT_ VARCHAR(64 Name of the primary


NAME BYTE) or unique key
constraint created on
the referenced
column if
CONSTRAINT_T
YPE is R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 127


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 DELETE_RULE CHAR(14 BYTE) Rule for processing


associated data in a
child table when the
data of the parent
table corresponding
to the foreign key
constraint is deleted.
Currently, only
NOT ALLOWED
is supported.

9 STATUS CHAR(8 BYTE) Enforcement status


of the constraint
Values are:
ENABLED
DISABLED

10 DEFERRABLE CHAR(14 BYTE) Whether the


constraint is
deferrable. This is a
compatibility
column, with the
only value NOT
DEFERRABLE.

11 DEFERRED CHAR(9 BYTE) Compatibility


column, with the
only value
IMMEDIATE

12 VALIDATED CHAR(13 BYTE) Compatibility


column, with the
only value
VALIDATED

13 BAD CHAR Compatibility


column, with no
value

14 RELY CHAR Compatibility


column, with no
value

15 INDEX_OWNER VARCHAR(64 Owner of the index


BYTE) (only shown for
primary and unique
key constraints)

16 INDEX_NAME VARCHAR(64 Name of the index


BYTE) (only shown for
primary and unique
key constraints)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 128


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

17 INVALID CHAR(5 BYTE) Compatibility


column, with the
only value FALSE

18 VIEW_RELATED CHAR Compatibility


column, with no
value

19 CONS_COLS VARCHAR(1088 Column on which a


BYTE) constraint is created

20 REF_COLS VARCHAR(1088 Name of the parent


BYTE) table column
referenced by a
foreign key
constraint

21 SYS_GENERATE CHAR(1 BYTE) Whether the


constraint name is
generated by the
system. Values are:
Y
N

22 IS_DUPLICATE CHAR(1 BYTE) Whether the


constraint name has
a duplicate. Values
are:
Y
N

3.2.11 ADM_DATA_FILES
Displays the information about all data files in the database.

Table 3-76 ADM_DATA_FILES columns

No. Column Name Data Type Description

0 FILE_NAME VARCHA Name of the database file


R(256
BYTE)

1 FILE_ID BINARY_I File ID


NTEGER

2 TABLESPACE_N VARCHA Name of the tablespace to which the file


AME R(64 belongs
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 129


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 BYTES BINARY_B Size of the file in bytes


IGINT

4 BLOCKS BINARY_B Number of blocks occupied by the file


IGINT

5 STATUS CHAR(5 File status (VALID/INVALID)


BYTE)

6 RELATIVE_FNO BINARY_I Relative file ID. This column is a


NTEGER compatibility column and an equivalent to
FILE_ID.

7 AUTOEXTENSIB CHAR(3 Whether to perform automatic extension after


LE BYTE) the file is full (YES/NO)

8 MAXBYTES BINARY_B Maximum file size in bytes after automatic


IGINT extension is enabled. If
AUTOEXTENSIBLE is set to NO, the value
of this column will be 0.

9 MAXBLOCKS BINARY_B Maximum file size in blocks after automatic


IGINT extension is enabled. If
AUTOEXTENSIBLE is set to NO, the value
of this column will be 0.

10 INCREMENT_BY BINARY_B Number of bytes used as the increment for


IGINT automatic extension

11 USER_BYTES BINARY_B The size of the file available for user data, in
IGINT bytes

12 USER_BLOCKS BINARY_B The size of the file available for user data, in
IGINT blocks

13 ONLINE_STATUS VARCHA Whether the file is online (ONLINE/


R(20 OFFLINE)
BYTE)

3.2.12 ADM_DBLINK_TABLES
Displays information about all tables in the database.

Table 3-77 ADM_DBLINK_TABLES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 130


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 OWNER_ID BINARY_INTEGE User ID


R

3 TABLE_ID BINARY_INTEGE Table ID


R

4 COLUMN_COUNT BINARY_INTEGE Number of columns


R in the table

5 INDEX_COUNT BINARY_INTEGE Number of indexes


R on the table

3.2.13 ADM_DBLINK_TAB_COLUMNS
Displays information about the columns of all tables in the database.

Table 3-78 ADM_DBLINK_TAB_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 DATA_TYPE BINARY_INTEGE Column data type


R

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE BINARY_INTEGE Whether the column


R allows for NULL

8 COLUMN_ID BINARY_INTEGE Column ID


R

3.2.14 ADM_DEPENDENCIES
Displays information about dependencies between all objects in the system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 131


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-79 ADM_DEPENDENCIES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

1 NAME VARCHAR(64 Object name


BYTE)

2 TYPE CHAR(12 BYTE) Object type

3 REFERENCED_O VARCHAR(64 Owner of the


WNER BYTE) referenced object

4 REFERENCED_NA VARCHAR(64 Name of the


ME BYTE) referenced object

5 REFERENCED_TY CHAR(12 BYTE) Type of the


PE referenced object

3.2.15 ADM_FREE_SPACE
Displays the free partitions in all tablespaces in the database.
When you create a tablespace, querying the ADM_FREE_SPACE view may display free
tablespaces with the same size. If you create a table without inserting records in any of the
tablespaces, querying the ADM_FREE_SPACE view shows that the sizes of the free
tablespaces remain unchanged.

Table 3-80 ADM_FREE_SPACE columns


No. Column Name Data Type Description

0 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

1 FILE_ID BINARY_INTEGE File ID


R

2 BLOCK_ID BINARY_INTEGE ID of the start block


R in the free extent

3 BYTES BINARY_BIGINT Size of the free


extent (unit: byte)

4 BLOCKS BINARY_BIGINT Size of the free


extent (unit: block)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 132


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 RELATIVE_FNO BINARY_INTEGE Relative file ID.


R This column is a
compatibility
column and an
equivalent to
FILE_ID.

3.2.16 ADM_HISTOGRAMS
Displays information about histograms on all tables in the database.

Table 3-81 ADM_HISTOGRAMS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 ENDPOINT_NUM BINARY_INTEGE Bucket number


BER R corresponding to a
column after data
distribution, starting
from 1

4 ENDPOINT_VALU BINARY_INTEGE Total number of


E R rows with a value
less than the
corresponding
column value

5 ENDPOINT_ACTU VARCHAR(4000 Column value


AL_VALUE BYTE) measured after data
distribution

3.2.17 ADM_HIST_DBASEGMENTS
Displays snapshot information about ADM_HIST_DBASEGMENTS.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 133


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-82 ADM_HIST_DBASEGMENTS columns

No. Column Name Data Type Description

0 SNAP_ID BINARY_INTEGE Snapshot ID


R

1 OWNER VARCHAR(64 Username


BYTE)

2 SEGMENT_NAME VARCHAR(133 Segment name


BYTE)

3 PARTITION_NAM VARCHAR(145 Partition name


E BYTE)

4 SEGMENT_TYPE CHAR(5 BYTE) Segment type

5 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the
segment

6 BYTES BINARY_BIGINT Segment size

7 PAGES BINARY_BIGINT Number of pages in


a segment

8 EXTENTS BINARY_BIGINT Number of extents


in a segment

3.2.18 ADM_HIST_LATCH
Displays the DV_LATCHS information in historical WSR snapshots.

Table 3-83 ADM_HIST_LATCH columns

No. Column Data Type Description


Name

0 SNAP_ID BINARY_INTE Snapshot ID


GER

1 ID BINARY_INTE Structure lock ID


GER

2 NAME VARCHAR(64 Structure lock name


BYTE)

3 GETS BINARY_INTE Number of times the latch lock is requested in


GER WAIT mode

4 MISSES BINARY_INTE Number of times the latch is first requested and


GER the requester has to wait

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 134


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

5 SPIN_GETS BINARY_INTE Number of latch requests which miss the first


GER try but succeed while spinning

6 WAIT_TIME BINARY_INTE Time spent on waiting for the latch lock


GER

3.2.19 ADM_HIST_LIBRARYCACHE
Displays the DV_LIBRARY_CACHE information in historical WSR snapshots.

Table 3-84 ADM_HIST_LIBRARYCACHE columns


No. Column Data Type Description
Name

0 SNAP_ID BINARY_INTE Snapshot ID


GER

1 NAMESPAC VARCHAR(20 Type of a buffered operation


E BYTE)

2 GETS BINARY_BIGI Number of times a lock is requested for objects


NT

3 GETHITS BINARY_BIGI Number of times an object's handle is found in


NT memory

4 PINS BINARY_BIGI Number of times PIN is requested for objects


NT

5 PINHITS BINARY_BIGI Number of times the library object is found in


NT memory

6 RELOADS BINARY_BIGI Number of times an object is pinned from disk


NT to memory after the object handle is created

7 INVLIDATI BINARY_BIGI Number of times an object is marked invalid


ONS NT

3.2.20 ADM_HIST_LONGSQL
Displays the DV_LONG_SQL information in historical WSR snapshots.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 135


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-85 ADM_HIST_LONGSQL columns


No. Column Name Data Description
Type

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 CTIME DATE Generation time

2 ELAPSED_TIME NUMBER( SQL execution time


38, 2)

3 SQL_ID VARCHA SQL ID


R(32
BYTE)

4 EXPLAIN_TEXT CLOB Execution plan text

3.2.21 ADM_HIST_PARAMETER
Displays parameter values in each snapshot of the database.

Table 3-86 ADM_HIST_PARAMETER columns


No. Column Name Data Type Description

0 SNAP_ID INTEGER Snapshot ID

1 NAME VARCHA Parameter name


R(64
BYTE)

2 VALUE VARCHA Parameter value


R(2048
BYTE)

3 DEFAULT_VALU VARCHA Default parameter value


E R(2048
BYTE)

4 ISDEFAULT VARCHA Whether the parameter is set to its default


R(20 value (TRUE/FALSE)
BYTE)

5 MODIFIABLE VARCHA Whether the parameter can be modified


R(20 (TRUE/FALSE)
BYTE)

6 DESCRIPITION VARCHA Parameter description


R(2048
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 136


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

7 DATATYPE VARCHA Value range


R(2048
BYTE)

8 EFFECTIVE VARCHA Effective mode


R(20
BYTE)

3.2.22 ADM_HIST_SEGMENT
Displays the DV_SEGMENT_STATS information in historical WSR snapshots.

Table 3-87 ADM_HIST_SEGMENT columns

No. Column Name Data Type Description

0 SNAP_ID BINARY_INTEGER Snapshot ID

1 OWNER VARCHAR(64 BYTE) Object owner

2 OBJECT_NAME VARCHAR(64 BYTE) Object name

3 SUBOBJECT_NAME VARCHAR(64 BYTE) Subobject name, for


example, a partition name

4 TS# BINARY_INTEGER ID of the tablespace


containing the object

5 OBJECT_TYPE VARCHAR(64 BYTE) Object type, such as a


table or index

6 STATISTIC_NAME VARCHAR(64 BYTE) Statistical type

7 STATISTIC# BINARY_INTEGER Statistical item sequence


number

8 VALUE BINARY_INTEGER Statistical value

3.2.23 ADM_HIST_SNAPSHOT
Displays snapshot information in the database.

Table 3-88 ADM_HIST_SNAPSHOT columns

No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 137


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 DBID BINARY_I Database ID


NTEGER

2 INSTANCE_ID BINARY_I Instance ID


NTEGER

3 STARTUP_TIME TIMESTA Database startup time


MP(3)

4 SNAP_TIME TIMESTA Snapshot generation time


MP(3)

5 FLUSH_ELAPSE INTERVAL Snapshot generation duration


D DAY(5) TO
SECOND(1
)

6 SESSIONS BINARY_I Number of sessions


NTEGER

7 CURSORS BINARY_I Number of cursors


NTEGER

3.2.24 ADM_HIST_SQLAREA
Displays DML execution information in each snapshot of the database.

Table 3-89 ADM_HIST_SQLAREA columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 SQL_ID VARCHA SQL statement ID


R(10
BYTE)

2 SQL_TEXT VARCHA SQL statement content


R(8000
BYTE)

3 MODULE VARCHA SQL statement channel


R(64
BYTE)

4 EXECUTIONS BINARY_ Number of times the SQL statement is


BIGINT executed

5 DISK_READS BINARY_ Number of times the SQL statement is read


BIGINT from the disk

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 138


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 BUFFER_GETS BINARY_ Number of times the SQL statement is read


BIGINT from the buffer

7 SORTS BINARY_ Number of times the sort operation is


BIGINT performed for the SQL statement

8 PARSE_CALLS BINARY_ Number of times the SQL statement is parsed


BIGINT

9 PROCESSED_RO BINARY_ Number of rows pre-fetched by the SQL


WS BIGINT statement

10 IO_WAIT_TIME BINARY_ I/O wait time of the SQL statement (unit: μs)
BIGINT

11 CON_WAIT_TIM BINARY_ Lock wait time of the SQL statement (unit: μs)
E BIGINT

12 CPU_TIME BINARY_ CPU time of the SQL statement (unit: μs)


BIGINT

13 ELAPSED_TIME BINARY_ Total duration of the SQL statement (unit: μs)


BIGINT

14 REF_COUNT BINARY_ Number of times the SQL statement is


BIGINT referenced

15 IS_FREE BOOLEAN Released or not

16 CLEANED BOOLEAN Deleted or not

17 CR_GETS BINARY_ Number of times an SQL statement searches


BIGINT in the CR pool in concurrent transaction
scenarios

18 PARSE_TIME BINARY_ Total time of SQL parsing (unit: microsecond)


BIGINT

19 PARSING_USER_ VARCHA Name of the user that performs a hard parse


NAME R(64) operation on the SQL statement for the first
time

20 PROGRAM_ID BINARY_ If the SQL statement is parsed for the first


BIGINT time in a stored procedure, UDF, or trigger,
this column will display the corresponding
OID. Otherwise, it will display only 0.

21 PROGRAM_LINE BINARY_I If the SQL statement is parsed for the first


# NTEGER time in a stored procedure, UDF, or trigger,
this column will display the corresponding
row number of the SQL statement. Otherwise,
it will display only 0.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 139


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.25 ADM_HIST_SYSSTAT
Displays statistics in each snapshot of the database.

Table 3-90 ADM_HIST_SYSSTAT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 STAT_ID BINARY_I Statistical item ID


NTEGER

2 STAT_NAME VARCHA Statistical item name


R(64
BYTE)

3 VALUE BINARY_B Statistical item value


IGINT

3.2.26 ADM_HIST_SYSTEM
Displays OS statistics in each snapshot of the database.

Table 3-91 ADM_HIST_SYSTEM columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 STAT_ID BINARY_I Statistical item ID


NTEGER

2 STAT_NAME VARCHA Statistical item name


R(64
BYTE)

3 VALUE VARCHA Statistical item value


R(128
BYTE)

3.2.27 ADM_HIST_SYSTEM_EVENT
Displays event information in each snapshot of the database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 140


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-92 ADM_HIST_SYSTEM_EVENT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_I Snapshot ID


NTEGER

1 EVENT# BINARY_I Event ID


NTEGER

2 EVENT VARCHA Event information


R(64
BYTE)

3 WAIT_CLASS VARCHA Wait event class


R(64)

4 TOTAL_WAITS VARCHA Total number of wait events


R(64
BYTE)

5 TIME_WAITED BINARY_B Time of the wait event (unit: μs)


IGINT

6 TIME_WAITED_ BINARY_B Time of the wait event (unit: ms)


MICRO IGINT

7 AVERAGE_WAIT BINARY_D Average time of wait events (unit: μs)


OUBLE

8 AVERAGE_WAIT BINARY_B Average time of wait events (unit: ms)


_MICRO IGINT

3.2.28 ADM_HIST_WAITSTAT
Displays the DV_WAIT_STATS information in historical WSR snapshots.

Table 3-93 ADM_HIST_WAITSTAT columns


No. Column Name Data Type Description

0 SNAP_ID BINARY_INTEGER Snapshot ID

1 CLASS VARCHAR(64 BYTE) Wait event name

2 COUNT BINARY_INTEGER Number of times the wait


event occurs

3 TIME BINARY_INTEGER Sum of wait time

3.2.29 ADM_HIST_WR_CONTROL
Displays the parameters of a database snapshot.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 141


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-94 ADM_HIST_WR_CONTROL columns


No. Column Name Data Type Description

0 DBID BINARY_I Database ID


NTEGER

1 SNAP_INTERVAL INTERVAL Snapshot generation interval


DAY(5) TO
SECOND(1
)

2 RETENTION INTERVAL Retention setting for the snapshot


DAY(5) TO
SECOND(1
)

3 TOPNSQL BINARY_I Number of top SQLs in the snapshot


NTEGER

4 STATUS VARCHA Whether the snapshot generation job is


R(3 BYTE) enabled. Values are:
Y
N

3.2.30 ADM_INDEXES
Displays information about indexes on all tables in the database.

Table 3-95 ADM_INDEXES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 INDEX_TYPE CHAR(6 BYTE) Index type, NORMAL by


default

3 TABLE_NAME VARCHAR(64 Table name


BYTE)

4 TABLESPACE_NAM VARCHAR(64 Tablespace name


E BYTE)

5 IS_PRIMARY CHAR(1 BYTE) Whether the index


enforces a primary key
constraint

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 142


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 IS_UNIQUE CHAR(1 BYTE) Whether the index


enforces a unique key
constraint

7 IS_DUPLICATE CHAR(1 BYTE) Whether the index name


has a duplicate. Values
are:
l Y
l N

8 PARTITIONED CHAR(1 BYTE) Partitioned or not

9 STATUS CHAR(7 BYTE) Index status


VALID
INVALID

10 INI_TRANS BINARY_INTEGER Initial number of


transactions

11 MAX_TRANS BINARY_INTEGER Maximum number of


transactions

12 PCT_FREE BINARY_INTEGER PCT FREE

13 COLUMN_COUNT BINARY_INTEGER Number of columns

14 COLUMNS VARCHAR(1088BY Linked list of columns


TE)

15 BYTES BINARY_BIGINT Index size

16 PAGES BINARY_BIGINT Number of pages


occupied by the index

17 EXTENTS BINARY_BIGINT Number of extents


occupied by the index

18 BLEVEL BINARY_INTEGER Index tree level

19 LEAF_BLOCKS BINARY_INTEGER Number of leaf node


pages

20 EMPTY_LEAF_BLO BINARY_INTEGER Number of leaf blocks


CKS

21 DISTINCT_KEYS BINARY_INTEGER Number of distinct keys

22 AVG_LEAF_BLOCK BINARY_DOUBLE Average number of leaf


S_PER_KEY nodes for each key

23 AVG_DATA_BLOCK BINARY_DOUBLE Average number of data


S_PER_KEY blocks for each key

24 CLUSTERING_FAC NUMBER Compatibility column,


TOR with no value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 143


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

25 NUM_ROWS BINARY_INTEGER Number of data rows in


the indexed table
measured last time

26 SAMPLE_SIZE BINARY_INTEGER Number of sample rows in


the indexed table
measured last time

27 LAST_ANALYZED TIMESTAMP(6) Time point when the


indexed table was
analyzed last time

28 SYS_GENERATE BINARY_BIGINT Whether the constraint


name is generated by the
system. Values are Y and
N.

29 CR_MODE CHAR(4 BYTE) Table/Index MVCC


mechanism
l ROW: row-level
MVCC
l PAGE: page-level
MVCC

3.2.31 ADM_IND_COLUMNS
Displays the indexed columns of all tables in the database.

Table 3-96 ADM_IND_COLUMNS columns


No. Column Name Data Type Description

0 INDEX_OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 TABLE_OWNER VARCHAR(64 Table owner


BYTE)

3 TABLE_NAME VARCHAR(64 Table name


BYTE)

4 COLUMN_NAME VARCHAR(64 Column name


BYTE)

5 COLUMN_POSITI BINARY_INTEGE Column position


ON R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 144


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 COLUMN_LENGT BINARY_INTEGE Column length


H R

3.2.32 ADM_IND_PARTITIONS
Displays information about all partitioned indexes in the database.

Table 3-97 ADM_IND_PARTITIONS columns


No. Column Name Data Type Description

0 INDEX_OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 COMPOSITE CHAR(2 BYTE) Whether the


partition within the
index is a composite
partition. Values are
YES and NO.

3 PARTITION_NAM VARCHAR(64 Name of the


E BYTE) partition within the
index

4 PARTITION_POSIT BINARY_INTEGE Subscript of the


ION R partition within the
index, starting from
1

5 STATUS CHAR(6 BYTE) Index status

6 PCT_FREE BINARY_INTEGE Percentage of


R minimum reserved
space for future
update operations on
a page

7 INI_TRANS BINARY_INTEGE Number of ITL


R entries initially
allocated to a page

8 MAX_TRANS BINARY_INTEGE Maximum number


R of ITL entries on a
page

9 BLEVEL BINARY_INTEGE Index tree level


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 145


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

10 LEAF_BLOCKS BINARY_INTEGE Number of leaf node


R pages

11 DISTINCT_KEYS BINARY_INTEGE Number of distinct


R keys

12 AVG_LEAF_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY leaf nodes for each
key

13 AVG_DATA_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY data blocks for each
key

14 CLUSTERING_FA NUMBER Compatibility


CTOR column, with no
value

15 NUM_ROWS BINARY_INTEGE Number of rows


R returned when the
partition was
analyzed last time

16 SAMPLE_SIZE BINARY_INTEGE Number of pages


R sampled when the
partition was
analyzed last time

17 LAST_ANALYZED DATE Time point when the


partition was
analyzed last time

3.2.33 ADM_IND_STATISTICS
Displays statistics about partition indexes of all users.

Table 3-98 ADM_IND_STATISTICS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 TABLE_OWNER VARCHAR(64 Owner of the


BYTE) indexed table

3 TABLE_NAME VARCHAR(64 Name of the indexed


BYTE) table

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 146


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 PARTITION_NAM VARCHAR(64 Name of the index


E BYTE) partition

5 PARTITION_POSIT NUMBER Position of the index


ION partition, starting
from 1

6 OBJECT_TYPE CHAR(9 BYTE) Type of the object


corresponding to the
index. Values are
INDEX and
PARTITION.

7 BLEVELS BINARY_INTEGE Index tree level


R

8 LEAF_BLOCKS BINARY_INTEGE Number of leaf node


R pages

9 DISTINCT_KEYS BINARY_INTEGE Number of distinct


R keys

10 AVG_LEAF_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY leaf nodes for each
key

11 AVG_DATA_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY data blocks for each
key

12 CLUSTERING_FA NUMBER Compatibility


CTOR column, with no
value

13 NUM_ROWS BINARY_INTEGE Number of rows


R returned when the
index partition was
analyzed last time

14 SAMPLE_SIZE BINARY_INTEGE Number of pages


R sampled when the
index partition was
analyzed last time

15 LAST_ANALYZED TIMESTAMP(6) Time point when the


index partition was
analyzed last time

3.2.34 ADM_JOBS
Displays information about all jobs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 147


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-99 ADM_JOBS columns


No. Column Name Data Type Description

0 JOB BINARY_BIGINT Job ID

1 LOG_USER VARCHAR(64 User who submits


BYTE) the job

2 PRIV_USER VARCHAR(64 User granted with


BYTE) the job permission

3 SCHEMA_USER VARCHAR(64 User who performs


BYTE) syntax analysis on
the job

4 LAST_DATE DATE Time when the job


was successfully
executed last time

5 LAST_SEC VARCHAR(48 Timestamp of the


BYTE) last successful job
(including the hour,
minute, and second
information)

6 THIS_DATE DATE Time when the


running job was
started

7 THIS_SEC VARCHAR(48 Timestamp of the


BYTE) running job start
(including the hour,
minute, and second
information)

8 NEXT_DATE DATE Time when the


scheduled job will
be executed next
time

9 NEXT_SEC VARCHAR(48 Time when the


BYTE) scheduled job will
be executed next
time
(including the hour,
minute, and second
information)

10 BROKEN CHAR(1 BYTE) Status (blocked or


not)

11 INTERVAL_TIME VARCHAR(200 Expression for


BYTE) calculating the next
time for job running

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 148


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

12 FAILURES BINARY_INTEGE Number of times the


R job consecutively
fails

13 WHAT VARCHAR(4000 PL/SQL block to be


BYTE) executed in the job

14 CREATE_DATE DATE Job creation time

3.2.35 ADM_JOBS_RUNNING
Displays all running job sessions.

Table 3-100 ADM_JOBS_RUNNING columns


No. Column Name Data Type Description

0 JOB BINARY_BIGINT Job ID

1 SID BINARY_INTEGE Session ID


R

2 SERIAL# BINARY_INTEGE Session sequence


R number, used to
uniquely identify a
session object

3 FAILURES BINARY_INTEGE Number of times the


R job consecutively
fails

4 LAST_DATE DATE Time when the job


was successfully
executed last time

5 LAST_SEC VARCHAR(48 Timestamp of the


BYTE) last successful job
(including the hour,
minute, and second
information)

6 THIS_DATE DATE Time when the


running job was
started

7 THIS_SEC VARCHAR(48 Timestamp of the


BYTE) running job start
(including the hour,
minute, and second
information)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 149


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.36 ADM_OBJECTS
Displays information about all objects.

Table 3-101 ADM_OBJECTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

1 OBJECT_NAME VARCHAR(128 Object name


BYTE)

2 SUBOBJECT_NAME VARCHAR(64 Sub-object name


BYTE)

3 OBJECT_ID BINARY_BIGINT Object ID

4 OBJECT_TYPE CHAR(15 BYTE) Object type. Values


are:
l SYNONYM
l SEQUENCE
l PROCEDURE
l FUNCTION
l DYNAMIC
VIEW
l VIEW
l INDEX
l RECYCLED
INDEX
l TABLE
l RECYCLED
TABLE
l TRIGGER

5 CREATED DATE Object creation time

6 LAST_DDL_TIME DATE Time of the last DC


update on the object

7 STATUS CHAR(7 BYTE) Object status,


VALID by default

8 TEMPORARY VARCHAR(1 Whether an object is


BYTE) temporary. Its values
are Y (yes) and N
(no).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 150


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.37 ADM_PART_COL_STATISTICS
Displays statistics about the columns of all partitioned tables in the database.

Table 3-102 ADM_PART_COL_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

3 COLUMN_NAME VARCHAR(64 Column name


BYTE)

4 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

5 LOW_VALUE VARCHAR(4000 Minimum value in


BYTE) the column

6 HIGH_VALUE VARCHAR(4000 Maximum value in


BYTE) the column

7 DENSITY BINARY_DOUBLE Density of the


column

8 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

9 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

10 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

11 LAST_ANALYZED DATE Time when statistics


were collected last
time

12 AVG_COL_LEN NUMBER Compatibility


column, with no
value

13 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 151


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.38 ADM_PART_KEY_COLUMNS
Displays information about the partition columns for all partitioned tables in the database.

Table 3-103 ADM_PART_KEY_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) partitioned table

1 NAME VARCHAR(64 Table name


BYTE)

2 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

3 COLUMN_NAME VARCHAR(64 Column name


BYTE)

4 COLUMN_POSITI BINARY_BIGINT Position of the


ON column within the
partition key

3.2.39 ADM_PART_STORE
Displays information about the tablespace corresponding to the STORE clause used for all
partitioned tables in the database.

Table 3-104 ADM_PART_STORE columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 NAME VARCHAR(64 Object name


BYTE)

2 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

3 POSITION BINARY_INTEGE Tablespace position


R

4 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

3.2.40 ADM_PART_TABLES
Displays information about all partitioned tables in the database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 152


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-105 ADM_PART_TABLES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) partitioned table

1 TABLE_NAME VARCHAR(64 Name of the


BYTE) partitioned table

2 PARTITIONING_T CHAR(7 BYTE) Partitioning type of


YPE the partitioned table.
Values are
INTERVAL,
RANGE, LIST, and
HASH.

3 PARTITION_COU BINARY_INTEGE Number of partitions


NT R in the table

4 PARTITIONING_K BINARY_INTEGE Number of columns


EY_COUNT R in the partition key

5 DEF_TABLESPAC VARCHAR(64 Default tablespace


E_NAME BYTE)

6 INTERVAL VARCHAR(1000 Valid for interval


BYTE) partitioned tables

7 STATUS CHAR(5 BYTE) Status of the


partitioned table

3.2.41 ADM_PROCEDURES
Displays information about all stored procedures, functions, and triggers in the database.

Table 3-106 ADM_PROCEDURES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 OBJECT_NAME VARCHAR(128BY Object name


TE)

2 PROCEDURE_NA VARCHAR(128BY Reserved system


ME TE) interface

3 OBJECT_ID BINARY_BIGINT Object ID

4 SUBPROGRAM_I BINARY_INTEGE Unique subprogram


D R identifier

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 153


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 OVERLOAD VARCHAR2(40BY Unique overload


TE) identifier

6 OBJECT_TYPE VARCHAR2(19BY Object type name


TE)

7 AGGREGATE VARCHAR2(3 Whether the


BYTE) procedure is an
aggregate function

8 PIPELINED VARCHAR2(3 Whether the


BYTE) procedure is a
pipelined table
function

9 SOURCE CLOB Source code

10 STATUS VARCHAR(7 Compilation status.


BYTE) 0: invalid; 1: valid;
2: unknown

3.2.42 ADM_PROFILES
Displays all profiles in the database.

Table 3-107 ADM_PROFILES columns


No. Column Name Data Type Description

0 PROFILE VARCHAR(64 Profile name


BYTE)

1 RESOURCE_NAM VARCHAR(64 Resource name


E BYTE)

2 RESOURCE_TYPE CHAR(8 BYTE) Resource type

3 THRESHOLD CHAR(52 BYTE) Threshold

3.2.43 ADM_ROLES
Displays information about all roles in the database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 154


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-108 ADM_ROLES columns

No. Column Name Data Type Description

0 ROLE VARCHAR(64 Role name


BYTE)

1 PASSWORD_REQ CHAR(2 BYTE) Whether a password


UIRED is required to enable
a role

2 AUTHENTICATIO CHAR(8 BYTE) Authentication type


N_TYPE

3.2.44 ADM_ROLE_PRIVS
Displays the permissions of all users in the database.

Table 3-109 DM_ROLE_PRIVS columns

No. Column Name Data Type Description

0 GRANTEE VARCHAR(64 Username


BYTE)

1 GRANTED_ROLE VARCHAR(64 Role permission


BYTE)

2 ADMIN_OPTION CHAR(3 BYTE) Whether the user has


the permission
(YES/NO)

3.2.45 ADM_SEGMENTS
Displays information about the storage allocated for all tables, indexes, and LOBs in the
database.

Table 3-110 ADM_SEGMENTS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 SEGMENT_NAME VARCHAR(133 Segment name


BYTE)

2 PARTITION_NAM VARCHAR(145 Partition name


E BYTE)

3 SEGMENT_TYPE CHAR(5 BYTE) Segment type

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 155


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the
segment

5 BYTES BINARY_BIGINT Segment size

6 PAGES BINARY_BIGINT Number of pages in


a segment

7 EXTENTS BINARY_BIGINT Number of extents


in a segment

3.2.46 ADM_SEQUENCES
Displays information about all sequences in the database.

Table 3-111 ADM_SEQUENCES columns


No. Column Name Data Type Description

0 SEQUENCE_OWN VARCHAR(64 Sequence owner


ER BYTE)

1 SEQUENCE_NAM VARCHAR(64 Sequence name


E BYTE)

2 MIN_VALUE BINARY_BIGINT Minimum value of


the sequence

3 MAX_VALUE BINARY_BIGINT Maximum value of


the sequence

4 INCREMENT_BY BINARY_BIGINT Value by which the


sequence is
incremented

5 CYCLE_FLAG BINARY_INTEGE Whether the


R sequence wraps
around on reaching
the limit

6 ORDER_FLAG BINARY_INTEGE Whether sequence


R numbers are
generated in order

7 CACHE_SIZE BINARY_BIGINT Number of sequence


numbers to cache

8 LAST_NUMBER BINARY_BIGINT Last sequence


number written to
disk

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 156


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.47 ADM_SOURCE
Displays information about all user-defined objects in the database.

Table 3-112 ADM_SOURCE columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 NAME VARCHAR(128 Object name


BYTE)

2 TYPE CHAR(9 BYTE) Type of the user-


defined object.
Values are:
l TRIGGER
l PROCEDURE
l FUNCTION
l UNDEFINED

3 LINE NUMBER Line number

4 TEXT CLOB Source code

3.2.48 ADM_SYNONYMS
Displays information about all synonyms in the database.

Table 3-113 ADM_SYNONYMS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 SYNONYM_NAME VARCHAR(64BY Synonym name


TE)

2 TABLE_OWNER VARCHAR(64BY Owner of the table


TE) referenced by the
synonym

3 TABLE_NAME VARCHAR(64 Name of the table


BYTE) referenced by the
synonym

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 157


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.49 ADM_SYS_PRIVS
Displays system permissions granted to all users in the database.

Table 3-114 ADM_SYS_PRIVS columns


No. Column Name Data Type Description

0 GRANTEE VARCHAR(64 Username


BYTE)

1 PRIVILEGE CHAR(28 BYTE) Permission

2 ADMIN_OPTION CHAR(3 BYTE) Whether the user


can grant
permissions to other
users or roles

3.2.50 ADM_TABLES
Displays information about all tables in the database.

Table 3-115 ADM_TABLES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 TABLE_ID BINARY_INTEGE Table ID


R

3 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the table

4 COLUMN_COUNT BINARY_INTEGE Number of table


R columns

5 INDEX_COUNT BINARY_INTEGE Number of table


R indexes

6 PARTITIONED CHAR(1 BYTE) Whether the table is


a partitioned table

7 CREATED_TIME DATE Time when the table


was created

8 LAST_DDL_TIME DATE Time when the table


was modified last
time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 158


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 PCT_FREE BINARY_INTEGE Minimum


R percentage of free
space in a block

10 INI_TRANS BINARY_INTEGE Initial size of the


R transaction table in a
block header

11 MAX_TRANS BINARY_INTEGE Maximum size of


R the transaction table
in a block header

12 BYTES BINARY_BIGINT Table size

13 PAGES BINARY_BIGINT Number of pages


occupied by the
table

14 EXTENTS BINARY_BIGINT Number of pages in


each automatic
extension

15 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

16 BLOCKS BINARY_INTEGE Number of data


R blocks in the table

17 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

18 AVG_SPACE NUMBER Compatibility


column, with no
value

19 CHAIN_CNT NUMBER Compatibility


column, with no
value

20 AVG_ROW_LEN BINARY_BIGINT Average row length

21 SAMPLE_SIZE BINARY_INTEGE Sample size


R

22 LAST_ANALYZED TIMESTAMP(6) Time when the table


was analyzed last
time

23 STATUS CHAR(5 BYTE) Whether the table is


valid

24 TEMPORARY CHAR(1 BYTE) Whether the table is


temporary

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 159


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

25 APPENDONLY CHAR(1 BYTE) Whether automatic


extension is enabled

26 TABLE_TYPE CHAR(12 BYTE) Table type. Values


are:
HEAP: ordinary
table
IOT: index-
organized table
TRANS_TEMP:
transaction-level
temporary table
SESSION_TEMP:
session-level
temporary table
EXTERNAL:
external table
NOLOGGING:
nologging table

27 CR_MODE CHAR(4 BYTE) MVCC mode of the


table. Values are:
l ROW: row-level
MVCC
l PAGE: page-
level MVCC

3.2.51 ADM_TABLESPACES
Displays information about all tablespaces in the database.

Table 3-116 ADM_TABLESPACES columns


No. Column Name Data Type Description

0 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

1 PAGE_SIZE BINARY_BIGINT Page size

2 EXTENT_PAGES BINARY_INTEGE Number of pages in


R an extent

3 DATAFILE_COUN BINARY_INTEGE Number of data files


T R

4 TOTAL_SIZE BINARY_BIGINT Total size

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 160


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 USED_SIZE BINARY_BIGINT Used size

6 STATUS VARCHAR(8 Status (ONLINE/


BYTE) OFFLINE)

7 IN_MEMORY VARCHAR(8 In-memory or not


BYTE)

8 CONTENTS CHAR(9 BYTE) PERMANENT/


TEMPORARY

9 LOGGING CHAR(1 BYTE) Whether logging is


enabled

10 BIGFILE CHAR(1 BYTE) Whether there are


big files

3.2.52 ADM_TAB_COLS
Displays information about the columns of all tables in the database.

Table 3-117 ADM_TAB_COLS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 DATA_TYPE VARCHAR(64 Column data type


BYTE)

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

8 COLUMN_ID BINARY_INTEGE Column ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 161


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

10 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

11 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

12 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

13 CHAR_LENGTH BINARY_INTEGE Length of the


R column in STRING
type (unit: byte). If
the column data type
is not STRING, the
value will be 0.

14 CHAR_USED VARCHAR(1 Whether


BYTE) CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C)

15 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.2.53 ADM_TAB_COLUMNS
Displays information about the columns of all tables and views in the database.

Table 3-118 ADM_TAB_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the table


BYTE) to which the column
belongs

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(128 Column name


BYTE)

3 DATA_TYPE VARCHAR(64 Column data type


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 162


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

8 COLUMN_ID INTEGER Column ID

9 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

10 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

11 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

12 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

13 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

14 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

15 CHAR_LENGTH BINARY_INTEGE Length of the


R column in STRING
type (unit: byte). If
the column data type
is not STRING, the
value will be 0.

16 CHAR_USED CHAR(1 BYTE) Whether


CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C). In
GaussDB 100, it
always uses BYTE
length semantics
(B).

17 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 163


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

18 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

19 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

20 AUTO_INCREME CHAR(1 BYTE) Whether the column


NT is an auto-increment
column. Values are:
Y
N

3.2.54 ADM_TAB_COL_STATISTICS
Displays statistics about the columns of all tables in the database.

Table 3-119 ADM_TAB_COL_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

4 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

5 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

6 DENSITY BINARY_DOUBLE Density of the


column

7 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

8 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 164


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

10 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

11 AVG_COL_LEN NUMBER Compatibility


column, with no
value

12 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.2.55 ADM_TAB_COMMENTS
Displays information about comments on all tables in the database.

Table 3-120 ADM_TAB_COMMENTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 TABLE_TYPE CHAR(5 BYTE) TABLE/VIEW

3 COMMENTS VARCHAR(4000 Comment on the


BYTE) table

3.2.56 ADM_TAB_DISTRIBUTE
Displays the table distribution information of all users. (If GaussDB 100 is deployed in
distributed mode, you can query this view for data. In standalone deployment, this view has
no data.)

Table 3-121 ADM_TAB_DISTRIBUTE columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 165


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 DIST_INFO VARCHAR(1024 Table distribution


BYTE) information

3.2.57 ADM_TAB_MODIFICATIONS
Displays modifications to all tables in the database, which include insert, delete, and update
operations.

Table 3-122 ADM_TAB_MODIFICATIONS columns


No. Column Name Data Type Description

0 TABLE_OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

3 SUBPARTITION_N VARCHAR(64 Subpartition name


AME BYTE)

4 INSERTS BINARY_INTEGE Number of inserted


R rows. It will be
cleared after the
ANALYZE
operation.

5 UPDATES BINARY_INTEGE Number of updated


R rows. It will be
cleared after the
ANALYZE
operation.

6 DELETES BINARY_INTEGE Number of deleted


R rows. It will be
cleared after the
ANALYZE
operation.

7 TIMESTAMP TIMESTAMP(6) Timestamp of row


modification last
time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 166


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 DROP_SEGMENT BINARY_INTEGE Number of segments


S R dropped since the
last analysis
operation

1. When STATISTICS_LEVEL, statistics collection level, is set to BASIC, table


modification information is not collected.
2. The table modification information is not synchronized in this view in real time.
According to system settings, there is at least a 15-minute delay before the
synchronization.

3.2.58 ADM_TAB_PARTITIONS
Displays information about partitions in all tables in the database.

Table 3-123 ADM_TAB_PARTITIONS columns


No. Column Name Data Type Description

0 TABLE_OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COMPOSITE VARCHAR(2 Whether the table is


BYTE) composite-
partitioned

3 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

4 SUBPARTITION_C NUMBER Number of


OUNT subpartitions in the
partition

5 HIGH_VALUE VARCHAR(4000 Partition boundary


BYTE) string

6 HIGH_VALUE_LE NUMBER Length of a partition


NGTH boundary string

7 PARTITION_POSIT BINARY_INTEGE Table partition ID


ION R

8 TABLESPACE_NA VARCHAR2(64 Table partition name


ME BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 167


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

9 INTERVAL CHAR(1 BYTE) Whether the


partition is an
interval partition
Values are Y and N.

10 PCT_FREE BINARY_INTEGE Reserved space


R

11 PCT_USED NUMBER Used space

12 INI_TRANS BINARY_INTEGE Initial number of


R transactions

13 MAX_TRANS NUMBER Maximum number


of transactions

14 INITIAL_EXTENT NUMBER Reserved system


interface

15 NEXT_EXTENT NUMBER Reserved system


interface

16 MIN_EXTENT NUMBER Reserved system


interface

17 MAX_EXTENT NUMBER Reserved system


interface

18 MAX_SIZE NUMBER Reserved system


interface

19 PCT_INCREASE NUMBER Reserved system


interface

20 FREELISTS NUMBER Reserved system


interface

21 FREELIST_GROU NUMBER Reserved system


PS interface

22 LOGGING VARCHAR2(7 Reserved system


BYTE) interface

23 COMPRESSION VARCHAR2(8 Reserved system


BYTE) interface

24 COMPRESS_FOR VARCHAR2(18 Reserved system


BYTE) interface

25 NUM_ROWS BINARY_INTEGE Reserved system


R interface

26 BLOCKS BINARY_INTEGE Reserved system


R interface

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 168


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

27 EMPTY_BLOCKS BINARY_INTEGE Reserved system


R interface

28 AVG_SPACE NUMBER Reserved system


interface

29 CHAIN_CNT NUMBER Reserved system


interface

30 AVG_ROW_LEN BINARY_INTEGE Reserved system


R interface

31 SAMPLE_SIZE BINARY_INTEGE Reserved system


R interface

32 LAST_ANALYZED DATE Reserved system


interface

33 BUFFER_POOL VARCHAR(7 Reserved system


BYTE) interface

34 GLOBAL_STATS VARCHAR(3 Reserved system


BYTE) interface

35 USER_STATS VARCHAR(3 Reserved system


BYTE) interface

3.2.59 ADM_TAB_PRIVS
Displays all user object permissions in the database.

Table 3-124 ADM_TAB_PRIVS columns


No. Column Name Data Type Description

0 GRANTEE VARCHAR(64 Name of the user to


BYTE) whom the
permission is
granted

1 OWNER VARCHAR(64 Object owner


BYTE)

2 OBJECT_NAME VARCHAR(64 Object name


BYTE)

3 OBJECT_TYPE CHAR(9 BYTE) Object type

4 PRIVILEGE CHAR(10 BYTE) Permission

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 169


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 GRANTABLE CHAR(3 BYTE) Whether the current


user can grant the
object permission to
another user or role.
Values are:
YES
NO

3.2.60 ADM_TAB_STATISTICS
Displays statistics about all tables in the database.

Table 3-125 ADM_TAB_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 PARTITION_NAM VARCHAR(64 Partition name. If


E BYTE) the table is not a
partitioned table,
this column will
display only NULL.

3 PARTITION_POSIT NUMBER Partitioned index,


ION starting from 1. If
the table is not a
partitioned table,
this column will
display only NULL.

4 OBJECT_TYPE CHAR(9 BYTE) Object type. Values


are TABLE and
PARTITION.

5 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

6 BLOCKS BINARY_INTEGE Number of blocks in


R the table

7 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 170


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 AVG_SPACE NUMBER Compatibility


column, with no
value

9 CHAIN_CNT NUMBER Compatibility


column, with no
value

10 AVG_ROW_LEN BINARY_BIGINT Average row length

11 AVG_SPACE_FRE NUMBER Compatibility


ELIST_BLOCKS column, with no
value

12 NUM_FREELIST_ NUMBER Compatibility


BLOCKS column, with no
value

13 AVG_CACHED_B NUMBER Compatibility


LOCKS column, with no
value

14 AVG_CACHE_HIT NUMBER Compatibility


_RATIO column, with no
value

15 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

16 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

3.2.61 ADM_TRIGGERS
Displays information about all triggers in the database.

Table 3-126 ADM_TRIGGERS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Trigger owner


BYTE)

1 TRIGGER_NAME VARCHAR(128 Trigger name


BYTE)

2 TABLE_NAME VARCHAR(128 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 171


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 TABLE_OWNER VARCHAR(128 Table owner


BYTE)

4 SOURCE CLOB Source code

5 STATUS VARCHAR(16 Trigger status


BYTE)

3.2.62 ADM_USERS
Displays information about all users in the database.

Table 3-127 ADM_USERS columns


No. Column Name Data Type Description

0 USERNAME VARCHAR(64 Username


BYTE)

1 USER_ID BINARY_INTEGE User ID


R

2 ACCOUNT_STATU CHAR(30 BYTE) User status. Values


S are:
OPEN
EXPIRED
EXPIRED(GRAC
E)
LOCKED(TIMED)
EXPIRED &
LOCKED(TIMED)
EXPIRED(GRAC
E) &
LOCKED(TIMED)
LOCKED
EXPIRED &
LOCKED
EXPIRED(GRAC
E) & LOCKED

3 LOCK_DATE DATE Time when the user


is locked

4 EXPIRY_DATE DATE Time when the user


password expires

5 DEFAULT_TABLE VARCHAR(64 Default tablespace


SPACE BYTE) name

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 172


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 TEMPORARY_TA VARCHAR(64 Temporary


BLESPACE BYTE) tablespace name

7 CREATED DATE Time when the user


is created.

8 PROFILE VARCHAR(64 User resource


BYTE) profile name

9 INITIAL_RSRC_C CHAR(22 BYTE) Compatibility


ONSUMER_GROU column,
P SYS_GROUP for
user SYS and
DEFAULT_CONS
UMER_GROUP
for other users

10 AUTHENTICATIO CHAR(8 BYTE) User authentication


N_TYPE mode. Currently,
only PASSWORD
is supported.

3.2.63 ADM_VIEWS
Displays information about all views in the database.

Table 3-128 ADM_VIEWS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 View owner


BYTE)

1 VIEW_NAME VARCHAR(64 View name


BYTE)

2 VIEW_TYPE CHAR(7 BYTE) View type

3 COLUMN_COUN BINARY_INTEGER Number of columns


T

4 TEXT CLOB View text

5 TEXT_LENGTH BINARY_INTEGER Length of the view text

6 CREATED_TIME DATE Time when the view was created

7 LAST_DDL_TIME DATE Time when the view definition was


updated last time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 173


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.2.64 ADM_VIEW_COLUMNS
Displays information about the columns of all views in the database.

Table 3-129 ADM_VIEW_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 View owner


BYTE)

1 VIEW_NAME VARCHAR(64 View name


BYTE)

2 COLUMN_ID BINARY_INTEGE Column ID


R

3 COLUMN_NAME VARCHAR(128 Column name


BYTE)

4 DATA_TYPE VARCHAR(64 Column data type


BYTE)

5 DATA_LENGTH BINARY_INTEGE Column length


R

6 DATA_PRECISION BINARY_INTEGE Column precision


R

7 DATA_SCALE BINARY_INTEGE Column scale


R

8 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

3.3 User Views


Table 3-130 lists the user views supported by GaussDB 100.

Table 3-130 User views


View Name Definition

DB_ARGUMENTS Displays the parameters of stored procedures and UDFs


created by the current user and user SYS.

DB_COL_COMMENTS Displays the column comments of the current user and


user SYS.

DB_CONSTRAINTS Displays the constraints of the current user and user


SYS.

DB_DBLINK_TABLES Displays table information of the current user and user


SYS.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 174


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

DB_DBLINK_TAB_COLUM Displays table column information of the current user


NS and user SYS.

DB_DEPENDENCIES Displays information about dependencies between all


the objects owned by the current user and user SYS.

DB_DISTRIBUTE_RULES Displays information about all distribution rules in the


system.

DB_DIST_RULE_COLS Displays information about all distribution rule columns


in the system.

DB_HISTOGRAMS Displays information about histograms on the tables


owned by the current user and user SYS.

DB_INDEXES Displays all indexes of the current user and user SYS.

DB_IND_COLUMNS Displays indexed columns in tables of the current user


and user SYS.

DB_IND_PARTITIONS Displays all partition indexes of the current user and


user SYS.

DB_OBJECTS Displays information about all objects of the current


user and user SYS.

DB_PART_COL_STATISTIC View column statistics about partitioned tables of the


S current user and user SYS.

DB_PART_KEY_COLUMNS Displays the partition column information of the


partitioned table of the current user and user SYS.

DB_PART_STORE Displays the tablespace information corresponding to


the STORE clause in the interval partitioned tables of
the current user and user SYS.

DB_PART_TABLES Displays the partitioned table information of the current


user and user SYS.

DB_PROCEDURES Displays information about stored procedures, functions,


and triggers of the current user.

DB_SEQUENCES Displays sequences of the current user and user SYS.

DB_SOURCE Displays information about user-defined objects of the


current user.

DB_SYNONYMS Displays synonyms of the current user, user SYS, and


user PUBLIC.

DB_TABLES Displays table information of the current user and user


SYS.

DB_TAB_COLS Displays table columns of the current user and user


SYS.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 175


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

DB_TAB_COLUMNS Displays all table columns of the current user and user
SYS.

DB_TAB_COL_STATISTICS Displays column statistics about the tables accessible to


the current user and user SYS.

DB_TAB_COMMENTS Displays all comments of the current user and user SYS.

DB_TAB_DISTRIBUTE Displays the table distribution information of the current


user and user SYS.

DB_TAB_PARTITIONS Displays table partitions of the current user and user


SYS.

DB_TAB_STATISTICS Displays statistics about the tables owned by the current


user and user SYS.

DB_TRIGGERS Displays triggers of the current user and user SYS.

DB_VIEWS Displays view information of the current user and user


SYS.

DB_VIEW_COLUMNS Displays the view columns of the current user and user
SYS.

DB_VIEW_DEPENDENCIE Displays the dependency between views created by the


S current user.

ROLE_SYS_PRIVS Displays the roles granted to the current user and the
system permissions granted to each role.

MY_ARGUMENTS Displays the parameters of stored procedures and UDFs


created by the current user.

MY_COL_COMMENTS Displays information about comments on the columns


of the tables owned by the current user.

MY_CONSTRAINTS Displays information about constraints on the tables


owned by the current user.

MY_CONS_COLUMNS Displays information about constraints on the columns


of tables owned by the current user.

MY_DEPENDENCIES Displays information about dependencies between all


the objects owned by the current user.

MY_FREE_SPACE Displays information about free extents in the


tablespaces accessible to the current user.

MY_HISTOGRAMS Displays information about histograms on the tables


owned by the current user.

MY_INDEXES Displays information about indexes owned by the


current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 176


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

MY_IND_COLUMNS Displays information about the indexed columns of the


current user.

MY_IND_PARTITIONS Displays the information about the partition indexes of


the current user.

MY_IND_STATISTICS Displays statistics about partitioned indexes owned by


the current user.

MY_JOBS Displays information about all jobs owned by the


current user.

MY_OBJECTS Displays information about all objects owned by the


current user.

MY_PART_COL_STATISTI Displays statistics about the columns of partitioned


CS tables owned by the current user.

MY_PART_KEY_COLUMN Displays information about the partition columns for


S partitioned tables owned by the current user.

MY_PART_STORE Displays information about the tablespaces


corresponding to the STORE clause used for interval
partitioned tables owned by the user.

MY_PART_TABLES Displays information about the partitioned tables owned


by the current user.

MY_PROCEDURES Displays stored procedures owned by the current user.


The stored procedures include general triggers, UDFs,
and stored procedure bodies.

MY_ROLE_PRIVS Displays information about roles granted to the current


user.

MY_SEGMENTS Displays information about the storage allocated for all


tables, indexes, and LOBs owned by the current user.

MY_SEQUENCES Displays information about the sequences owned by the


current user.

MY_SOURCE Displays information about all use-defined objects of the


current user.

MY_SQL_MAPS Displays all SQL mapping relationships owned by the


current user.

MY_SYNONYMS Displays synonyms of the current user.

MY_SYS_PRIVS Displays information about system permissions granted


to the current user.

MY_TABLES Displays information about the tables owned by the


current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 177


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

MY_TAB_COLS Displays information about the columns of tables owned


by the current user.

MY_TAB_COLUMNS Displays details about the columns of tables and views


owned by the current user.

MY_TAB_COL_STATISTIC Displays statistics about the columns of tables owned by


S the current user.

MY_TAB_COMMENTS Displays information about comments on the tables


owned by the current user.

MY_TAB_DISTRIBUTE Displays the table distribution information of the current


user.

MY_TAB_MODIFICATIONS Displays table modifications made by the current user.

MY_TAB_PARTITIONS Displays information about partitions in the tables


owned by the current user.

MY_TAB_PRIVS Displays information about permissions to the tables


owned by the current user.

MY_TAB_STATISTICS Displays the table statistics of the current user.

MY_TRIGGERS Displays information about the triggers owned by the


current user.

MY_USERS Displays information about the current user.

MY_VIEWS Displays information about the views owned by the


current user.

MY_VIEW_COLUMNS Displays information about the columns of views owned


by the current user.

3.3.1 DB_ARGUMENTS
Displays the parameters of stored procedures and UDFs created by the current user and user
SYS.

Table 3-131 DB_ARGUMENTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

1 OBJECT_NAME VARCHAR(128 Object name


BYTE)

2 ARGUMENT_NA VARCHAR(128 Parameter name


ME BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 178


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 POSITION BINARY_INTEGE Position of all


R parameters at the
same
DATA_LEVEL,
starting from 0

4 SEQUENCE BINARY_INTEGE Sequence of all


R parameters for the
same object, starting
from 1

5 DATA_LEVEL BINARY_INTEGE Level of the


R parameter,
supporting only 0
currently

6 DATA_TYPE VARCHAR(64 Data type of the


BYTE) parameter

7 DEFAULTED CHAR(1 BYTE) Whether the


parameter has a
default value

8 IN_OUT CHAR(6 BYTE) Values are:


l IN: input
parameter
l OUT: output
parameter
l IN OUT: both
input parameter
and output
parameter

9 DATA_LENGTH BINARY_INTEGE Data length


R

10 DATA_PRECISION BINARY_INTEGE Data precision,


R invalid temporarily

11 DATA_SCALE BINARY_INTEGE Data scale, invalid


R temporarily

3.3.2 DB_COL_COMMENTS
Displays the column comments of the current user and user SYS.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 179


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-132 DB_COL_COMMENTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(128 Column name


BYTE)

3 COMMENTS VARCHAR(4000 Column comment


BYTE)

3.3.3 DB_CONSTRAINTS
Displays the constraints of the current user and user SYS.

Table 3-133 DB_CONSTRAINTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Constraint owner


BYTE)

1 CONSTRAINT_NA VARCHAR(64 Constraint name


ME BYTE)

2 CONSTRAINT_TY CHAR(1 BYTE) Constraint type.


PE Values are:
P: primary key
constraint
C: check constraint
R: foreign key
constraint
U: unique key
constraint
This view displays
nothing for the NOT
NULL constraint.

3 TABLE_NAME VARCHAR(64 Name of the table on


BYTE) which the constraint
is defined

4 SEARCH_CONDIT VARCHAR(2048 Text of the search


ION BYTE) condition for a
check constraint. For
other constraints, the
value is NULL.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 180


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 R_OWNER VARCHAR(64 Owner of the


BYTE) primary or unique
key constraint
created on the
referenced column if
CONSTRAINT_T
YPE is R

6 R_TABLE_NAME VARCHAR(64 Name of the


BYTE) referenced table if
CONSTRAINT_T
YPE is R

7 R_CONSTRAINT_ VARCHAR(64 Name of the primary


NAME BYTE) or unique key
constraint created on
the referenced
column if
CONSTRAINT_T
YPE is R

8 DELETE_RULE CHAR(14 BYTE) Rule for processing


associated data in a
child table when the
data of the parent
table corresponding
to the foreign key
constraint is deleted.
Currently, only
NOT ALLOWED
is supported.

9 STATUS CHAR(8 BYTE) Enforcement status


of the constraint
Values are:
ENABLED
DISABLED

10 DEFERRABLE CHAR(14 BYTE) Whether the


constraint is
deferrable. This is a
compatibility
column, with the
only value NOT
DEFERRABLE.

11 DEFERRED CHAR(9 BYTE) Compatibility


column, with the
only value
IMMEDIATE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 181


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

12 VALIDATED CHAR(13 BYTE) Compatibility


column, with the
only value
VALIDATED

13 BAD CHAR Compatibility


column, with no
value

14 RELY CHAR Compatibility


column, with no
value

15 INDEX_OWNER VARCHAR(64 Owner of the index


BYTE) (only shown for
primary and unique
key constraints)

16 INDEX_NAME VARCHAR(64 Name of the index


BYTE) (only shown for
primary and unique
key constraints)

17 INVALID CHAR(5 BYTE) Compatibility


column, with the
only value FALSE

18 VIEW_RELATED CHAR Compatibility


column, with no
value

19 CONS_COLS VARCHAR(1088 Column on which a


BYTE) constraint is created

20 REF_COLS VARCHAR(1088 Name of the parent


BYTE) table column
referenced by a
foreign key
constraint

21 SYS_GENERATE CHAR(1 BYTE) Whether the


constraint name is
generated by the
system. Values are:
Y
N

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 182


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

22 IS_DUPLICATE CHAR(1 BYTE) Whether the


constraint name has
a duplicate. Values
are:
Y
N

3.3.4 DB_DBLINK_TABLES
Displays table information of the current user and user SYS.

Table 3-134 DB_DBLINK_TABLES columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 OWNER_ID BINARY_INTEGE User ID


R

3 TABLE_ID BINARY_INTEGE Table ID


R

4 COLUMN_COUNT BINARY_INTEGE Number of columns


R in the table

5 INDEX_COUNT BINARY_INTEGE Number of indexes


R on the table

3.3.5 DB_DBLINK_TAB_COLUMNS
Displays table column information of the current user and user SYS.

Table 3-135 DB_DBLINK_TAB_COLUMNS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 183


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 DATA_TYPE BINARY_INTEGE Column data type


R

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE BINARY_INTEGE Whether the column


R allows for NULL

8 COLUMN_ID BINARY_INTEGE Column ID


R

3.3.6 DB_DEPENDENCIES
Displays information about dependencies between all the objects owned by the current user
and user SYS.

Table 3-136 DB_DEPENDENCIES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

1 NAME VARCHAR(64 Object name


BYTE)

2 TYPE CHAR(12 BYTE) Object type

3 REFERENCED_O VARCHAR(64 Owner of the


WNER BYTE) referenced object

4 REFERENCED_NA VARCHAR(64 Name of the


ME BYTE) referenced object

5 REFERENCED_TY CHAR(12 BYTE) Type of the


PE referenced object

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 184


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.3.7 DB_DISTRIBUTE_RULES
Displays information about all distribution rules in the system. (If GaussDB 100 is deployed
in distributed mode, you can query this view for data. In standalone deployment, this view has
no data.)

Table 3-137 DB_DISTRIBUTE_RULES columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE Distribution rule ID


R

1 NAME VARCHAR(64 Distribution rule


BYTE) name

2 DIST_INFO VARCHAR(1024 Shard information of


BYTE) the distribution rule

3.3.8 DB_DIST_RULE_COLS
Displays information about all distribution rule columns in the system. (If GaussDB 100 is
deployed in distributed mode, you can query this view for data. In standalone deployment,
this view has no data.)

Table 3-138 DB_DIST_RULE_COLS columns

No. Column Name Data Type Description

0 DIST_RULE_NAM VARCHAR(64 Distribution rule


E BYTE) name

1 COLUMN_NAME VARCHAR(64 Column name


BYTE)

2 DATA_TYPE VARCHAR(64 Column data type


BYTE)

3 DATA_LENGTH BINARY_INTEGE Column length


R

4 DATA_PRECISION BINARY_INTEGE Column precision


R

5 DATA_SCALE BINARY_INTEGE Column scale


R

6 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

7 COLUMN_ID BINARY_INTEGE Column ID


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 185


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

9 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

10 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

11 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

12 CHAR_LENGTH BINARY_INTEGE Length of the


R column in STRING
type (unit: byte). If
the column data type
is not STRING, the
value will be 0.

13 CHAR_USED CHAR(1 BYTE) Whether


CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C). In
GaussDB 100, it
always uses BYTE
length semantics
(B).

14 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.9 DB_HISTOGRAMS
Displays information about histograms on the tables owned by the current user and user SYS.

Table 3-139 DB_HISTOGRAMS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 186


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 ENDPOINT_NUM BINARY_INTEGE Bucket number


BER R corresponding to a
column after data
distribution, starting
from 1

4 ENDPOINT_VALU BINARY_INTEGE Total number of


E R rows with a value
less than the
corresponding
column value

5 ENDPOINT_ACTU VARCHAR(4000 Column value


AL_VALUE BYTE) measured after data
distribution

3.3.10 DB_INDEXES
Displays all indexes of the current user and user SYS.

Table 3-140 DB_INDEXES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 INDEX_TYPE CHAR(6 BYTE) Index type, NORMAL by


default

3 TABLE_NAME VARCHAR(64 Table name


BYTE)

4 TABLESPACE_NAME VARCHAR(64 Tablespace name


BYTE)

5 IS_PRIMARY CHAR(1 BYTE) Whether the index


enforces a primary key
constraint

6 IS_UNIQUE CHAR(1 BYTE) Whether the index


enforces a unique key
constraint

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 187


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

7 IS_DUPLICATE CHAR(1 BYTE) Whether the index name


has a duplicate. Values
are:
l Y
l N

8 PARTITIONED CHAR(1 BYTE) Partitioned or not

9 STATUS CHAR(7 BYTE) Index status


VALID
INVALID

10 INI_TRANS BINARY_INTEGER Initial number of


transactions

11 MAX_TRANS BINARY_INTEGER Maximum number of


transactions

12 PCT_FREE BINARY_INTEGER PCT FREE

13 COLUMN_COUNT BINARY_INTEGER Number of columns

14 COLUMNS VARCHAR(1088 Linked list of columns


BYTE)

15 BYTES BINARY_BIGINT Index size

16 PAGES BINARY_BIGINT Number of pages


occupied by the index

17 EXTENTS BINARY_BIGINT Number of extents


occupied by the index

18 BLEVEL BINARY_INTEGER Index tree level

19 LEAF_BLOCKS BINARY_INTEGER Number of leaf blocks

20 EMPTY_LEAF_BLOCK BINARY_INTEGER Number of empty leaf


S blocks

21 DISTINCT_KEYS BINARY_INTEGER Number of distinct keys

22 AVG_LEAF_BLOCKS_P BINARY_DOUBLE Average number of leaf


ER_KEY nodes for each key

23 AVG_DATA_BLOCKS_ BINARY_DOUBLE Average number of data


PER_KEY blocks for each key

24 CLUSTERING_FACTOR NUMBER Compatibility column,


with no value

25 NUM_ROWS BINARY_INTEGER Number of data rows in


the indexed table
measured last time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 188


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

26 SAMPLE_SIZE BINARY_INTEGER Number of sample rows in


the indexed table
measured last time

27 LAST_ANALYZED TIMESTAMP(6) Time point when the


indexed table was
analyzed last time

28 SYS_GENERATE BINARY_BIGINT Whether the index is


generated by the system

29 CR_MODE CHAR(4 BYTE) MVCC mode of the


index. Values are:
l ROW: row-level
MVCC
l PAGE: page-level
MVCC

3.3.11 DB_IND_COLUMNS
Displays indexed columns in tables of the current user and user SYS.

Table 3-141 DB_IND_COLUMNS columns


No. Column Name Data Type Description

0 INDEX_OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 TABLE_OWNER VARCHAR(64 Table owner


BYTE)

3 TABLE_NAME VARCHAR(64 Table name


BYTE)

4 COLUMN_NAME VARCHAR(64 Column name


BYTE)

5 COLUMN_POSITI BINARY_INTEGE Column position


ON R

6 COLUMN_LENGT BINARY_INTEGE Column length


H R

7 ID BINARY_INTEGE Column ID
R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 189


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 DEFAULT_TEXT VARCHAR(1024 Default column


BYTE) value (text)

3.3.12 DB_IND_PARTITIONS
Displays all partition indexes of the current user and user SYS.

Table 3-142 DB_IND_PARTITIONS columns


No. Column Name Data Type Description

0 INDEX_OWNER VARCHAR(64 Index owner


BYTE)

1 INDEX_NAME VARCHAR(64 Index name


BYTE)

2 COMPOSITE CHAR(2 BYTE) Whether the


partition within the
index is a composite
partition. Values are
YES and NO.

3 PARTITION_NAM VARCHAR(64 Name of the


E BYTE) partition within the
index

4 PARTITION_POSIT BINARY_INTEGE Subscript of the


ION R partition within the
index, starting from
1

5 STATUS CHAR(6 BYTE) Index status

6 PCT_FREE BINARY_INTEGE Percentage of


R minimum reserved
space for future
update operations on
a page

7 INI_TRANS BINARY_INTEGE Number of ITL


R entries initially
allocated to a page

8 MAX_TRANS BINARY_INTEGE Maximum number


R of ITL entries on a
page

9 BLEVEL BINARY_INTEGE Index tree level


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 190


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

10 LEAF_BLOCKS BINARY_INTEGE Number of leaf node


R pages

11 DISTINCT_KEYS BINARY_INTEGE Number of distinct


R keys

12 AVG_LEAF_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY leaf nodes for each
key

13 AVG_DATA_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY data blocks for each
key

14 CLUSTERING_FA NUMBER Compatibility


CTOR column, with no
value

15 NUM_ROWS BINARY_INTEGE Number of rows


R returned when the
partition was
analyzed last time

16 SAMPLE_SIZE BINARY_INTEGE Number of pages


R sampled when the
partition was
analyzed last time

17 LAST_ANALYZED DATE Time point when the


partition was
analyzed last time

3.3.13 DB_OBJECTS
Displays information about all objects of the current user and user SYS.

Table 3-143 DB_OBJECTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

1 OBJECT_NAME VARCHAR(128 Object name


BYTE)

2 SUBOBJECT_NAME VARCHAR(64 Sub-object name


BYTE)

3 OBJECT_ID BINARY_BIGINT Object ID

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 191


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 OBJECT_TYPE CHAR(14 BYTE) Object type. Values


are:
l SYNONYM
l SEQUENCE
l PROCEDURE
l FUNCTION
l DYNAMIC
VIEW
l VIEW
l INDEX
l RECYCLED
INDEX
l TABLE
l RECYCLED
TABLE
l TRIGGER

5 CREATED DATE Object creation time

6 LAST_DDL_TIME DATE Time of the last DC


update on the object

7 STATUS CHAR(7 BYTE) Object status,


VALID by default

8 TEMPORARY VARCHAR(1 Whether an object is


BYTE) temporary. Its values
are Y (yes) and N
(no).

3.3.14 DB_PART_COL_STATISTICS
View column statistics about partitioned tables of the current user and user SYS.

Table 3-144 DB_PART_COL_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) partitioned table

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 192


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 COLUMN_NAME VARCHAR(64 Column name


BYTE)

4 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

5 LOW_VALUE VARCHAR(4000 Minimum value in


BYTE) the column

6 HIGH_VALUE VARCHAR(4000 Maximum value in


BYTE) the column

7 DENSITY BINARY_DOUBLE Density of the


column

8 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

9 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

10 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

11 LAST_ANALYZED DATE Time when statistics


were collected last
time

12 AVG_COL_LEN NUMBER Compatibility


column, with no
value

13 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.15 DB_PART_KEY_COLUMNS
Displays the partition column information of the partitioned table of the current user and user
SYS.

Table 3-145 DB_PART_KEY_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) partitioned table

1 NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 193


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

3 COLUMN_NAME VARCHAR(64 Column name


BYTE)

4 COLUMN_POSITI BINARY_BIGINT Position of the


ON column within the
partition key

3.3.16 DB_PART_STORE
Displays the tablespace information corresponding to the STORE clause in the interval
partitioned tables of the current user and user SYS.

Table 3-146 DB_PART_STORE columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 NAME VARCHAR(64 Object name


BYTE)

2 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

3 POSITION BINARY_INTEGE Tablespace position


R

4 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

3.3.17 DB_PART_TABLES
Displays the partitioned table information of the current user and user SYS.

Table 3-147 DB_PART_TABLES columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the


BYTE) partitioned table

1 TABLE_NAME VARCHAR(64 Name of the


BYTE) partitioned table

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 194


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 PARTITIONING_T CHAR(7 BYTE) Partitioning type of


YPE the partitioned table.
The value can be
INVALID,
RANGE, LIST, or
HASH.

3 PARTITION_COU BINARY_INTEGE Number of partitions


NT R in the table

4 PARTITIONING_K BINARY_INTEGE Number of columns


EY_COUNT R in the partition key

5 DEF_TABLESPAC VARCHAR(64 Default tablespace


E_NAME BYTE)

6 INTERVAL VARCHAR(1000 Valid for interval


BYTE) partitioned tables

7 STATUS CHAR(5 BYTE) Status of the


partitioned table

3.3.18 DB_PROCEDURES
Displays information about stored procedures, functions, and triggers of the current user.

Table 3-148 DB_PROCEDURES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 OBJECT_NAME VARCHAR(128 Object name


BYTE)

2 PROCEDURE_NA VARCHAR(128 Name of a package


ME BYTE) or type subprogram

3 OBJECT_ID BINARY_BIGINT Object ID

4 SUBPROGRAM_I BINARY_INTEGE Unique subprogram


D R identifier

5 OVERLOAD VARCHAR2(40 Unique overload


BYTE) identifier

6 OBJECT_TYPE VARCHAR2(19 Object type name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 195


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

7 AGGREGATE VARCHAR2(3 Whether the


BYTE) procedure is an
aggregate function

8 PIPELINED VARCHAR2(3 Whether the


BYTE) procedure is a
pipelined table
function

9 SOURCE CLOB Source code

10 STATUS VARCHAR(7 Compilation status.


BYTE) 0: invalid; 1: valid;
2: unknown

3.3.19 DB_SEQUENCES
Displays sequences of the current user and user SYS.

Table 3-149 DB_SEQUENCES columns


No. Column Name Data Type Description

0 SEQUENCE_OWN VARCHAR(64 Sequence owner


ER BYTE)

1 SEQUENCE_NAM VARCHAR(64 Sequence name


E BYTE)

2 MIN_VALUE BINARY_BIGINT Minimum value of


the sequence

3 MAX_VALUE BINARY_BIGINT Maximum value of


the sequence

4 INCREMENT_BY BINARY_BIGINT Value by which the


sequence is
incremented

5 CYCLE_FLAG BINARY_INTEGE Whether the


R sequence wraps
around on reaching
the limit

6 ORDER_FLAG BINARY_INTEGE Whether sequence


R numbers are
generated in order

7 CACHE_SIZE BINARY_BIGINT Number of sequence


numbers to cache

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 196


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 LAST_NUMBER BINARY_BIGINT Last sequence


number written to
disk

3.3.20 DB_SOURCE
Displays information about user-defined objects of the current user.

Table 3-150 DB_SOURCE columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 NAME VARCHAR(128 Object name


BYTE)

2 TYPE VARCHAR(9 Type of the user-


BYTE) defined object.
Values are:
l TRIGGER
l PROCEDURE
l FUNCTION
l UNDEFINED

3 LINE NUMBER Line number

4 TEXT CLOB Source code

3.3.21 DB_SYNONYMS
Displays synonyms of the current user, user SYS, and user PUBLIC.

Table 3-151 DB_SYNONYMS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 SYNONYM_NAME VARCHAR(64 Synonym name


BYTE)

2 TABLE_OWNER VARCHAR(64 Owner of the table


BYTE) referenced by the
synonym

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 197


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 TABLE_NAME VARCHAR(64 Name of the table


BYTE) referenced by the
synonym

3.3.22 DB_TABLES
Displays table information of the current user and user SYS.

Table 3-152 DB_TABLES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 TABLE_ID BINARY_INTEGE Table ID


R

3 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the table

4 COLUMN_COUNT BINARY_INTEGE Number of table


R columns

5 INDEX_COUNT BINARY_INTEGE Number of table


R indexes

6 PARTITIONED CHAR(1 BYTE) Whether the table is


a partitioned table

7 CREATED_TIME DATE Time when the table


was created

8 LAST_DDL_TIME DATE Time when the table


was modified last
time

9 PCT_FREE BINARY_INTEGE Minimum


R percentage of free
space in a block

10 INIT_TRANS BINARY_INTEGE Initial size of the


R transaction table in a
block header

11 MAX_TRANS BINARY_INTEGE Maximum size of


R the transaction table
in a block header

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 198


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

12 BYTES BINARY_BIGINT Table size

13 PAGES BINARY_BIGINT Number of pages


occupied by the
table

14 EXTENTS BINARY_BIGINT Number of pages in


each automatic
extension

15 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

16 BLOCKS BINARY_INTEGE Number of data


R blocks in the table

17 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

18 AVG_SPACE NUMBER Compatibility


column, with no
value

19 CHAIN_CNT NUMBER Compatibility


column, with no
value

20 AVG_ROW_LEN BINARY_BIGINT Average row length

21 SAMPLE_SIZE BINARY_INTEGE Sample size


R

22 LAST_ANALYZED TIMESTAMP(6) Time when the table


was analyzed last
time

23 STATUS CHAR(5 BYTE) Whether the table is


valid

24 TEMPORARY CHAR(1 BYTE) Whether the table is


temporary

25 APPENDONLY CHAR(1 BYTE) Whether automatic


extension is enabled

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 199


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

26 TABLE_TYPE CHAR(12 BYTE) Table type. Values


are:
HEAP: ordinary
table
IOT: index-
organized table
TRANS_TEMP:
transaction-level
temporary table
SESSION_TEMP:
session-level
temporary table
EXTERNAL:
external table
NOLOGGING:
nologging table

27 CR_MODE CHAR(4 BYTE) MVCC mode of the


table. Values are:
l ROW: row-level
MVCC
l PAGE: page-
level MVCC

3.3.23 DB_TAB_COLS
Displays table columns of the current user and user SYS.

Table 3-153 DB_TAB_COLS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 DATA_TYPE VARCHAR(64 Column data type


BYTE)

4 DATA_LENGTH BINARY_INTEGE Column length


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 200


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

8 COLUMN_ID BINARY_INTEGE Column ID


R

9 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

10 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

11 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

12 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

13 CHAR_LENGTH BINARY_INTEGE Length of the


R column in STRING
type (unit: byte). If
the column data type
is not STRING, the
value will be 0.

14 CHAR_USED VARCHAR(1 Whether


BYTE) CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C)

15 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.24 DB_TAB_COLUMNS
Displays all table columns of the current user and user SYS.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 201


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-154 DB_TAB_COLUMNS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Owner of the table


BYTE) to which the column
belongs

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(128 Column name


BYTE)

3 DATA_TYPE VARCHAR(64 Column data type


BYTE)

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Column precision


R

6 DATA_SCALE BINARY_INTEGE Column scale


R

7 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

8 COLUMN_ID BINARY_INTEGE Column ID


R

9 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

10 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

11 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

12 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

13 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

14 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

15 CHAR_LENGTH BINARY_INTEGE Length of the


R column in STRING
type (unit: byte). If
the column data type
is not STRING, the
value will be 0.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 202


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

16 CHAR_USED CHAR(1 BYTE) Whether


CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C). In
GaussDB 100, it
always uses BYTE
length semantics
(B).

17 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

18 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

19 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

20 AUTO_INCREME CHAR(1 BYTE) Whether the column


NT is an auto-increment
column. Values are:
Y
N

3.3.25 DB_TAB_COL_STATISTICS
Displays column statistics about the tables accessible to the current user and user SYS.

Table 3-155 DB_TAB_COL_STATISTICS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

4 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 203


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

6 DENSITY BINARY_DOUBLE Density of the


column

7 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

8 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

9 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

10 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

11 AVG_COL_LEN NUMBER Compatibility


column, with no
value

12 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.26 DB_TAB_COMMENTS
Displays all comments of the current user and user SYS.

Table 3-156 DB_TAB_COMMENTS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 TABLE_TYPE CHAR(5 BYTE) Table or view

3 COMMENTS VARCHAR(4000 Comment


BYTE) information of the
table or view

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 204


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.3.27 DB_TAB_DISTRIBUTE
Displays the table distribution information of the current user and user SYS. (If GaussDB 100
is deployed in distributed mode, you can query this view for data. In standalone deployment,
this view has no data.)

Table 3-157 DB_TAB_DISTRIBUTE columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 DIST_INFO VARCHAR(1024 Table distribution


BYTE) information

3.3.28 DB_TAB_PARTITIONS
Displays table partitions of the current user and user SYS.

Table 3-158 DB_TAB_PARTITIONS columns

No. Column Name Data Type Description

0 TABLE_OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

2 COMPOSITE VARCHAR(2 Whether the table is


BYTE) composite-
partitioned

3 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

4 SUBPARTITION_C NUMBER Number of


OUNT subpartitions in the
partition

5 HIGH_VALUE VARCHAR(4000 Partition boundary


BYTE) string

6 HIGH_VALUE_LE NUMBER Length of a partition


NGTH boundary string

7 PARTITION_POSIT BINARY_INTEGE Table partition ID


ION R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 205


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 TABLESPACE_NA VARCHAR2(64 Table partition name


ME BYTE)

9 INTERVAL CHAR(1 BYTE) Whether the


partition is an
interval partition
Values are:
Y and N

10 PCT_FREE BINARY_INTEGE Reserved space


R

11 PCT_USED NUMBER Used space

12 INI_TRANS BINARY_INTEGE Initial number of


R transactions

13 MAX_TRANS NUMBER Maximum number


of transactions

14 INITIAL_EXTENT NUMBER Reserved system


interface

15 NEXT_EXTENT NUMBER Reserved system


interface

16 MIN_EXTENT NUMBER Reserved system


interface

17 MAX_EXTENT NUMBER Reserved system


interface

18 MAX_SIZE NUMBER Reserved system


interface

19 PCT_INCREASE NUMBER Reserved system


interface

20 FREELISTS NUMBER Reserved system


interface

21 FREELIST_GROU NUMBER Reserved system


PS interface

22 LOGGING VARCHAR(7 Reserved system


BYTE) interface

23 COMPRESSION VARCHAR(8 Reserved system


BYTE) interface

24 COMPRESS_FOR VARCHAR(18 Reserved system


BYTE) interface

25 NUM_ROWS BINARY_INTEGE Reserved system


R interface

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 206


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

26 BLOCKS BINARY_INTEGE Reserved system


R interface

27 EMPTY_BLOCKS BINARY_INTEGE Reserved system


R interface

28 AVG_SPACE NUMBER Reserved system


interface

29 CHAIN_CNT NUMBER Reserved system


interface

30 AVG_ROW_LEN BINARY_INTEGE Reserved system


R interface

31 SAMPLE_SIZE BINARY_INTEGE Reserved system


R interface

32 LAST_ANALYZED DATE Reserved system


interface

33 BUFFER_POOL VARCHAR(7 Reserved system


BYTE) interface

34 GLOBAL_STATS VARCHAR(3 Reserved system


BYTE) interface

35 USER_STATS VARCHAR(3 Reserved system


BYTE) interface

3.3.29 DB_TAB_STATISTICS
Displays statistics about the tables owned by the current user and user SYS.
The table statistics are mainly used for optimizing SQL statements. The collection will be
triggered by the analyze table table_name compute statistics command, and all statistics of
a table will be collected.

Table 3-159 DB_TAB_STATISTICS columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Table owner


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 207


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 PARTITION_NAM VARCHAR(64 Partition name. If


E BYTE) the table is not a
partitioned table,
this column will
display only NULL.

3 PARTITION_POSIT NUMBER Partitioned index,


ION starting from 1. If
the table is not a
partitioned table,
this column will
display only NULL.

4 OBJECT_TYPE CHAR(9 BYTE) Object type. Values


are TABLE and
PARTITION.

5 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

6 BLOCKS BINARY_INTEGE Number of blocks in


R the table

7 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

8 AVG_SPACE NUMBER Compatibility


column, with no
value

9 CHAIN_CNT NUMBER Compatibility


column, with no
value

10 AVG_ROW_LEN BINARY_BIGINT Average row length

11 AVG_SPACE_FRE NUMBER Compatibility


ELIST_BLOCKS column, with no
value

12 NUM_FREELIST_ NUMBER Compatibility


BLOCKS column, with no
value

13 AVG_CACHED_B NUMBER Compatibility


LOCKS column, with no
value

14 AVG_CACHE_HIT NUMBER Compatibility


_RATIO column, with no
value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 208


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

15 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

16 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

3.3.30 DB_TRIGGERS
Displays triggers of the current user and user SYS.

Table 3-160 DB_TRIGGERS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Trigger owner


BYTE)

1 TRIGGER_NAME VARCHAR(128 Trigger name


BYTE)

2 TABLE_OWNER VARCHAR(128 Table owner


BYTE)

3 TABLE_NAME VARCHAR(128 Table name


BYTE)

4 SOURCE CLOB Source code

5 STATUS VARCHAR(16 Trigger status


BYTE)

3.3.31 DB_VIEWS
Displays view information of the current user and user SYS.

Table 3-161 DB_VIEWS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 View owner


BYTE)

1 VIEW_NAME VARCHAR(64 View name


BYTE)

2 VIEW_TYPE CHAR(7 BYTE) View type

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 209


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 COLUMN_COUN BINARY_INTEGER Number of columns


T

4 TEXT CLOB View text

5 TEXT_LENGTH BINARY_INTEGER Length of the view text

6 CREATED_TIME DATE Time when the view was created

7 LAST_DDL_TIME DATE Time of the last DC update in the


view

3.3.32 DB_VIEW_COLUMNS
Displays the view columns of the current user and user SYS.

Table 3-162 DB_VIEW_COLUMNS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 View owner


BYTE)

1 VIEW_NAME VARCHAR(64 View name


BYTE)

2 COLUMN_ID BINARY_INTEGE Column ID


R

3 COLUMN_NAME VARCHAR(128 Column name


BYTE)

4 DATA_TYPE VARCHAR(64 Column data type


BYTE)

5 DATA_LENGTH BINARY_INTEGE Column length


R

6 DATA_PRECISION BINARY_INTEGE Column precision


R

7 DATA_SCALE BINARY_INTEGE Column scale


R

8 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

3.3.33 DB_VIEW_DEPENDENCIES
Displays the dependency between views created by the current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 210


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-163 DB_VIEW_DEPENDENCIES columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Primary view owner


BYTE)

1 NAME VARCHAR(64 Primary view name


BYTE)

2 REFERENCED_O VARCHAR(64 Dependent view


WNER BYTE) owner

3 REFERENCED_NA VARCHAR(64 Dependent view


ME BYTE) name

4 REFERENCED_LE BINARY_INTEGE Dependency level


VEL R

3.3.34 ROLE_SYS_PRIVS
Displays the roles granted to the current user and the system permissions granted to each role.

Table 3-164 ROLE_SYS_PRIVS columns


No. Column Name Data Type Description

0 ROLE VARCHAR(64 Role name


BYTE)

1 PRIVILEGE CHAR(28 BYTE) Permission

2 ADMIN_OPTION CHAR(3 BYTE) Whether the role has


the permission
(YES/NO)

3.3.35 MY_ARGUMENTS
Displays the parameters of stored procedures and UDFs created by the current user.

Table 3-165 MY_ARGUMENTS columns


No. Column Name Data Type Description

0 OBJECT_NAME VARCHAR(128 Object name


BYTE)

1 ARGUMENT_NA VARCHAR(128 Parameter name


ME BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 211


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 POSITION BINARY_INTEGE Position of all


R parameters at the
same
DATA_LEVEL,
starting from 0

3 SEQUENCE BINARY_INTEGE Sequence of all


R parameters for the
same object, starting
from 1

4 DATA_LEVEL BINARY_INTEGE Level of the


R parameter,
supporting only 0
currently

5 DATA_TYPE VARCHAR(64 Data type of the


BYTE) parameter

6 DEFAULTED CHAR(1 BYTE) Whether the


parameter has a
default value

7 IN_OUT CHAR(6 BYTE) Values are:


l IN: input
parameter
l OUT: output
parameter
l IN OUT: both
input parameter
and output
parameter

8 DATA_LENGTH BINARY_INTEGE Data length


R

9 DATA_PRECISION BINARY_INTEGE Data precision, valid


R for numbers

10 DATA_SCALE BINARY_INTEGE Data scale, valid for


R numbers

3.3.36 MY_COL_COMMENTS
Displays information about comments on the columns of the tables owned by the current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 212


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-166 MY_COL_COMMENTS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 COLUMN_NAME VARCHAR(128 Column name


BYTE)

2 COMMENTS VARCHAR(4000 Column comment


BYTE)

3.3.37 MY_CONSTRAINTS
Displays information about constraints on the tables owned by the current user.

Table 3-167 MY_CONSTRAINTS columns


No. Column Data Description
Name Type

0 OWNER VARCHA Constraint owner, same as the current user


R(64
BYTE)

1 CONSTRAIN VARCHA Constraint name


T_NAME R(64
BYTE)

2 CONSTRAIN CHAR(1 Constraint type. Values are:


T_TYPE BYTE) P: primary key constraint
C: check constraint
R: foreign key constraint
U: unique key constraint
This view displays nothing for the NOT NULL
constraint.

3 TABLE_NA VARCHA Name of the table on which the constraint is


ME R(64 defined
BYTE)

4 SEARCH_C VARCHA Text of the search condition for a check constraint.


ONDITION R(2048 For other constraints, the value is NULL.
BYTE)

5 R_OWNER VARCHA Owner of the primary or unique key constraint


R(64 created on the referenced column if
BYTE) CONSTRAINT_TYPE is R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 213


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Description


Name Type

6 R_TABLE_N VARCHA Name of the referenced table if


AME R(64 CONSTRAINT_TYPE is R
BYTE)

7 R_CONSTR VARCHA Name of the primary or unique key constraint


AINT_NAM R(64 created on the referenced column if
E BYTE) CONSTRAINT_TYPE is R

8 DELETE_RU CHAR(14 Rule for processing associated data in a child table


LE BYTE) when the data of the parent table corresponding to
the foreign key constraint is deleted. Currently, only
NOT ALLOWED is supported.

9 STATUS CHAR(8 Enforcement status of the constraint Values are:


BYTE) ENABLED
DISABLED

10 DEFERRAB CHAR(14 Whether the constraint is deferrable. This is a


LE BYTE) compatibility column, with the only value NOT
DEFERRABLE.

11 DEFERRED CHAR(9 Compatibility column, with the only value


BYTE) IMMEDIATE

12 VALIDATED CHAR(13 Compatibility column, with the only value


BYTE) VALIDATED

13 BAD CHAR Compatibility column, with no value

14 RELY CHAR Compatibility column, with no value

15 INDEX_OW VARCHA Owner of the index (only shown for primary and
NER R(64 unique key constraints)
BYTE)

16 INDEX_NA VARCHA Name of the index (only shown for primary and
ME R(64 unique key constraints)
BYTE)

17 INVALID CHAR(5 Compatibility column, with the only value FALSE


BYTE)

18 VIEW_RELA CHAR Compatibility column, with no value


TED

19 CONS_COLS VARCHA Name of the column on which a constraint is


R(1088 created
BYTE)

20 REF_COLS VARCHA Name of the parent table column referenced by a


R(1088 foreign key constraint
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 214


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Description


Name Type

21 SYS_GENER CHAR(1 Whether the constraint name is generated by the


ATE BYTE) system.
Y
N

22 IS_DUPLICA CHAR(1 Whether the constraint name has a duplicate. Values


TE BYTE) are:
Y
N

3.3.38 MY_CONS_COLUMNS
Displays information about constraints on the columns of tables owned by the current user.

Table 3-168 MY_CONS_COLUMNS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Constraint owner


BYTE)

1 CONSTRAINT_NA VARCHAR(64 Constraint name


ME BYTE)

2 TABLE_NAME VARCHAR(64 Table name


BYTE)

3 COLUMN_NAME VARCHAR(64 Column name


BYTE)

4 POSITION BINARY_INTEGE ID of the column on


R which the constraint
is created

3.3.39 MY_DEPENDENCIES
Displays information about dependencies between all the objects owned by the current user.

Table 3-169 MY_DEPENDENCIES columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 Object owner


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 215


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 NAME VARCHAR(64 Object name


BYTE)

2 TYPE CHAR(12 BYTE) Object type

3 REFERENCED_O VARCHAR(64 Owner of the


WNER BYTE) referenced object

4 REFERENCED_NA VARCHAR(64 Name of the


ME BYTE) referenced object

5 REFERENCED_TY CHAR(12 BYTE) Type of the


PE referenced object

3.3.40 MY_FREE_SPACE
Displays information about free extents in the tablespaces accessible to the current user.

Table 3-170 MY_FREE_SPACE columns


No. Column Name Data Type Description

0 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

1 FILE_ID BINARY_INTEGE File ID


R

2 BLOCK_ID BINARY_INTEGE ID of the start block


R in the free extent

3 BYTES BINARY_BIGINT Size of the free


extent (unit: byte)

4 BLOCKS BINARY_BIGINT Size of the free


extent (unit: block)

5 RELATIVE_FNO BINARY_INTEGE Relative file ID.


R This column is a
compatibility
column and an
equivalent to
FILE_ID.

3.3.41 MY_HISTOGRAMS
Displays information about histograms on the tables owned by the current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 216


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-171 MY_HISTOGRAMS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 COLUMN_NAME VARCHAR(64 Column name


BYTE)

2 ENDPOINT_NUM BINARY_INTEGE Bucket number


BER R corresponding to a
column after data
distribution, starting
from 1

3 ENDPOINT_VALU BINARY_INTEGE Total number of


E R rows with a value
less than the
corresponding
column value

4 ENDPOINT_ACTU VARCHAR(4000 Column value


AL_VALUE BYTE) measured after data
distribution

3.3.42 MY_INDEXES
Displays information about indexes owned by the current user.

Table 3-172 MY_INDEXES columns


No. Column Name Data Type Description

0 INDEX_NAME VARCHAR(64 Index name


BYTE)

1 INDEX_TYPE CHAR(6 BYTE) Index type,


NORMAL by
default

2 TABLE_NAME VARCHAR(64 Table name


BYTE)

3 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

4 IS_PRIMARY CHAR(1 BYTE) Whether the index


enforces a primary
key constraint

5 IS_UNIQUE CHAR(1 BYTE) Whether the index


enforces a unique
key constraint

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 217


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 IS_DUPLICATE CHAR(1 BYTE) Whether the index


name has a
duplicate. Values
are:
l Y
l N

7 PARTITIONED CHAR(1 BYTE) Partitioned or not

8 STATUS CHAR(7 BYTE) Index status


VALID
INVALID

9 INI_TRANS BINARY_INTEGE Initial number of


R transactions

10 MAX_TRANS BINARY_INTEGE Maximum number


R of transactions, that
is, 255

11 PCT_FREE BINARY_INTEGE Minimum


R percentage of free
space in a block.
Currently, the value
is always 8.

12 COLUMN_COUNT BINARY_INTEGE Number of columns


R

13 COLUMNS VARCHAR(1088 List of column


BYTE) names

14 BYTES BINARY_BIGINT Size

15 PAGES BINARY_BIGINT Number of pages

16 EXTENTS BINARY_BIGINT Number of extents

17 BLEVEL BINARY_INTEGE Index tree level


R

18 LEAF_BLOCKS BINARY_INTEGE Number of leaf node


R pages

19 EMPTY_LEAF_BL BINARY_INTEGE Number of empty


OCKS R leaf blocks

20 DISTINCT_KEYS BINARY_INTEGE Number of distinct


R keys

21 AVG_LEAF_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY leaf nodes for each
key

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 218


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

22 AVG_DATA_BLOC BINARY_DOUBLE Average number of


KS_PER_KEY data blocks for each
key

23 CLUSTERING_FA NUMBER Compatibility


CTOR column, with no
value

24 NUM_ROWS BINARY_INTEGE Number of data


R rows in the indexed
table measured last
time

25 SAMPLE_SIZE BINARY_INTEGE Number of sample


R rows in the indexed
table measured last
time

26 LAST_ANALYZED TIMESTAMP(6) Time point when the


indexed table was
analyzed last time

27 SYS_GENERATE BINARY_BIGINT Whether the


constraint name is
generated by the
system. Values are Y
and N.

28 CR_MODE CHAR(4 BYTE) Index MVCC


mechanism. Values
are:
l ROW: row-level
MVCC
l PAGE: page-
level MVCC

3.3.43 MY_IND_COLUMNS
Displays information about the indexed columns of the current user.

Table 3-173 MY_IND_COLUMNS columns


No. Column Name Data Type Description

0 INDEX_NAME VARCHAR(64 Index name


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 219


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 COLUMN_POSITI BINARY_INTEGE Column position


ON R

4 COLUMN_LENGT BINARY_INTEGE Column length


H R

3.3.44 MY_IND_PARTITIONS
Displays the information about the partition indexes of the current user.

Table 3-174 MY_IND_PARTITIONS columns


No Column Name Data Type Description
.

0 INDEX_NAME VARCHAR(64 Index name


BYTE)

1 COMPOSITE CHAR(2 BYTE) Whether the partition within the index is


a composite partition. Values are YES
and NO.

2 PARTITION_NA VARCHAR(64 Name of the partition within the index


ME BYTE)

3 PARTITION_POS BINARY_INTEG Subscript of the partition within the


ITION ER index, starting from 1

4 STATUS CHAR(6 BYTE) Index status

5 PCT_FREE BINARY_INTEG Percentage of minimum reserved space


ER for future update operations on a page

6 INI_TRANS BINARY_INTEG Number of ITL entries initially allocated


ER to a page

7 MAX_TRANS BINARY_INTEG Maximum number of ITL entries on a


ER page

8 BLEVEL BINARY_INTEG Index tree level


ER

9 LEAF_BLOCKS BINARY_INTEG Number of leaf node pages


ER

10 DISTINCT_KEYS BINARY_INTEG Number of distinct keys


ER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 220


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No Column Name Data Type Description


.

11 AVG_LEAF_BLO BINARY_DOUB Average number of leaf nodes for each


CKS_PER_KEY LE key

12 AVG_DATA_BLO BINARY_DOUB Average number of data blocks for each


CKS_PER_KEY LE key

13 CLUSTERING_F NUMBER Compatibility column, with no value


ACTOR

14 NUM_ROWS BINARY_INTEG Number of rows returned when the index


ER partition was analyzed last time

15 SAMPLE_SIZE BINARY_INTEG Number of pages sampled when the


ER index partition was analyzed last time

16 LAST_ANALYZE DATE Time point when the index partition was


D analyzed last time

3.3.45 MY_IND_STATISTICS
Displays statistics about partitioned indexes owned by the current user.

Table 3-175 MY_IND_STATISTICS columns


No. Column Name Data Type Description

0 INDEX_NAME VARCHAR(6 Index name


4 BYTE)

1 TABLE_OWNER VARCHAR(6 Owner of the indexed table


4 BYTE)

2 TABLE_NAME VARCHAR(6 Name of the indexed table


4 BYTE)

3 PARTITION_NAME VARCHAR(6 Name of the index partition


4 BYTE)

4 PARTITION_POSITIO NUMBER Position of the index partition, starting


N from 1

5 OBJECT_TYPE CHAR(9 Type of the object corresponding to the


BYTE) index. Values are INDEX and
PARTITION.

6 BLEVEL BINARY_IN Index tree level


TEGER

7 LEAF_BLOCKS BINARY_IN Number of leaf node pages


TEGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 221


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 DISTINCT_KEYS BINARY_IN Number of distinct keys


TEGER

9 AVG_LEAF_BLOCKS BINARY_DO Average number of leaf nodes for each


_PER_KEY UBLE key

10 AVG_DATA_BLOCKS BINARY_DO Average number of data blocks for


_PER_KEY UBLE each key

11 CLUSTERING_FACT NUMBER Compatibility column, with no value


OR

12 NUM_ROWS BINARY_IN Number of rows returned when the


TEGER index partition was analyzed last time

13 SAMPLE_SIZE BINARY_IN Number of pages sampled when the


TEGER index partition was analyzed last time

14 LAST_ANALYZED TIMESTAM Time point when the index partition


P(6) was analyzed last time

3.3.46 MY_JOBS
Displays information about all jobs owned by the current user.

Table 3-176 MY_JOBS columns


No. Column Name Data Type Description

0 JOB BINARY_BIGINT Job ID

1 LOG_USER VARCHAR(64 User who submits


BYTE) the job

2 PRIV_USER VARCHAR(64 User granted with


BYTE) the job permission

3 SCHEMA_USER VARCHAR(64 User who performs


BYTE) syntax analysis on
the job

4 LAST_DATE DATE Time when the job


was successfully
executed last time

5 LAST_SEC VARCHAR(48 Timestamp of the


BYTE) last successful job
(including the hour,
minute, and second
information)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 222


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 THIS_DATE DATE Time when the


running job was
started

7 THIS_SEC VARCHAR(48 Timestamp of the


BYTE) running job start
(including the hour,
minute, and second
information)

8 NEXT_DATE DATE Time when the


scheduled job will
be executed next
time

9 NEXT_SEC VARCHAR(48 Time when the


BYTE) scheduled job will
be executed next
time
(including the hour,
minute, and second
information)

10 BROKEN CHAR(1 BYTE) Status (blocked or


not)

11 INTERVAL_TIME VARCHAR(200 Expression for


BYTE) calculating the next
time for job running

12 FAILURES BINARY_INTEGE Number of times the


R job consecutively
fails

13 WHAT VARCHAR(4000 PL/SQL block to be


BYTE) executed in the job

14 CREATE_DATE DATE Job creation time

3.3.47 MY_OBJECTS
Displays information about all objects owned by the current user.

Table 3-177 MY_OBJECTS columns


No. Column Name Data Type Description

0 OBJECT_NAME VARCHAR( Object name


128 BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 223


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 SUBOBJECT_N VARCHAR( Sub-object name


AME 64 BYTE)

2 OBJECT_ID BINARY_BI Object ID


GINT

3 OBJECT_TYPE VARCHAR( Object type. Values are:


15 BYTE) l SYNONYM
l SEQUENCE
l PROCEDURE
l FUNCTION
l DYNAMIC VIEW
l VIEW
l INDEX
l RECYCLED INDEX
l TABLE
l RECYCLED TABLE
l TRIGGER

4 CREATED DATE Object creation time

5 LAST_DDL_TI DATE Time when the object was updated in a DC


ME last time

6 STATUS CHAR(7 Object status. Values are:


BYTE) l INVALID
l VALID
l UNKNOWN

7 TEMPORARY VARCHAR( Whether the object is temporary (that is, the


1 BYTE) session is used only for the current object).
Values are:
l Y (temporary)
l N (common)

3.3.48 MY_PART_COL_STATISTICS
Displays statistics about the columns of partitioned tables owned by the current user.

Table 3-178 MY_PART_COL_STATISTICS columns

No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 224


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

4 LOW_VALUE VARCHAR(4000 Minimum value in


BYTE) the column

5 HIGH_VALUE VARCHAR(4000 Maximum value in


BYTE) the column

6 DENSITY BINARY_DOUBLE Density of the


column

7 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

8 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

9 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

10 LAST_ANALYZED DATE Time when statistics


were collected last
time

11 AVG_COL_LEN NUMBER Compatibility


column, with no
value

12 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.49 MY_PART_KEY_COLUMNS
Displays information about the partition columns for partitioned tables owned by the current
user.

Table 3-179 MY_PART_KEY_COLUMNS columns


No. Column Name Data Type Description

0 NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 225


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

2 COLUMN_NAME VARCHAR(64 Column name


BYTE)

3 COLUMN_POSITI BINARY_BIGINT Position of the


ON column within the
partition key

3.3.50 MY_PART_STORE
Displays information about the tablespaces corresponding to the STORE clause used for
interval partitioned tables owned by the user.

Table 3-180 MY_PART_STORE columns

No. Column Name Data Type Description

0 NAME VARCHAR(64 Object name


BYTE)

1 OBJECT_TYPE CHAR(5 BYTE) Object type, always


TABLE

2 POSITION BINARY_INTEGE Tablespace position


R

3 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

3.3.51 MY_PART_TABLES
Displays information about the partitioned tables owned by the current user.

Table 3-181 MY_PART_TABLES columns

No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Name of the


BYTE) partitioned table

1 PARTITIONING_T CHAR(7 BYTE) Partitioning type of


YPE the partitioned table.
Values are
INVALID,
RANGE, LIST, and
HASH.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 226


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 PARTITION_COU BINARY_INTEGE Number of partitions


NT R in the table

3 PARTITIONING_K BINARY_INTEGE Number of columns


EY_COUNT R in the partition key

4 DEF_TABLESPAC VARCHAR(64 Default tablespace


E_NAME BYTE)

5 INTERVAL VARCHAR(1000 Partition boundary


BYTE) string

6 STATUS CHAR(5 BYTE) Status of the


partitioned table

3.3.52 MY_PROCEDURES
Displays stored procedures owned by the current user. The stored procedures include general
triggers, UDFs, and stored procedure bodies.

Table 3-182 MY_PROCEDURES columns


No. Column Name Data Type Description

0 OBJECT_NAME VARCHAR(128 Object name


BYTE)

1 PROCEDURE_NA VARCHAR(128 Name of the


ME BYTE) package or a specific
type of the
subprogram

2 OBJECT_ID BINARY_BIGINT Object ID

3 SUBPROGRAM_I BINARY_INTEGE Unique subprogram


D R identifier

4 OVERLOAD VARCHAR2(40 Unique overload


BYTE) identifier

5 OBJECT_TYPE VARCHAR2(19 Object type name


BYTE)

6 AGGREGATE VARCHAR2(3 Whether the


BYTE) procedure is an
aggregate function

7 PIPELINED VARCHAR2(3 Whether the


BYTE) procedure is a
pipelined table
function

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 227


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 SOURCE CLOB Source code

9 STATUS VARCHAR(7 Compilation status.


BYTE) 0: invalid; 1: valid;
2: unknown

3.3.53 MY_ROLE_PRIVS
Displays information about roles granted to the current user.

Table 3-183 MY_ROLE_PRIVS columns


No. Column Name Data Type Description

0 USERNAME VARCHAR(64 Username


BYTE)

1 GRANTED_ROLE VARCHAR(64 Permission


BYTE)

2 ADMIN_OPTION CHAR(3 BYTE) Whether the user has


the right to grant
permissions

3.3.54 MY_SEGMENTS
Displays information about the storage allocated for all tables, indexes, and LOBs owned by
the current user.

Table 3-184 MY_SEGMENTS columns


No. Column Name Data Type Description

0 SEGMENT_NAME VARCHAR(133 Segment name


BYTE)

1 PARTITION_NAM VARCHAR(145 Partition name


E BYTE)

2 SEGMENT_TYPE CHAR(5 BYTE) Segment type


(TABLE/INDEX/_)

3 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

4 BYTES BINARY_BIGINT Segment size

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 228


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 PAGES BINARY_BIGINT Number of pages in


a segment

6 EXTENTS BINARY_BIGINT Number of extents


allocated to a
segment

3.3.55 MY_SEQUENCES
Displays information about the sequences owned by the current user.

Table 3-185 MY_SEQUENCES columns


No. Column Name Data Type Description

0 SEQUENCE_NAM VARCHAR(64 Sequence name


E BYTE)

1 MIN_VALUE BINARY_BIGINT Minimum value of


the sequence

2 MAX_VALUE BINARY_BIGINT Maximum value of


the sequence

3 INCREMENT_BY BINARY_BIGINT Value by which the


sequence is
incremented

4 CYCLE_FLAG BINARY_INTEGE Whether the


R sequence wraps
around on reaching
the limit

5 ORDER_FLAG BINARY_INTEGE Whether sequence


R numbers are
generated in order

6 CACHE_SIZE BINARY_BIGINT Number of sequence


numbers to cache

7 LAST_NUMBER BINARY_BIGINT Last sequence


number written to
disk

3.3.56 MY_SOURCE
Displays information about all use-defined objects of the current user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 229


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-186 MY_SOURCE columns


No. Column Name Data Type Description

0 NAME VARCHAR(128 Object name


BYTE)

1 TYPE VARCHAR(12 Type of the user-


BYTE) defined object.
Values are:
l TRIGGER
l PROCEDURE
l FUNCTION
l UNDEFINED

2 LINE NUMBER Line number

3 TEXT CLOB Source code

3.3.57 MY_SQL_MAPS
Displays all SQL mapping relationships owned by the current user.

Table 3-187 MY_SQL_MAPS columns


No. Column Name Data Type Description

0 SRC_SQL CLOB Source SQL


statement

1 DEST_SQL CLOB Target SQL


statement

3.3.58 MY_SYNONYMS
Displays synonyms of the current user.

Table 3-188 MY_SYNONYMS columns


No. Column Name Data Type Description

0 SYNONYM_NAM VARCHAR(64 Name of the


E BYTE) synonym to which
the column belongs

1 TABLE_OWNER VARCHAR(64 Table name


BYTE)

2 TABLE_NAME VARCHAR(64 Owner of the


BYTE) column

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 230


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.3.59 MY_SYS_PRIVS
Displays information about system permissions granted to the current user.

Table 3-189 MY_SYS_PRIVS columns

No. Column Name Data Type Description

0 USERNAME VARCHAR(64 Username


BYTE)

1 PRIVILEGE CHAR(28 BYTE) Permission

2 ADMIN_OPTION CHAR(3 BYTE) Whether the user has


the permission
(YES/NO)

3.3.60 MY_TABLES
Displays information about the tables owned by the current user.

Table 3-190 MY_TABLES columns

No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 TABLE_ID BINARY_INTEGE Table ID


R

2 TABLESPACE_NA VARCHAR(64 Name of the


ME BYTE) tablespace
containing the table

3 COLUMN_COUNT BINARY_INTEGE Number of table


R columns

4 INDEX_COUNT BINARY_INTEGE Number of table


R indexes

5 PARTITIONED CHAR(1 BYTE) Whether the table is


a partitioned table

6 CREATED_TIME DATE Time when the table


was created

7 LAST_DDL_TIME DATE Time when the table


was modified last
time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 231


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 PCT_FREE BINARY_INTEGE Minimum


R percentage of free
space in a block

9 INI_TRANS BINARY_INTEGE Initial size of the


R transaction table in a
block header

10 MAX_TRANS BINARY_INTEGE Maximum size of


R the transaction table
in a block header

11 BYTES BINARY_BIGINT Table size

12 PAGES BINARY_BIGINT Number of pages


occupied by the
table

13 EXTENTS BINARY_BIGINT Number of pages in


each automatic
extension

14 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

15 BLOCKS BINARY_INTEGE Number of data


R blocks in the table

16 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

17 AVG_SPACE NUMBER Compatibility


column, with no
value

18 CHAIN_CNT NUMBER Compatibility


column, with no
value

19 AVG_ROW_LEN BINARY_BIGINT Average row length

20 SAMPLE_SIZE BINARY_INTEGE Sample size


R

21 LAST_ANALYZED TIMESTAMP(6) Time when the table


was analyzed last
time

22 STATUS CHAR(5 BYTE) Whether the table is


valid

23 TEMPORARY CHAR(1 BYTE) Whether the table is


temporary

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 232


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

24 APPENDONLY CHAR(1 BYTE) Whether automatic


extension is enabled

25 TABLE_TYPE CHAR(12 BYTE) Table type. Values


are:
HEAP: ordinary
table
IOT: index-
organized table
TRANS_TEMP:
transaction-level
temporary table
SESSION_TEMP:
session-level
temporary table
EXTERNAL:
external table
NOLOGGING:
NOLOGGING table

26 CR_MODE CHAR(4 BYTE) MVCC mode of the


table. Values are:
l ROW: row-level
MVCC
l PAGE: page-
level MVCC

3.3.61 MY_TAB_COLS
Displays information about the columns of tables owned by the current user.

Table 3-191 MY_TAB_COLS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 COLUMN_NAME VARCHAR(64 Column name


BYTE)

2 DATA_TYPE VARCHAR(64 Column data type


BYTE)

3 DATA_LENGTH BINARY_INTEGE Column length


R

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 233


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 DATA_PRECISION BINARY_INTEGE Column precision


R

5 DATA_SCALE BINARY_INTEGE Column scale


R

6 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

7 COLUMN_ID BINARY_INTEGE Column ID


R

8 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

9 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

10 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

11 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

12 CHAR_LENGTH BINARY_INTEGE Column size (byte)


R when this column is
of the CHAR type.
For other data types,
the value is 0.

13 CHAR_USED VARCHAR(1 Whether


BYTE) CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C)

14 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.62 MY_TAB_COLUMNS
Displays details about the columns of tables and views owned by the current user.

Table 3-192 MY_TAB_COLUMNS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 234


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 COLUMN_NAME VARCHAR(128 Column name


BYTE)

2 DATA_TYPE VARCHAR(64 Column data type


BYTE)

3 DATA_LENGTH BINARY_INTEGE Column length


R

4 DATA_PRECISION BINARY_INTEGE Column precision


R

5 DATA_SCALE BINARY_INTEGE Column scale


R

6 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

7 COLUMN_ID BINARY_INTEGE Column ID


R

8 DATA_DEFAULT VARCHAR(1024 Default value for the


BYTE) column

9 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

10 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

11 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

12 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

13 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

14 CHAR_LENGTH BINARY_INTEGE Column size in bytes


R when this column is
of the CHAR data
type. For other data
types, the value is 0.

15 CHAR_USED CHAR(1 BYTE) Whether


CHAR_LENGTH
uses BYTE length
semantics (B) or
CHAR length
semantics (C). Its
value is always B
(BYTE) in GaussDB
100.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 235


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

16 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

17 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

18 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

19 AUTO_INCREME CHAR(1 BYTE) Whether the column


NT is an auto-increment
column. Values are:
Y
N

3.3.63 MY_TAB_COL_STATISTICS
Displays statistics about the columns of tables owned by the current user.

Table 3-193 MY_TAB_COL_STATISTICS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 COLUMN_NAME VARCHAR(64 Column name


BYTE)

2 NUM_DISTINCT BINARY_INTEGE Number of distinct


R values in the column

3 LOW_VALUE VARCHAR(64 Minimum value in


BYTE) the column

4 HIGH_VALUE VARCHAR(64 Maximum value in


BYTE) the column

5 DENSITY BINARY_DOUBLE Density of the


column

6 NUM_NULLS BINARY_INTEGE Number of NULL


R values in the column

7 NUM_BUCKETS BINARY_INTEGE Number of buckets


R in the histogram for
the column

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 236


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

9 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

10 AVG_COL_LEN NUMBER Compatibility


column, with no
value

11 HISTOGRAM VARCHAR(64 Histogram type


BYTE)

3.3.64 MY_TAB_COMMENTS
Displays information about comments on the tables owned by the current user.

Table 3-194 MY_TAB_COMMENTS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 TABLE_TYPE CHAR(5 BYTE) Enumerated type, a


table or view

2 COMMENTS VARCHAR(4000) Column comment

3.3.65 MY_TAB_DISTRIBUTE
Displays the table distribution information of the current user. (If GaussDB 100 is deployed in
distributed mode, you can query this view for data. In standalone deployment, this view has
no data.)

Table 3-195 MY_TAB_DISTRIBUTE columns


No. Column Name Data Type Description

0 OWNER VARCHAR(64 Username


BYTE)

1 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 237


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 DIST_INFO VARCHAR(1024 Table distribution


BYTE) information

3.3.66 MY_TAB_MODIFICATIONS
Displays table modifications made by the current user.

Table 3-196 MY_TAB_MODIFICATIONS columns

No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(6 Table name


4 BYTE)

1 PARTITION_NAM VARCHAR(6 Partition name


E 4 BYTE)

2 SUBPARTITION_N VARCHAR(6 Subpartition name


AME 4 BYTE)

3 INSERTS BINARY_INT Number of inserted rows. It will be


EGER cleared after the ANALYZE
operation.

4 UPDATES BINARY_INT Number of updated rows. It will be


EGER cleared after the ANALYZE
operation.

5 DELETES BINARY_INT Number of deleted rows. It will be


EGER cleared after the ANALYZE
operation.

6 TIMESTAMP TIMESTAM Timestamp of table modification


P(6) last time

7 DROP_SEGMENT BINARY_INT Number of segments dropped since


S EGER the last analysis operation

1. When STATISTICS_LEVEL, statistics collection level, is set to BASIC, table


modification information is not collected.
2. The table modification information is not synchronized in this view in real time.
According to system settings, there is at least a 15-minute delay before the
synchronization.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 238


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.3.67 MY_TAB_PARTITIONS
Displays information about partitions in the tables owned by the current user.

Table 3-197 MY_TAB_PARTITIONS columns


No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

1 COMPOSITE VARCHAR(2 Whether the table is


BYTE) composite-
partitioned

2 PARTITION_NAM VARCHAR(64 Partition name


E BYTE)

3 SUBPARTITION_C NUMBER Number of


OUNT subpartitions in the
partition

4 HIGH_VALUE VARCHAR(4000 Partition boundary


BYTE) string

5 HIGH_VALUE_LE NUMBER Length of a partition


NGTH boundary string

6 PARTITION_POSIT BINARY_INTEGE Table partition ID


ION R

7 TABLESPACE_NA VARCHAR(64 Table partition name


ME BYTE)

8 INTERVAL CHAR(1 BYTE) Whether the


partition is an
interval partition
Values are Y and N.

9 PCT_FREE BINARY_INTEGE Reserved space


R

10 PCT_USED NUMBER Used space

11 INI_TRANS BINARY_INTEGE Initial number of


R transactions

12 MAX_TRANS NUMBER Maximum number


of transactions

13 INITIAL_EXTENT NUMBER Reserved system


interface

14 NEXT_EXTENT NUMBER Reserved system


interface

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 239


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

15 MIN_EXTENT NUMBER Reserved system


interface

16 MAX_EXTENT NUMBER Reserved system


interface

17 MAX_SIZE NUMBER Reserved system


interface

18 PCT_INCREASE NUMBER Reserved system


interface

19 FREELISTS NUMBER Reserved system


interface

20 FREELIST_GROU NUMBER Reserved system


PS interface

21 LOGGING VARCHAR(7 Reserved system


BYTE) interface

22 COMPRESSION VARCHAR(8 Reserved system


BYTE) interface

23 COMPRESS_FOR VARCHAR(18 Reserved system


BYTE) interface

24 NUM_ROWS BINARY_INTEGE Reserved system


R interface

25 BLOCKS BINARY_INTEGE Reserved system


R interface

26 EMPTY_BLOCKS BINARY_INTEGE Reserved system


R interface

27 AVG_SPACE NUMBER Reserved system


interface

28 CHAIN_CNT NUMBER Reserved system


interface

29 AVG_ROW_LEN BINARY_INTEGE Reserved system


R interface

30 SAMPLE_SIZE BINARY_INTEGE Reserved system


R interface

31 LAST_ANALYZED DATE Reserved system


interface

32 BUFFER_POOL VARCHAR(7 Reserved system


BYTE) interface

33 GLOBAL_STATS VARCHAR(3 Reserved system


BYTE) interface

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 240


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

34 USER_STATS VARCHAR(3 Reserved system


BYTE) interface

3.3.68 MY_TAB_PRIVS
Displays information about permissions to the tables owned by the current user.

Table 3-198 MY_TAB_PRIVS columns

No. Column Name Data Type Description

0 GRANTEE VARCHAR(64 Name of the user to


BYTE) whom the
permission is
granted

1 OWNER VARCHAR(64 Object owner


BYTE)

2 OBJECT_NAME VARCHAR(64 Object name


BYTE)

3 OBJECT_TYPE CHAR(9 BYTE) Object type

4 PRIVILEGE CHAR(10 BYTE) Permission

5 GRANTABLE CHAR(3) Whether the current


user can grant the
object permission to
another user or role.
Values are:
YES
NO

3.3.69 MY_TAB_STATISTICS
Displays the table statistics of the current user.

The collection will be triggered by the analyze table table_name compute statistics
command, and all statistics of a table will be collected.

Table 3-199 MY_TAB_STATISTICS columns

No. Column Name Data Type Description

0 TABLE_NAME VARCHAR(64 Table name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 241


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 PARTITION_NAM VARCHAR(64 Partition name. If


E BYTE) the table is not a
partitioned table,
this column will
display only NULL.

2 PARTITION_POSIT NUMBER Partitioned index,


ION starting from 1. If
the table is not a
partitioned table,
this column will
display only NULL.

3 OBJECT_TYPE CHAR(9 BYTE) Object type. Values


are TABLE and
PARTITION.

4 NUM_ROWS BINARY_INTEGE Number of rows in


R the table

5 BLOCKS BINARY_INTEGE Number of blocks in


R the table

6 EMPTY_BLOCKS BINARY_INTEGE Number of empty


R blocks in the table

7 AVG_SPACE NUMBER Compatibility


column, with no
value

8 CHAIN_CNT NUMBER Compatibility


column, with no
value

9 AVG_ROW_LEN BINARY_BIGINT Average row length

10 AVG_SPACE_FRE NUMBER Compatibility


ELIST_BLOCKS column, with no
value

11 NUM_FREELIST_ NUMBER Compatibility


BLOCKS column, with no
value

12 AVG_CACHED_B NUMBER Compatibility


LOCKS column, with no
value

13 AVG_CACHE_HIT NUMBER Compatibility


_RATIO column, with no
value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 242


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

14 SAMPLE_SIZE BINARY_INTEGE Number of pages for


R resampling in
statistics collection

15 LAST_ANALYZED TIMESTAMP(6) Time when statistics


were collected last
time

3.3.70 MY_TRIGGERS
Displays information about the triggers owned by the current user.

Table 3-200 MY_TRIGGERS columns


No. Column Name Data Type Description

0 TRIGGER_NAME VARCHAR(128 Trigger name


BYTE)

1 TABLE_OWNER VARCHAR(128 Table owner


BYTE)

2 TABLE_NAME VARCHAR(128 Table name


BYTE)

3 SOURCE CLOB Source code

4 STATUS VARCHAR(16 Trigger status


BYTE)

3.3.71 MY_USERS
Displays information about the current user.

Table 3-201 MY_USERS columns


No. Column Name Data Description
Type

0 USERNAME VARCH Username


AR(64
BYTE)

1 USER_ID BINAR User ID


Y_INTE
GER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 243


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Description


Type

2 ACCOUNT_STAT CHAR( User status. Values are:


US 30 OPEN, EXPIRED, EXPIRED(GRACE),
BYTE) LOCKED(TIMED), EXPIRED &
LOCKED(TIMED), EXPIRED(GRACE) &
LOCKED(TIMED), LOCKED, EXPIRED &
LOCKED, EXPIRED(GRACE) & LOCKED

3 LOCK_DATE DATE Time when the user is locked

4 EXPIRY_DATE DATE Time when the user password expires

5 DEFAULT_TABLE VARCH Default tablespace name


SPACE AR(64
BYTE)

6 TEMPORARY_TA VARCH Temporary tablespace name


BLESPACE AR(64
BYTE)

7 CREATED DATE Time when the user was created

8 INITIAL_RSRC_C CHAR( Compatibility column, SYS_GROUP for user


ONSUMER_GRO 22 SYS and DEFAULT_CONSUMER_GROUP
UP BYTE) for other users

3.3.72 MY_VIEWS
Displays information about the views owned by the current user.

Table 3-202 MY_VIEWS columns

No. Column Name Data Type Description

0 VIEW_NAME VARCHAR(64 View name


BYTE)

1 VIEW_TYPE CHAR(7 BYTE) View type,


supporting only
NORMAL currently

2 COLUMN_COUNT BINARY_INTEGE Number of columns


R

3 TEXT CLOB View text

4 TEXT_LENGTH BINARY_INTEGE Length of the view


R text

5 CREATED_TIME DATE Time when the view


was created

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 244


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 LAST_DDL_TIME DATE Time when the view


was updated last
time in the DC

3.3.73 MY_VIEW_COLUMNS
Displays information about the columns of views owned by the current user.

Table 3-203 MY_VIEW_COLUMNS columns

No. Column Name Data Type Description

0 VIEW_NAME VARCHAR(64 View name


BYTE)

1 COLUMN_ID BINARY_INTEGE Column ID


R

2 COLUMN_NAME VARCHAR(128 Column name


BYTE)

3 DATA_TYPE VARCHAR(64 Column data type


BYTE)

4 DATA_LENGTH BINARY_INTEGE Column length


R

5 DATA_PRECISION BINARY_INTEGE Precision of a


R NUMBER type
column

6 DATA_SCALE BINARY_INTEGE Scale of a


R NUMBER type
column

7 NULLABLE CHAR(1 BYTE) Whether the column


allows for NULL

3.4 Dynamic Performance Views


Table 3-204 lists the dynamic performance views supported by GaussDB 100.

Table 3-204 Dynamic performance views

View Name Definition

NLS_SESSION_PARAMETE Displays the NLS parameters of a session.


RS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 245


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

DV_ALL_TRANS Displays information about all transactions.

DV_ARCHIVED_LOGS Displays information about archived logs.

DV_ARCHIVE_DEST_STAT Displays information about archived log destinations.


US

DV_ARCHIVE_GAPS Displays information about archive gaps in a standby


database.

DV_ARCHIVE_THREADS Displays the status of various archive processes.

DV_BACKUP_PROCESSES Displays the status of various backup processes for the


current instance.

DV_BUFFER_POOLS Displays information about all buffer pools available for


the instance.

DV_BUFFER_POOL_STATS Displays statistics about all buffer pools available for


the instance.

DV_CONTROL_FILES Displays basic information about control files in the


current database.

DV_DATABASE Displays basic information about the current database.

DV_DATA_FILES Displays information about data files in the current


database.

DV_OBJECT_CACHE Displays information about cached objects in the current


database.

DV_DC_POOLS Displays information about current DC pools.

DV_DYNAMIC_VIEWS Displays information about dynamic views.

DV_DYNAMIC_VIEW_COL Displays information about the columns of dynamic


S views.

DV_FREE_SPACE Displays the free partitions in all tablespaces in the


database.

DV_HA_SYNC_INFO Displays information including the primary/standby


connection and log sending status on the primary node;
or information including the standby/cascaded standby
connection and log sending status on the standby node.

DV_HBA Displays the configurations of the user whitelist.

DV_INSTANCE Displays information about database instances.

DV_RUNNING_JOBS Displays all running job sessions.

DV_LATCHS Displays information about current structure locks.

DV_LIBRARY_CACHE Displays the management information about SQL


statements in a shared pool.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 246


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

DV_LOCKS Displays information about current lock resources.

DV_LOCKED_OBJECTS Displays information about locked objects.

DV_LOG_FILES Displays information about current log files.

DV_LONG_SQL Displays logs of long SQL statements

DV_STANDBYS Displays the status of threads for standby databases.

DV_ME Displays information about current sessions.

DV_OPEN_CURSORS Displays information about the status of currently


opened cursors.

DV_PARAMETERS Displays the configuration items of the current database.

DV_PL_MANAGER Displays information about stored procedure loading to


memory.

DV_PL_REFSQLS Displays information about the SQL statements


associated with PL after stored procedure loading to
memory.

DV_REACTOR_POOLS Displays information about connection pools and the


corresponding work thread pools.

DV_REPL_STATUS Displays information about the communication status


between primary and standby databases.

DV_RESOURCE_MAP Displays information about resource views in the


database.

DV_SEGMENT_STATS Displays information about the usage of objects, such as


heap index, in the database.

DV_SESSIONS Displays information about current sessions.

DV_SESSION_EVENTS Displays information about the wait events for current


sessions.

DV_SESSION_SHARED_LO Displays information about all session-level shared


CKS advisory locks in use.

DV_SESSION_WAITS Displays information about the wait events for current


sessions.

DV_GMA Displays information about the memory that is applied


for.

DV_GMA_STATS Displays the statistics items of the SGA memory.

DV_SPINLOCKS Displays information about the usage of spinlocks on


current sessions.

DV_SQLS Displays information about the execution of SQL DML


statements.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 247


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

View Name Definition

DV_SQL_POOL Displays information about SQL pool usage in the


current system.

DV_SYS_STATS Displays statistics about the current system.

DV_SYSTEM Displays information about CPU and memory usage in


the current OS.

DV_SYS_EVENTS Displays information about events in the current system.

DV_TABLESPACES Displays information about current tablespaces.

DV_TEMP_POOLS Displays information about current temporary pools.

DV_TEMP_UNDO_SEGME Displays the status of all temporary undo segment


NT queues.

DV_TRANSACTIONS Displays information about transactions.

DV_UNDO_SEGMENTS Displays the status of all undo segment queues.

DV_USER_ADVISORY_LO Displays information about all session-level advisory


CKS locks in use.

DV_USER_ASTATUS_MAP Displays information about the views of the database


user status type.

DV_USER_PARAMETERS Displays the configuration items of the current database.


This view is accessible to common users.

DV_VERSION Displays software versions.

DV_VM_FUNC_STACK Displays the function stack information when the VM is


not released.

DV_WAIT_STATS Displays statistics about all wait events when there is a


large number of buffer busy waits events.

DV_XACT_LOCKS Displays information about all transaction-level


exclusive advisory locks in use.

DV_XACT_SHARED_LOCK Displays information about all transaction-level shared


S advisory locks in use.

3.4.1 NLS_SESSION_PARAMETERS
Displays the NLS parameters of a session.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 248


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-205 NLS_SESSION_PARAMETERS columns

No. Column Name Data Type Description

0 PARAMETER VARCHAR(30 Parameter name


BYTE)

1 VALUE VARCHAR(60 Parameter value


BYTE)

3.4.2 DV_ALL_TRANS
Displays information about all transactions.

Table 3-206 DV_ALL_TRANS columns

No. Column Data Type Description


Name

0 SEG_ID BINARY_INTE Transaction segment ID


GER

1 SLOT BINARY_INTE Transaction slot number in pages


GER

2 XNUM BINARY_INTE Transaction version number


GER

3 SCN BINARY_BIGI Transaction SCN


NT

4 SID BINARY_INTE Transaction session ID


GER

5 STATUS VARCHAR(64 Transaction status


BYTE)

6 UNDO_COU BINARY_INTE Number of undo pages used by the


NT GER transaction

7 UNDO_FIRS BINARY_INTE First undo page used by the transaction


T GER

8 UNDO_LAS BINARY_INTE Last undo page used by the transaction


T GER

9 TXN_PAGEI BINARY_INTE ID of the page where the transaction is


D GER located

3.4.3 DV_ARCHIVED_LOGS
Displays information about archived logs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 249


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-207 DV_ARCHIVED_LOGS columns


No. Column Name Data Type Description

0 RECID BINARY_INTEGE Archived log ID


R

1 STAMP BINARY_INTEGE Archived log


R timestamp

2 NAME VARCHAR(256 Archive log path


BYTE)

3 DEST_ID BINARY_INTEGE Original destination


R from which the
archived log is
generated

4 THREAD# BINARY_INTEGE Redo thread number


R

5 SEQUENCE# BINARY_INTEGE Redo log sequence


R number

6 RESETLOGS_CHA BINARY_INTEGE Number of database


NGE# R RESETLOGS
changes when the
log is written

7 RESETLOGS_TIM DATE Time of the database


E RESETLOGS
changes when the
log is written

8 RESETLOGS_ID BINARY_INTEGE ID of reset logs


R associated with the
archived redo log

9 FIRST_CHANGE# BINARY_INTEGE First change in the


R archived log

10 FIRST_TIME DATE Timestamp of the


first change

11 NEXT_CHANGE# BINARY_INTEGE First change in the


R next log

12 NEXT_TIME DATE Timestamp of the


next change

13 BLOCKS BINARY_INTEGE Size of the archived


R log (unit: block)

14 BLOCK_SIZE BINARY_INTEGE Size of the blocks


R for the archived log

15 CREATOR VARCHAR(8 Creator of the


BYTE) archive log

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 250


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

16 REGISTRAR VARCHAR(8 Entry registration.


BYTE) The interface is
reserved by the
system.

17 STANDBY_DEST VARCHAR(4 Whether the entry is


BYTE) an ARCHIVELOG
destination
(YES/NO)

18 ARCHIVED VARCHAR(4 Whether the online


BYTE) redo log is archived
(YES) or whether
RMAN only
inspects the log and
creates a record for
future application of
redo logs during
restoration (NO)

19 APPLIED VARCHAR(4 Whether the


BYTE) archived redo log
has been applied to
its corresponding
standby database.
The value is always
NO for local
destinations.

20 DELETED VARCHAR(4 Whether an RMAN


BYTE) DELETE command
has physically
deleted the archived
log file from disk
and logically
removed it from the
control file of the
target database and
from the restoration
directory

21 STATUS VARCHAR(4 Status of the


BYTE) archived log

22 COMPLETION_TI DATE Time when the


ME archiving is
completed

23 DICTIONARY_BE VARCHAR(4 Whether the log


GIN BYTE) contains the start of
a LogMiner
dictionary
(YES/NO)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 251


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

24 DICTIONARY_EN VARCHAR(4 Whether the log


D BYTE) contains the end of a
LogMiner dictionary
(YES/NO)

25 END_OF_REDO VARCHAR(4 Whether the


BYTE) archived redo log
contains the end of
all redo information
from the primary
database (YES/NO)

26 BACKUP_COUNT BINARY_INTEGE Number of times


R this file has been
backed up. Values
range from 0 to 15.
If the file has been
backed up more than
15 times, the value
remains 15.

27 ARCHIVAL_THRE BINARY_INTEGE Redo thread number


AD# R of the instance that
performs the
archiving operation.
This column differs
from the
THREAD# column
only when a closed
thread is archived by
another instance.

28 ACTIVATION# BINARY_INTEGE Number assigned to


R the database
instance

29 IS_RECOVERY_D VARCHAR(4 Whether the file is


EST_FILE BYTE) created in the flash
restoration area
(YES/NO)

30 COMPRESSED VARCHAR(4 Reserved for


BYTE) internal use

31 FAL VARCHAR(4 Whether the


BYTE) archived log is
generated as the
result of a FAL
request (YES/NO)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 252


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

32 END_OF_REDO_T VARCHAR(10 Whether the


YPE BYTE) archived redo log
contains the end of
all redo information
from the primary
database (YES/NO).
The interface is
reserved by the
system.

33 BACKED_BY_VSS VARCHAR(4 Whether the file has


BYTE) been backed up by
Volume Shadow
Copy Service (VSS).
This column is
reserved for internal
use.

34 CON_ID BINARY_INTEGE ID of the container


R to which the data
belongs. The
interface is reserved
by the system.

3.4.4 DV_ARCHIVE_DEST_STATUS
Displays information about archived log destinations.

Table 3-208 DV_ARCHIVE_DEST_STATUS columns


No. Column Name Data Type Description

0 DEST_ID BINARY_IN Archive destination ID (0–9)


TEGER

1 DEST_NAME VARCHAR(2 Archive destination name


56 BYTE)

2 STATUS VARCHAR(9 Destination status (VALID/INACTIVE)


BYTE)

3 TYPE VARCHAR(3 Archive destination database type


0 BYTE) (PHYSICAL)

4 DATABASE_MOD VARCHAR(1 Archive mode on the destination database


E 1 BYTE) (READ-ONLY/READ-WRITE)

5 PROTECTION_MO VARCHAR(2 Whether the database is protected


DE 0 BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 253


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 DESTINATION VARCHAR(2 Destination path


56 BYTE)

7 DB_UNIQUE_NA VARCHAR(3 Instance name


ME 0 BYTE)

8 SYNCHRONIZATI VARCHAR(2 Synchronization status. Values are:


ON_STATUS 0 BYTE) l CHECK CONFIGURATION:
Synchronization with the destination is
not possible because this database is
either not in MAXIMUM
PROTECTION or MAXIMUM
AVAIALBILITY mode, or the
LOG_ARCHIVE_DEST_n parameter
has not been configured with the SYNC
attribute.
l CHECK NETWORK: The primary
node cannot connect to its standby node.
l OK: The destination is synchronized
with the primary database.
l NOT AVAILABLE: Synchronization
status is not available (displayed on
standby nodes).

9 SYNCHRONIZED VARCHAR(8 Whether the destination has been


BYTE) synchronized (YES/NO/UNKNOWN)

3.4.5 DV_ARCHIVE_GAPS
Displays information about archive gaps in a standby database.

Table 3-209 DV_ARCHIVE_GAPS columns


No. Column Name Data Type Description

0 THREAD# BINARY_INTEGE Thread ID. The


R value is 1.

1 LOW_SEQUENCE VARCHAR(32 Replay point of the


# BYTE) standby node,
including resetid and
asn. For example,
1_101.

2 HIGH_SEQUENCE VARCHAR(32 The latest archive


# BYTE) file on the standby
node. For example,
2_10.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 254


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.6 DV_ARCHIVE_THREADS
Displays the status of various archive processes.

Table 3-210 DV_ARCHIVE_THREADS columns


No. Column Name Data Type Description

0 PROCESS BINARY_INTEGE ID of the archive


R process for the
instance (0–9)

1 STATUS VARCHAR(10 Status of the archive


BYTE) process

2 LOG_SEQUENCE BINARY_INTEGE Sequence number of


R the redo log that is
being archived

3 STATE VARCHAR(4 Keyword of the


BYTE) archive process
(IDLE/BUSY)

4 ROLES VARCHAR(36 Role of the archive


BYTE) process

5 CON_ID BINARY_INTEGE Container ID of the


R archive process

3.4.7 DV_BACKUP_PROCESSES
Displays the status of various backup processes for the current instance.

Table 3-211 DV_BACKUP_PROCESSES columns


No. Colum Data Type Description
n
Name

0 TYPE VARCHAR(64 Backup or restoration


BYTE)

1 PROGR BINARY_INT Backup/Restoration progress


ESS EGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 255


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Colum Data Type Description


n
Name

2 STAGE VARCHAR(64 Backup phase


BYTE) l start: start of a backup
l ctrl file: backup control file
l summary: backup header file
l build files: build files
l data files: backup data files
l log files: backup log files
l end: end of backup

3 STATU VARCHAR(64 Backup/Restoration status (success, processing, or


S BYTE) failed)

4 ERR_N BINARY_INT Error code in backup/restoration


O EGER

5 ERR_M VARCHAR(10 Error information


SG 24 BYTE)

6 TOTAL BINARY_INT Total number of backup/restoration threads


_PROC EGER

7 FREE_P BINARY_INT Number of idle backup/restoration threads


ROC EGER

3.4.8 DV_BUFFER_POOLS
Displays information about all buffer pools available for the instance.

Table 3-212 DV_BUFFER_POOLS columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE Buffer ID
R

1 NAME VARCHAR(64 Buffer name


BYTE)

2 PAGE_SIZE BINARY_INTEGE Number of pages


R occupied for
buffering

3 CURRENT_SIZE BINARY_INTEGE Current buffer size


R

4 BUFFERS BINARY_INTEGE Maximum number


R of buffered pages

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 256


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 FREE BINARY_INTEGE Number of idle


R pages

3.4.9 DV_BUFFER_POOL_STATS
Displays statistics about all buffer pools available for the instance.

Table 3-213 DV_BUFFER_POOL_STATS columns


No. Column Name Data Type Description

0 ID BINARY_INT Buffer pool ID


EGER

1 NAME VARCHAR(6 Buffer pool name


4 BYTE)

2 SET_MSIZE BINARY_INT Total number of pages in


EGER the buffer pool

3 CNUM_REPL BINARY_INT Total number of pages in


EGER the buffer pool LRU queue

4 CNUM_WRITE BINARY_INT Number of dirty pages in


EGER the buffer pool

5 CNUM_FREE BINARY_INT Number of free pages in


EGER the buffer pool

6 CNUM_PINNED BINARY_INT Total number of pinned


EGER and resident pages in the
buffer pool

7 CNUM_RO BINARY_INT Total number of clean


EGER pages in the buffer pool,
excluding pinned and
resident pages

8 OLD_LEN BINARY_INT Length of the cold section


EGER in the buffer pool LRU
queue

9 STATS_LEN BINARY_INT Number of ctrls in the


EGER buffer LRU list of the
statistics

10 RECYCLED BINARY_INT Number of buffer ctrls not


EGER used in the buffer LRU list

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 257


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.10 DV_CONTROL_FILES
Displays basic information about control files in the current database.

Table 3-214 DV_CONTROL_FILES columns


No. Column Name Data Description
Type

0 STATUS VARCHA Whether the file name is valid, INVALID if it is


R(16 invalid and NULL otherwise. GaussDB 100 has
BYTE) no INVALID.

1 NAME VARCHA Control file name (including a full path)


R(256
BYTE)

2 IS_RECOVERY_ VARCHA Whether the file is created in the flashback area.


DEST_FILE R(4 Values are YES and NO. Currently, GaussDB
BYTE) 100 has no YES.

3 BLOCK_SIZE BINARY_ Control file block size


INTEGER

4 FILE_SIZE_BLK BINARY_ Control file size (unit: block).


S INTEGER

NOTE

Currently, the storage engine of GaussDB 100 does not support the function of returning control file
sizes. Therefore, in the current version, the value of FILE_SIZE_BLKS is always 0.

3.4.11 DV_DATABASE
Displays basic information about the current database.

Table 3-215 DV_DATABASE columns


No Column Data Type Description
. Name

0 DBID BINARY_I Database ID, which uniquely identifies a database


NTEGER

1 NAME VARCHA Current database name


R(32
BYTE)

2 STATUS VARCHA Current database status (CLOSED/NOMOUNT/


R(20 CREATING/MOUNT/RECOVERY/
BYTE) INIT_PHASE/WAIT_CLEAN/OPEN)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 258


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No Column Data Type Description


. Name

3 OPEN_STAT VARCHA Database running status (RESTRICT/READ


US R(20 ONLY/READ WRITE/MOUNTED)
BYTE)

4 OPEN_COU BINARY_I Number of times the database is opened


NT NTEGER

5 INIT_TIME DATE Time when the database is created

6 CURRENT_S BINARY_B Database SCN


CN IGINT

7 RCY_POINT VARCHA Restoration information


R(20
BYTE)

8 LRP_POINT VARCHA Least restoration information


R(20
BYTE)

9 CKPT_ID BINARY_B Checkpoint ID


IGINT

10 LSN BINARY_B Redo log sequence number


IGINT

11 LFN BINARY_B Redo log update number


IGINT

12 LOG_COUN BINARY_I Number of redo log files


T NTEGER

13 LOG_FIRST BINARY_I Start file ID of the current redo log


NTEGER

14 LOG_LAST BINARY_I End file ID of the current redo log


NTEGER

15 LOG_FREE_ BINARY_B Size of available log space


SIZE IGINT

16 LOG_MODE VARCHA Logging mode (ARCHIVELOG/


R(30 NOARCHIVELOG)
BYTE)

17 SPACE_COU BINARY_I Number of tablespaces


NT NTEGER

18 DEVICE_CO BINARY_I Number of devices


UNT NTEGER

19 DW_START BINARY_I Start position of dual-write


NTEGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 259


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No Column Data Type Description


. Name

20 DW_END BINARY_I End position of dual-write


NTEGER

21 PROTECTIO VARCHA Database protection mode


N_MODE R(20 (MAXIMUM_PROTECTION/
BYTE) MAXIMUM_AVAILABILITY/
MAXIMUM_PERFORMANCE)

22 DATABASE_ VARCHA Database role (PRIMARY/


ROLE R(30 PHYSICAL_STANDBY/
BYTE) CASCADED_PHYSICAL_STANDBY)

23 DATABASE_ VARCHA Database status (NORMAL/STARTING/


CONDITION R(16 DEMOTING/PROMOTING/FAILOVER
BYTE) PROMOTING/BUILDING/NEED REPAIR/NO
PROCESS/DISCONNECTED)

24 SWITCHOV VARCHA Primary/standby database switchover status (TO


ER_STATUS R(20 PRIMARY/WAIT ROLLBACK/ROLLBACK
BYTE) END/CHECKPOINT END/WAIT SEND
LOGFILE/SEND LOGFILE END/WAIT PEER
PROMOTE/PEER PROMOTE END/PEER
DEMOTE END/ANOTHER RUNNING/NOT
READY/NOT ALLOWED)

25 FAILOVER_ VARCHA Whether the FAILOVER command can be executed


STATUS R(20 (TO PRIMARY/NOT ALLOWED)
BYTE)

26 ARCHIVELO BINARY_I SCN of the end of the last archive


G_CHANGE NTEGER

27 LREP_POIN VARCHA Log point when logical replication is enabled


T R(20
BYTE)

28 LREP_MOD VARCHA Whether logical replication is enabled (ON/OFF)


E R(20
BYTE)

29 OPEN_INCO VARCHA Whether the database consistency is damaged


NSISTENCY R(20 (FALSE or TRUE). Generally, this parameter is set
BYTE) after ALTER DATABAE OPEN IGNORE LOGS
is executed.

3.4.12 DV_DATA_FILES
Displays information about data files in the current database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 260


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-216 DV_DATA_FILES columns


No. Column Name Data Type Description

0 ID BINARY_INT Data file ID


EGER

1 TABLESPACE_I BINARY_INT ID of the tablespace containing the data


D EGER file

2 STATUS VARCHAR(20 Data file status (ONLINE/OFFLINE)


BYTE)

3 TYPE VARCHAR(20 Data file type (FILE/RAW/CFS)


BYTE)

4 FILE_NAME VARCHAR(25 Data file name


6 BYTE)

5 BYTES BINARY_BIGI Data file size


NT

6 AUTO_EXTEN VARCHAR(20 Whether automatic extension is


D BYTE) supported

7 AUTO_EXTEN BINARY_BIGI Automatic extension size


D_SIZE NT

8 MAX_SIZE BINARY_BIGI Maximum size of a file that can be


NT expanded to

9 HIGH_WATER_ BINARY_INT High watermark of the number of used


MARK EGER pages in a file (maximum number of
pages in a data file)

3.4.13 DV_OBJECT_CACHE
Displays information about cached objects in the current database.

Table 3-217 DV_OBJECT_CACHE columns


N Column Data Type Description
o. Name

0 OWNER VARCHA Object owner


R(64
BYTE)

1 NAME VARCHA Object name


R(64
BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 261


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

N Column Data Type Description


o. Name

2 NAMESP VARCHA This is meaningless. Currently, the value is always


ACE R(20 NAMESPACE.
BYTE)

3 TYPE VARCHA Object type (TABLE/DC_DYNAMIC_VIEW/VIEW/


R(32 TRANSACTION TEMP TABLE/SESSION TEMP
BYTE) TABLE/EXTERNAL TABLE)

4 LOADS BOOLEAN Whether the object is in use

5 LOCKS BINARY_I Number of users currently locking this object


NTEGER

6 HASH_V BINARY_I Hash value converted from NAME


ALUE NTEGER

7 LOCK_ VARCHA Object lock mode (IDLE/S/IX/X)


MODE R(20
BYTE)

8 STATUS VARCHA Whether the object DC is valid


R(20
BYTE)

3.4.14 DV_DC_POOLS
Displays information about current DC pools.

Table 3-218 DV_DC_POOLS columns


No. Column Name Data Type Description

0 POOL_OPT_COUNT BINARY_I Maximum number of pages


NTEGER in the DC pool

1 POOL_PAGE_COUN BINARY_I Number of pages occupied


T NTEGER by the DC pool

2 POOL_FREE_PAGE_ BINARY_I Number of available pages in


COUNT NTEGER the DC pool

3 LRU_COUNT BINARY_I Number of table objects in


NTEGER the DC elimination queue

4 LRU_PAGE_COUNT BINARY_I Number of pages occupied


NTEGER by table objects in the DC
elimination queue

5 LRU_LOCKED_COU BINARY_I Number of locked objects in


NT NTEGER the DC elimination queue

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 262


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 LRU_LOCKED_PAG BINARY_I Number of pages occupied


E_COUNT NTEGER by locked objects in the DC
elimination queue

7 LRU_RECYCLABLE BINARY_I Number of table objects that


_COUNT NTEGER can be eliminated in the DC
elimination queue

8 LRU_RECYCLABLE BINARY_I Number of pages occupied


_PAGE_COUNT NTEGER by table objects that can be
eliminated in the DC
elimination queue

3.4.15 DV_DYNAMIC_VIEWS
Displays information about dynamic views.

Table 3-219 DV_DYNAMIC_VIEWS columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE Dynamic view ID


R

1 USER_NAME VARCHAR(64 Dynamic view


BYTE) owner

2 NAME VARCHAR(64 Dynamic view name


BYTE)

3 COLUMN_COUNT BINARY_INTEGE Total number of


R columns in the
dynamic view

3.4.16 DV_DYNAMIC_VIEW_COLS
Displays information about the columns of dynamic views.

Table 3-220 DV_DYNAMIC_VIEW_COLS columns

No. Column Data Type Description


Name

0 USER_NAME VARCHAR(64 Dynamic view owner


BYTE)

1 VIEW_NAME VARCHAR(64 Dynamic view name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 263


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

2 COLUMN_ID BINARY_INTEG ID of a column in the dynamic view


ER

3 COLUMN_NA VARCHAR(64 Name of the column in the dynamic


ME BYTE) view

4 DATA_TYPE VARCHAR(64 Data type of the column in the


BYTE) dynamic view

5 DATA_LENGT BINARY_INTEG Length of the column in the dynamic


H ER view

6 DATA_PRECI BINARY_INTEG Precision of the column in the


SION ER dynamic view

7 DATA_SCALE BINARY_INTEG Scale of the column in the dynamic


ER view

3.4.17 DV_FREE_SPACE
Displays the free partitions in all tablespaces in the database.
When you create a tablespace, querying the DV_FREE_SPACE view may display free
tablespaces with the same size. If you create a table without inserting records in any of the
tablespaces, querying the DV_FREE_SPACE view shows that the sizes of the free
tablespaces remain unchanged.

Table 3-221 DV_FREE_SPACE columns


No. Column Name Data Type Description

0 TABLESPACE_NA VARCHAR(64 Tablespace name


ME BYTE)

1 FILE_ID BINARY_INTEGE File ID


R

2 BLOCK_ID BINARY_INTEGE ID of the start block


R in the free extent

3 BYTES BINARY_BIGINT Size of the free


extent (unit: byte)

4 BLOCKS BINARY_BIGINT Size of the free


extent (unit: block)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 264


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 RELATIVE_FNO BINARY_INTEGE Relative file ID.


R This column is a
compatibility
column and an
equivalent to
FILE_ID.

3.4.18 DV_HA_SYNC_INFO
Displays information including the primary/standby connection and log sending status on the
primary node; or information including the standby/cascaded standby connection and log
sending status on the standby node.

Table 3-222 DV_HA_SYNC_INFO columns


No. Column Name Data Type Description

0 THREAD# BINARY_INTEGE Log sending thread number


R

1 STATUS VARCHAR(20 Log sending thread status.


BYTE) Values are:
l NOT RUNNING: The
corresponding link has not been
used.
l DISCONNECTED: The
corresponding link has been
used but disconnected. The
primary database attempts to
reconnect to the standby
database.
l CONNECTED: The primary
database has connected to the
standby database but is not
ready for sending logs.
l SHIFTING: The primary
database has been ready and
entered the normal log sending
state.

2 LOCAL_HOST VARCHAR(64 Local node IP address


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 265


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 ROLE_VALID VARCHAR(13 Condition for the


BYTE) ARCHIVE_DEST_n parameter
on the local node to take effect.
Values are:
l PRIMARY_ROLE: The
parameter takes effect only
when the local node is primary.
l STANDBY_ROLE: The
parameter takes effect only
when the local node is standby.
l ALL_ROLES: The parameter
takes effect no matter whether
the local node is primary or
standby.

4 NET_MODE VARCHAR(6 Log transmission mode. Values


BYTE) are:
l SYNC: synchronous mode
l ASYNC: asynchronous mode

5 PEER_HOST VARCHAR(64 IP address of the log receiver


BYTE)

6 PEER_PORT BINARY_INTEGE Port number of the log receiver


R

7 LOCAL_SEND_ VARCHAR(128 Local log sending position


POINT BYTE)

8 PEER_FLUSH_P VARCHAR(128 Peer log receiving and flushing-to-


OINT BYTE) disk point

9 PEER_BUILDIN VARCHAR(6 Whether the standby database is


G BYTE) being built

10 LOCAL_LFN BINARY_BIGINT Local log flush number (LFN)

11 LOCAL_LSN BINARY_BIGINT Local log serial number (LSN)

12 PEER_LFN BINARY_BIGINT Peer LFN

13 PEER_LSN BINARY_BIGINT Peer LSN

14 FLUSH_LAG BINARY_BIGINT Delay in receiving logs on the peer


end (unit: ms)
Value -1 indicates that the primary
node has not sent logs to the
standby node. In this case,
FLUSH_LAG is invalid.

15 REPLAY_LAG BINARY_BIGINT Delay in replaying logs on the peer


end (unit: ms)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 266


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.19 DV_HBA
Displays the configurations of the user whitelist.

Table 3-223 DV_HBA columns


No. Column Name Data Type Description

0 TYPE VARCHAR(64 Type ID


BYTE)

1 USER_NAME VARCHAR(64 Username


BYTE)

2 ADDRESS VARCHAR(8000 IP address


BYTE)

3.4.20 DV_INSTANCE
Displays information about database instances.

Table 3-224 DV_INSTANCE columns


No. Column Name Data Type Description

0 INSTANCE_ID BINARY_INTEGE Instance ID


R

1 INSTANCE_NA VARCHAR(20 Instance name


ME BYTE)

2 STATUS VARCHAR(20 Instance status


BYTE)

3 KERNEL_SCN BINARY_BIGINT Instance SCN

4 SHUTDOWN_P VARCHAR(20 Stopped state


HASE BYTE)

5 STARTUP_TIME DATE Instance start time

6 HOST_NAME VARCHAR(64 Name of the node where the


BYTE) instance resides

7 PLATFORM_NA VARCHAR(68 OS of the node where the instance


ME BYTE) resides

3.4.21 DV_RUNNING_JOBS
Displays all running job sessions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 267


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-225 DV_RUNNING_JOBS columns


No. Column Name Data Type Description

0 JOBNO BINARY_BIGINT Job ID

1 SESSION_ID BINARY_INTEGE Session ID


R

2 SERIAL_ID BINARY_INTEGE Session sequence


R number, used to
uniquely identify a
session object

3.4.22 DV_LATCHS
Displays information about current structure locks.

Table 3-226 DV_LATCHS columns


Column Data Type Description
Name

ID BINARY_INTEG Structure lock ID


ER

NAME VARCHAR(64 Structure lock name


BYTE)

GETS BINARY_INTEG Number of times the latch lock is requested in


ER WAIT mode

MISSES BINARY_INTEG Number of times the latch is first requested and the
ER requester has to wait

SPIN_GETS BINARY_INTEG Number of latch requests which miss the first try but
ER succeed while spinning

WAIT_TIME BINARY_INTEG Time spent on waiting for the latch lock (unit: ms)
ER

3.4.23 DV_LIBRARY_CACHE
Displays the management information about SQL statements in a shared pool.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 268


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-227 DV_LIBRARY_CACHE columns


No. Column Data Type Description
Name

0 NAMESPA VARCHAR(2 SQL statement type


CE 0 BYTE)

1 GETS BINARY_BI Number of times the SQL statement is parsed


GINT

2 GETHITS BINARY_BI Number of times the SQL statement is soft parsed


GINT

3 PINS BINARY_BI Total number of pages used by the SQL statement


GINT

4 PINHITS BINARY_BI Total number of pages used for soft parsing of the
GINT SQL statement

5 RELOADS BINARY_BI Number of times the SQL statement uses pages


GINT

6 INVLIDATI BINARY_BI Number of times the SQL statement parsing fails


ONS GINT

3.4.24 DV_LOCKS
Displays information about current lock resources.

Table 3-228 DV_LOCKS columns


No. Column Data Type Description
Name

0 SID BINARY_IN Session ID


TEGER

1 TYPE VARCHAR(2 Lock type (TS/TX/RS/RX/KS/KX). Currently,


0 BYTE) only TS, TX, RX, and KX locks are used. The
first two are table-level locks, and the last two are
transaction-level locks.

2 ID1 BINARY_BI ID of the user corresponding to the DC which is


GINT waiting for a TS/TX lock; or No. of the page that
is being obtained if the lock type is different

3 ID2 BINARY_BI ID of the DC which is waiting for a TS/TX lock;


GINT or ITL that is being obtained if the lock type is
different

4 LMODE VARCHAR(2 Lock mode (IDLE/S/IX/X) if the lock type is TS


0 BYTE) or TX; or NULL if the lock type is different

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 269


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Data Type Description


Name

5 BLOCK BINARY_IN Lock status (1: self lock; 0: being locked) if the
TEGER lock type is TS or TX; or 1 if the lock type is
different

3.4.25 DV_LOCKED_OBJECTS
Displays information about locked objects.

Table 3-229 DV_LOCKED_OBJECTS columns


No. Column Name Data Type Description

0 SESSION_ID BINARY_INTEGE Session ID


R

1 XIDUSN BINARY_INTEGE Number of undo segments


R

2 XIDSLOT BINARY_INTEGE Slot number


R

3 XIDSQN BINARY_INTEGE Sequence number


R

4 USER_NAME CHAR(68 BYTE) Locked object owner

5 OBJECT_ID BINARY_INTEGE Locked object ID


R

6 OBJECT_NAME CHAR(68 BYTE) Locked object name

7 CLIENT_OS_NA CHAR(64 BYTE) Client OS


ME

8 ClIENT_PROGR CHAR(256 BYTE) Client name


EM

9 LMODE CHAR(10 BYTE) Lock mode (IDLE/S/IX/X)

3.4.26 DV_LOG_FILES
Displays information about current log files.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 270


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-230 DV_LOG_FILES columns


No. Column Name Data Type Description

0 ID BINARY_INTE Log file ID


GER

1 STATUS VARCHAR(20 Status of a log file. The values are as


BYTE) follows:
l ACTIVE: The log file is active
but not being used. In this state,
not all data in the log file has been
written to data files. This log file
may be used for restoration.
l INACTIVE: The log file is
inactive. In this state, all data in
the log file has been written to
data files. This log file will not be
used for restoration.
l CURRENT: The log file is being
used.
l UNUSED: No data has been
written into the log file, which is
usually just created.

2 TYPE VARCHAR(20 Log file type. The value is ONLINE.


BYTE)

3 FILE_NAME VARCHAR(256 Log file name


BYTE)

4 BYTES BINARY_BIGI Log file size


NT

5 WRITE_POS BINARY_BIGI Log write position


NT

6 FREE_SIZE BINARY_BIGI Free log space size


NT

7 RESET_ID BINARY_INTE Log reset ID


GER

8 ASN BINARY_INTE Log ASN (archived serial number)


GER

9 BLOCK_SIZE BINARY_INTE Log block size


GER

10 CURRENT_POINT VARCHAR(128 Log flush point


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 271


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.27 DV_LONG_SQL
Displays logs of long SQL statements. Only the SQL statements whose execution time
exceeds the specified time (LONGSQL_TIMEOUT) can be queried. For details about the
LONGSQL_TIMEOUT parameter, see Session Control Parameters.

Table 3-231 DV_LONG_SQL columns


No. Column Name Data Type Description

0 CTIME VARCHAR(48 Start time for


BYTE) executing a long
SQL statement

1 STAGE VARCHAR(12 Execution phase of


BYTE) the long SQL
statement. Possible
values are:
PREPARE,
EXECUTE,
QUERY,
PREP_EXEC, and
FETCH

2 SID BINARY_BIGINT ID of the session


where the SQL
statement is
executed

3 CLIENT_IP VARCHAR(20 IP address of the


BYTE) client where the
SQL session is
performed

4 ELAPSED_TIME NUMBER(38, 2) Time consumed by


the SQL statement
(unit: ms)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 272


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 PARAMS VARCHAR(6144 Parameter type –


BYTE) Parameter data
length - [Parameter
value] in the SQL
statement. The
parameter type is a
digit, and the
specific meanings
are as follows:
1-int
2-bigint
3-real
4-number
5-decimal
6-date
7-timestamp
8-char
9-varchar
10-string
11-binary
12-varbinary
13-clob
14-blob
17-bool
18-timestampTZ
19-timestampLTZ
20-interval
21-intervalYM
22-intervalDS
23-raw
24-image
NULL indicates that
there is no
parameter.

6 SQL_ID VARCHAR(32 Unique ID of an


BYTE) SQL statement

7 EXPLAIN_ID VARCHAR(32 Unique ID of an


BYTE) SQL execution plan

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 273


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 SQL_TEXT VARCHAR(8000 Original text of the


BYTE) SQL statement. If
the length exceeds
8000 bytes, the SQL
statement will be
truncated.

9 EXPLAIN_TEXT VARCHAR(8000 Text of the SQL


BYTE) execution plan. If
the length exceeds
8000 bytes, the SQL
execution plan will
be truncated.

3.4.28 DV_STANDBYS
Displays the status of threads for standby databases.

Table 3-232 DV_STANDBYS columns

No. Column Name Data Type Description

0 PROCESS VARCHAR(20 Thread name. Values are as follows:


BYTE) l RFS: log receiving thread
l MRP: log replay thread
l ARCH: archive thread
l FAL: archive log fetch thread

1 STATUS VARCHAR(20 Thread status


BYTE)

2 RESETLOG_ID BINARY_INTE RESETLOG ID of the archived redo


GER log

3 THREAD# VARCHAR(20 Archived redo log thread number


BYTE)

4 SEQUENCE# BINARY_INTE Archived redo log sequence number


GER

5 FLUSH_POINT VARCHAR(128 Standby node log flush point


BYTE)

6 PRIMARY_CU VARCHAR(128 Primary node log flush point


RR_POINT BYTE)

7 REPLAY_POIN VARCHAR(128 Standby node log replay point


T BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 274


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.29 DV_ME
Displays information about current sessions.

Table 3-233 DV_ME columns


No. Column Name Data Type Description

0 SID BINARY_INTE ID of the current session


GER

1 USER_NAME VARCHAR(64 Username of the current connection


BYTE)

2 USER_ID BINARY_INTE User ID of the current session


GER

3 CURRENT_SC VARCHAR(64 Default schema of the current query


HEMA BYTE)

4 SPID VARCHAR(11 ID of the thread for the session.


BYTE)

5 OS_PROG VARCHAR(256 Program name of the client that is


BYTE) currently connected

6 OS_HOST VARCHAR(64 Host name of the client that is


BYTE) currently connected

7 OS_USER VARCHAR(68 OS username of the client that is


BYTE) currently connected

8 CLIENT_IP VARCHAR(20 IP address of the client that is currently


BYTE) connected

9 CLIENT_PORT VARCHAR(11 Port number of the client that is


BYTE) currently connected

3.4.30 DV_OPEN_CURSORS
Displays information about the status of currently opened cursors.

Table 3-234 DV_OPEN_CURSORS columns


Column Name Data Type Description

SESSION_ID BINARY_INTEGER Session ID

STMT_ID BINARY_INTEGER STMT ID

USER_NAME VARCHAR(64 BYTE) Username

SQL_TEXT VARCHAR(1024 BYTE) SQL text

SQL_TYPE BINARY_INTEGER SQL type

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 275


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Column Name Data Type Description

SQL_ID VARCHAR(10 BYTE) ID of an SQL statement if


the SQL type is DML; or
NULL for other types of
SQL statements

STATUS VARCHAR(64 BYTE) Statement status. Values are:


l STMT_STATUS_PREP
ARED: The statement is
in the PREPARE phase.
l STMT_STATUS_EXE
CUTED: The statement
is in the EXECUTE
phase.

CURSOR_TYPE VARCHAR(64 BYTE) Cursor type. Values are:


l USER CURSOR: a
cursor opened by a
database user
l PL/SQL DECLARE
CURSOR: an explicit or
reference cursor opened
in a stored procedure
l PL/SQL IMPLICIT
CURSOR: an implicit
cursor opened in a stored
procedure

3.4.31 DV_PARAMETERS
Displays the configuration items of the current database.

Common users cannot query this view without authorization.

Table 3-235 DV_PARAMETERS columns

No. Column Name Data Type Description

0 NAME VARCHAR(64 Parameter name


BYTE)

1 VALUE VARCHAR(2048 Parameter value


BYTE)

2 DEFAULT_VALUE VARCHAR(2048 Default parameter value


BYTE)

3 ISDEFAULT VARCHAR(20 Whether the parameter has been


BYTE) modified

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 276


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

4 MODIFIABLE VARCHAR(20 Whether the parameter can be


BYTE) modified

5 DESCRIPTION VARCHAR(2048 Parameter description


BYTE)

6 RANGE VARCHAR(2048 Parameter value range


BYTE)

7 DATATYPE VARCHAR(20 Parameter type


BYTE)

8 EFFECTIVE VARCHAR(20 Parameter validation level. Values


BYTE) are reboot, reconnect, and
immediately.

3.4.32 DV_PL_MANAGER
Displays information about stored procedure loading to memory.

Table 3-236 DV_PL_MANAGER columns


Column Name Data Type Description

USER# BINARY_INTEGER User ID

USER_NAME VARCHAR(64 BYTE) Username

NAME VARCHAR(64 BYTE) Stored procedure, trigger, or


UDF name

TYPE VARCHAR(30 BYTE) Stored procedure type.


Values are:
PROCEDURE: stored
procedure
FUNCTION: UDF
TRIGGER: trigger

BUCKET_ID BINARY_INTEGER ID of the memory bucket for


the stored procedure

LIST_POS BINARY_INTEGER Position of the link in the


same bucket for the stored
procedure

UNUSED BINARY_INTEGER Entry usage for loading the


stored procedure to memory

TRIG_USER VARCHAR(64 BYTE) Owner of the table on which


the trigger is created

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 277


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Column Name Data Type Description

TRIG_TABLE VARCHAR(64 BYTE) Name of the table on which


the trigger is created

REF_COUNT BINARY_INTEGER Reference of the stored


procedure

ENTITY BINARY_BIGINT Entry for loading the stored


procedure to memory
l A non-0 value indicates
an entry address of the
SQL pool after
compilation.
l The value 0 indicates
that SQL pool resources
are not used.

PAGES BINARY_INTEGER Number of occupied pages.


The size of a page is
specified by page_size.

3.4.33 DV_PL_REFSQLS
Displays information about the SQL statements associated with PL after stored procedure
loading to memory.

Table 3-237 DV_PL_REFSQLS columns


Column Name Data Type Description

USER# BINARY_INTEGER Session ID

USER_NAME VARCHAR(64 BYTE) Username

NAME VARCHAR(64 BYTE) Stored procedure name

ENTITY BINARY_BIGINT Entry for loading the stored


procedure to memory
A non-0 value indicates an
entry address of the SQL
pool after compilation.
The value 0 indicates that
SQL pool resources are not
used.

SQL_ID VARCHAR(10 BYTE) ID of the SQL statement if


the SQL type is DML

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 278


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.34 DV_REACTOR_POOLS
Displays information about connection pools and the corresponding work thread pools.

Table 3-238 DV_REACTOR_POOLS columns


Column Name Data Type Description

REACTOR_ID BINARY_INTEGER Reactor ID

EPOLL_FD BINARY_INTEGER epool descriptor

REACTOR_STATUS VARCHAR(10 BYTE) Reactor status (RUNNING/


PAUSING/PASUSED/
STOPPED)

SESSION_COUNT BINARY_INTEGER Number of current reactor


sessions

KILLEVENT_R_POS BINARY_INTEGER killevent queue read


position

KILLEVENT_W_POS BINARY_INTEGER killevent queue write


position

ACTIVE_AGENT_COUNT BINARY_INTEGER Number of agents where


threads have been created

BLANK_AGENT_COUNT BINARY_INTEGER Number of agents with no


threads allocated

IDLE_AGENT_COUNT BINARY_INTEGER Number of idle agents

OPTIMIZED_AGENT_CO BINARY_INTEGER Number of optimized agent


UNT threads allocated to each
reactor

MODE VARCHAR(10 BYTE) Reactor work mode, which


can be shared or exclusive

MAX_AGENT_COUNT BINARY_INTEGER Maximum number of agent


threads allocated to each
reactor

DEDICATED_AGENT_CO BINARY_INTEGER Number of agents


UNT exclusively occupied by
each reactor

FREE_DEDICATED_AGE BINARY_INTEGER Number of agents that are


NT_COUNT exclusively occupied by
each reactor in idle time

EMERG_SESSION_COUN BINARY_INTEGER Number of login users SYS


T when the agent pool is full

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 279


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.35 DV_REPL_STATUS
Displays information about the communication status between primary and standby
databases.

Table 3-239 DV_REPL_STATUS columns

No. Column Name Data Type Description

0 DATABASE_ROLE VARCHAR(30 BYTE) Database role (primary or


standby)

1 DATABASE_CONDITIO VARCHAR(16 BYTE) Database status


N

2 SWITCHOVER_STATU VARCHAR(20 BYTE) Primary/standby database


S switchover status

3.4.36 DV_RESOURCE_MAP
Displays information about resource views in the database.

Table 3-240 DV_RESOURCE_MAP columns

No. Column Name Data Type Description

0 RESOURCE# BINARY_INTEGER Resource ID

1 TYPE# BINARY_INTEGER Resource type. Values are:


0: password-related
resources
1: system resources

2 NAME VARCHAR(64 BYTE) Resource name

3.4.37 DV_SEGMENT_STATS
Displays information about the usage of objects, such as heap index, in the database.

Table 3-241 DV_SEGMENT_STATS columns

No. Column Name Data Type Description

0 OWNER VARCHAR(64 BYTE) Object owner

1 OBJECT_NAME VARCHAR(64 BYTE) Object name

2 SUBOBJECT_NAME VARCHAR(64 BYTE) Subobject name, for


example, a partition name

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 280


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 TS# BINARY_INTEGER ID of the tablespace


containing the object

4 OBJECT_TYPE VARCHAR(64 BYTE) Object type, such as a


table or index

5 STATISTIC_NAME VARCHAR(64 BYTE) Statistical type

6 STATISTIC# BINARY_INTEGER Statistical item sequence


number

7 VALUE BINARY_INTEGER Statistical value

3.4.38 DV_SESSIONS
Displays information about current sessions.

Table 3-242 DV_SESSIONS columns


N Column Data Type Description
o. Name

0 SID BINARY_IN Session ID


TEGER

1 SPID VARCHAR(1 ID of the thread for the session. For sessions that are
1 BYTE) not buffered in the session pool, SPID is 0.

2 SERIAL# BINARY_IN Session sequence number, used to uniquely identify a


TEGER session object

3 USER# BINARY_IN ID of the login user when the current session is


TEGER created

4 USERNAM VARCHAR(6 Name of the login user when the current session is
E 4 BYTE) created

5 CURR_SCH VARCHAR(6 Schema of the current session


EMA 4 BYTE)

6 CLIENT_IP VARCHAR(2 IP address of the client for the current session


0 BYTE)

7 CLIENT_P VARCHAR(1 Port number of the client for the current session
ORT 0 BYTE)

8 SERVER_IP VARCHAR(2 IP address of the server for the current session


0 BYTE)

9 SERVER_P VARCHAR(1 Port number of the server for the current session
ORT 0 BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 281


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

N Column Data Type Description


o. Name

10 SERVER_M VARCHAR(1 Service mode of the current session. Its value is


ODE 0 BYTE) MIXTURE.
The actual service mode of the current session
depends on the values of SESSIONS,
OPTIMIZED_WORKER_THREADS, and the
number of connections.
l If SESSIONS is smaller than
OPTIMIZED_WORKER_THREADS, the
current session can only run in DEDICATED
mode.
l If SESSIONS is greater than
OPTIMIZED_WORKER_THREADS and the
actual number of connections is greater than
OPTIMIZED_WORKER_THREADS, the
current session runs in SHARED mode.
Otherwise, it runs in DEDICATED mode. This
mode is called MIXTURE mode.

11 OSUSER VARCHAR(6 OS user of the client for the current session


4 BYTE)

12 MACHINE VARCHAR(3 Host of the client for the current session


0 BYTE)

13 PROGRAM VARCHAR(2 Name of the client for the current session


56 BYTE)

14 AUTO_CO BOOLEAN Autocommit


MMIT Statements setting GS_TRUE are automatically
committed after execution.

15 CLIENT_V BINARY_IN Client version


ERSION TEGER

16 TYPE VARCHAR(1 Type of the current session. Values are:


0 BYTE) l BACKGROUND (backend)
l AUTONOMOUS (autonomous transaction)
l USER (user)
l REPLICA (log replication)
l JOB
l EMERG (When the connection pool is full, user
SYS-established connections exclusively occupy
the agent sessions.)

17 LOGON_TI DATE Login time of the current session


ME

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 282


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

N Column Data Type Description


o. Name

18 STATUS VARCHAR(1 Current session status. Values are:


0 BYTE) l IN-ACTIVE (standby)
l ACTIVE (being executed)
l CANCELED (canceled, to be recycled)
l KILLED (killed, to be reclaimed)
l SUSPENSION (suspended after the autonomous
transaction is enabled)

19 LOCK_WAI VARCHAR(4 Whether there is a lock wait event


T BYTE)

20 WAIT_SID BINARY_IN Session ID for the lock wait event


TEGER

21 EXECUTIO BINARY_BI Number of SQL executions


NS GINT

22 SIMPLE_Q BINARY_BI Number of simple query executions


UERIES GINT

23 DISK_REA BINARY_BI Number of disk read operations


DS GINT

24 BUFFER_G BINARY_BI Number of buffer read operations


ETS GINT

25 CR_GETS BINARY_BI Number of consistent reads from page cache


GINT

26 CURRENT_ VARCHAR(1 SQL statement that is being executed (Only DML


SQL 024 BYTE) statements are displayed.)

27 SQL_EXEC DATE Start time of the SQL statement execution


_START

28 SQL_ID BINARY_BI Hash value for the SQL statement


GINT

29 ATOMIC_O BINARY_BI Number of atomic operations


PERS GINT

30 REDO_BYT BINARY_BI Number of bytes that will be involved in redo


ES GINT operations

31 COMMITS BINARY_BI Number of commit times


GINT

32 NOWAIT_C BINARY_BI Number of commit times in NOWAIT mode


OMMITS GINT

33 XA_COMM BINARY_BI Number of times the two-phase transaction is


ITS GINT committed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 283


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

N Column Data Type Description


o. Name

34 ROLLBAC BINARY_BI Number of rollback times


KS GINT

35 XA_ROLLB BINARY_BI Number of times the two-phase transaction is rolled


ACKS GINT back

36 LOCAL_TX BINARY_BI Local transaction execution time (unit: μs)


N_TIMES GINT

37 XA_TXN_T BINARY_BI Two-phase transaction execution time (unit: μs)


IMES GINT

38 PARSES BINARY_BI Number of parsing times


GINT

39 HARD_PAR BINARY_BI Number of hard parsing times


SES GINT

40 EVENT# BINARY_IN Event ID


TEGER

41 EVENT VARCHAR(6 Event name


4 BYTE)

42 SORTS BINARY_BI Total number of times the sort operation is performed


GINT in the current session

43 PROCESSE BINARY_BI Total number of rows processed in the current


D_ROWS GINT session

44 IO_WAIT_T BINARY_BI Total I/O wait time for SQL statements in the current
IME GINT session (unit: μs)

45 CON_WAIT BINARY_BI Total lock wait time for SQL statements in the
_TIME GINT current session (unit: μs)

46 CPU_TIME BINARY_BI Total CPU time for SQL statements in the current
GINT session (unit: μs)

47 ELAPSED_ BINARY_BI Total time consumption of SQL statements in the


TIME GINT current session (unit: μs)

48 ISOLEVEL BINARY_BI Transaction isolation level in the session


GINT

49 MODULE VARCHAR(6 Name of the client that performs a hard parse


4 BYTE) operation on the SQL statement for the first time.
Possible values are GSC_APPLICATION, JDBC,
and ZSQL. If the client cannot be recognized, the
value will be UNKNOWN.

50 VMP_PAGE BINARY_BI Number of memory pages that VMP has applied for
S GINT from VMA

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 284


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

N Column Data Type Description


o. Name

51 LARGE_V BINARY_BI Number of memory pages that LARGE VMP has


MP_PAGES GINT applied for from LARGE VMA

3.4.39 DV_SESSION_EVENTS
Displays information about the wait events for current sessions.

Table 3-243 DV_SESSION_EVENTS columns


No. Column Name Data Type Description

0 SID BINARY_INTEGER Session ID

1 EVENT# BINARY_INTEGER Event ID

2 EVENT VARCHAR(64 Event name


BYTE)

3 P1 VARCHAR(64 Additional parameter


BYTE)

4 WAIT_CLASS VARCHAR(64 Name of the event class


BYTE)

5 TOTAL_WAITS BINARY_BIGINT Total number of waits for


the event

6 TIME_WAITED BINARY_BIGINT Total amount of time waited


for the event (unit: ns)

7 TIME_WAITED_MIRC BINARY_BIGINT Total amount of time waited


O for the event (unit: ms)

8 AVERAGE_WAIT BINARY_DOUBLE Average amount of time


waited for the event (unit:
ns)

9 AVERAGE_WAIT_MIR BINARY_BIGINT Average amount of time


CO waited for the event (unit:
ms)

3.4.40 DV_SESSION_SHARED_LOCKS
Displays information about all session-level shared advisory locks in use.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 285


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-244 DV_SESSION_SHARED_LOCKS columns


Column Name Data Type Description

SID BINARY_INTEGER Session ID

LOCK_NAME VARCHAR(64 BYTE) Name of the advisory lock


at the transaction level

TOTAL_LOCK_TIMES BINARY_INTEGER Total number of times that


the shared lock is used by
sessions

3.4.41 DV_SESSION_WAITS
Displays information about the wait events for current sessions.

Table 3-245 DV_SESSION_WAITS columns


No. Column Name Data Type Description

0 SID BINARY_INTEGE Session ID


R

1 EVENT# BINARY_INTEGE Wait event ID


R

2 EVENT VARCHAR(64 Wait event name


BYTE)

3 P1 VARCHAR(64 Resource that the session is


BYTE) waiting for

4 WAIT_CLASS VARCHAR(64 Name of the class of the wait


BYTE) event

5 STATE VARCHAR(64 Current status


BYTE)

6 WAIT_BEGIN_TI DATE Start time of the wait event


ME

7 WAIT_TIME_MIR BINARY_BIGINT Amount of time waited for the


CO event (unit: μs)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 286


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

8 SECONDS_IN_W BINARY_BIGINT If WAIT_TIME is 0, then


AIT SECONDS_IN_WAIT will
display the number of seconds
spent on waiting in current
conditions. If WAIT_TIME
is not 0, then
SECONDS_IN_WAIT will
display the number of seconds
since the last wait starts. The
number of valid seconds since
the last wait ends can be
calculated as follows:
SECONDS_IN_WAIT –
WAIT_TIME/100

3.4.42 DV_GMA
Displays information about the memory that is applied for.

Table 3-246 DV_GMA columns

No. Column Name Data Type Description

0 NAME CHAR(40 BYTE) Statistical item name

1 VALUE CHAR(40 BYTE) Statistical item value

3.4.43 DV_GMA_STATS
Displays the statistics items of the SGA memory.

Only users SYS and DBA can query this view. The memory pointer columns need to be used
by the database maintenance personnel.

Table 3-247 DV_GMA_STATS columns

No. Column Name Data Type Description

0 AREA VARCHAR(32 Memory area


BYTE)

1 POOL VARCHAR(32 Pool name


BYTE)

2 NAME VARCHAR(32 Statistical item name


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 287


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 VALUE VARCHAR(32 Statistical item value


BYTE)

The following table lists supported statistical items.

Table 3-248 Supported statistical items of DV_GMA_STATS


AREA POOL NAME VALUE

shared pool - buf Start address of the shared


memory pool

shared pool - maps Pointer to a map page in


the shared memory pool

shared pool - page buf Start address of the pages


that can be allocated in
the shared memory pool

shared pool - page count Total number of pages in


the shared memory pool

shared pool - page size Size of each page in the


shared memory pool

shared pool - page hwm High water mark of used


pages in the shared
memory pool

shared pool - free page count Number of free pages in


the shared memory pool

shared pool - free page first ID of the first free page in


the shared memory pool

shared pool - free page last ID of the last free page in


the shared memory pool

shared pool sql pool buf Start address of the SQL


buffer pool

shared pool sql pool maps Pointer to a map page in


the SQL buffer pool

shared pool sql pool page buf Start address of the pages
that can be allocated in
the SQL buffer pool

shared pool sql pool page count Total number of pages in


the SQL buffer pool

shared pool sql pool page size Size of each page in the
SQL buffer pool

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 288


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

AREA POOL NAME VALUE

shared pool sql pool optimizer page count Number of pages that can
be added to the SQL
buffer pool

shared pool sql pool free page count Number of free pages in
the SQL buffer pool

shared pool sql pool free page first ID of the first free page in
the SQL buffer pool

shared pool sql pool free page last ID of the last free page in
the SQL buffer pool

shared pool sql pool bucket size Size of the hash bucket in
the SQL buffer pool

shared pool sql pool bucket count Number of hash buckets


in the SQL buffer pool

shared pool sql pool lru count Number of linked lists for
the replacement algorithm
in the SQL buffer pool

- large pool buf Start address of the large


pool

- large pool maps Pointer to a map page in


the large pool

- large pool page buf Start address of the pages


that can be allocated in
the large pool

- large pool page count Total number of pages in


the large pool

- large pool page size Size of each page in the


large pool

- large pool optimizer page count Number of pages that can


be added to the large pool

- large pool free page count Number of free pages in


the large pool

- large pool free page first ID of the first free page in


the large pool

- large pool free page last ID of the last free page in


the large pool

3.4.44 DV_SPINLOCKS
Displays information about the usage of spinlocks on current sessions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 289


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-249 DV_SPINLOCKS columns


No Column Data Type Description
. Name

0 SID BINARY_INT Session ID


EGER

1 TYPE VARCHAR(1 SPINLOCK type. Value values include: TXN,


28 BYTE) REDO_BUF, COMMIT_QUEUE, CKPT_QUEUE,
BUFFER, BUCKET, SPACE

2 SPINS BINARY_BI Number of spins after a lock is added


GINT

3 SLEEPS BINARY_BI Time to wait for adding a lock (unit: μs)


GINT

4 FAILS BINARY_BI Number of failures to add locks


GINT

3.4.45 DV_SQLS
Displays information about the execution of SQL DML statements.

Table 3-250 DV_SQLS columns


No. Column Name Data Type Description

0 SQL_TEXT VARCHAR(8000 SQL statement,


BYTE) supporting only
DML statements

1 SQL_ID VARCHAR(10 SQL statement ID


BYTE)

2 EXECUTIONS BINARY_BIGINT Number of times the


SQL statement is
executed

3 DISK_READS BINARY_BIGINT Number of times the


SQL statement is
read from the disk

4 BUFFER_GETS BINARY_BIGINT Number of times the


SQL statement is
read from the buffer

5 CR_GETS BINARY_BIGINT Number of times an


SQL statement
searches in the CR
pool in concurrent
transaction scenarios

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 290


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

6 SORTS BINARY_BIGINT Number of times the


sort operation is
performed for the
SQL statement

7 PARSE_TIME BINARY_BIGINT Hard parsing time of


the SQL statement
(unit: μs)

8 PARSE_CALLS BINARY_BIGINT Number of times the


SQL statement is
parsed

9 PROCESSED_RO BINARY_BIGINT Number of rows pre-


WS fetched by the SQL
statement

10 PARSING_USER_I BINARY_INTEGE ID of the user that


D R performs a hard
parse operation on
the SQL statement
for the first time

11 PARSING_USER_ VARCHAR(64 Name of the user


NAME BYTE) that performs a hard
parse operation on
the SQL statement
for the first time

12 MODULE VARCHAR(64 Name of the client


BYTE) that performs a hard
parse operation on
the SQL statement
for the first time.
Possible values are
GSC_APPLICATI
ON, JDBC, and
ZSQL. If the client
cannot be
recognized, the
value will be
UNKNOWN.

13 IO_WAIT_TIME BINARY_BIGINT I/O wait time of the


SQL statement (unit:
μs)

14 CON_WAIT_TIME BINARY_BIGINT Lock wait time of


the SQL statement
(unit: μs)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 291


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

15 CPU_TIME BINARY_BIGINT CPU time of the


SQL statement (unit:
μs)

16 ELAPSED_TIME BINARY_BIGINT Total duration of the


SQL statement (unit:
μs)

17 LAST_LOAD_TIM DATE Time when the SQL


E statement was
loaded to the library
cache last time,
usually the time
when hard parsing is
performed for the
first time

18 PROGRAM_ID BINARY_BIGINT If the SQL statement


is parsed, for the
first time, in a stored
procedure, UDF, or
trigger, this column
will display the
corresponding OID.
Otherwise, it will
display only 0.

19 PROGRAM_LINE# BINARY_INTEGE If the SQL statement


R is parsed, for the
first time, in a stored
procedure, UDF, or
trigger, this column
will display the
corresponding row
number of the SQL
statement.
Otherwise, it will
display only 0.

20 LAST_ACTIVE_TI DATE Time when the SQL


ME statement was active
last time, usually the
time when the SQL
statement was
executed last time

21 REF_COUNT BINARY_INTEGE Number of times the


R SQL statement is
referenced

21 IS_FREE BOOLEAN Released or not

23 CLEANED BOOLEAN Deleted or not

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 292


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

24 PAGES BINARY_INTEGE Number of pages


R occupied by the
context

25 VALID BINARY_INTEGE Whether the context


R is valid

26 SHARABLE_MEM BINARY_BIGINT Occupied memory


(unit: byte)

27 VM_OPEN_PAGE BINARY_BIGINT Number of VM


S pages opened by the
SQL statement.
After the statement
is executed, the
value of this
statistical item
should be 0.

28 VM_CLOSE_PAG BINARY_BIGINT Number of VM


ES pages closed by the
SQL statement.
After the statement
is executed, the
value of this
statistical item
should be 0.

29 VM_SWAPIN_PAG BINARY_BIGINT Number of VM


ES pages that the SQL
statement swaps
from disk to
memory

30 VM_FREE_PAGES BINARY_BIGINT Number of VM


pages used for
executing SQL
statements

3.4.46 DV_SQL_POOL
Displays information about SQL pool usage in the current system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 293


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-251 DV_SQL_POOL columns


No. Column Name Data Type Description

0 SQL_ID VARCHAR(10 SQL statement ID, which is


BYTE) unique and is a string in the
following format: 'hash value
(10-bit) of a SQL text'

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 294


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

1 SQL_TYPE BINARY_INTEGER SQL type. Values are:


1: SELECT
2: UPDATE
3: INSERT
4: DELETE
5: MERGE
7: BEGIN
8: COMMIT_PHASE1
9: COMMIT_PHASE2
10: COMMIT
11: ROLLBACK_PHASE2
12: ROLLBACK
13: ROLLBACK_TO
14: SAVEPOINT
26: CREATE_DATABASE
27:
CREATE_DATABASE_LIN
K
28:
CREATE_DISTRIBUTE_R
ULE
29: CREATE_SEQUENCE
30: CREATE_TABLESPACE
31: CREATE_TABLE
32: CREATE_INDEX
33: CREATE_USER
34: CREATE_ROLE
35: CREATE_VIEW
36: CREATE_NODE
37: CREATE_SYNONYM
38: CREATE_PROFILE
39:
DROP_DATABASE_LINK
40: DROP_SEQUENCE
41: DROP_TABLESPACE
42: DROP_TABLE
43: DROP_INDEX
44: DROP_USER
45: DROP_ROLE
46: DROP_VIEW

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 295


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

47: DROP_SYNONYM
48: DROP_PROFILE
49: DROP_NODE
50:
DROP_DISTRIBUTE_RUL
E
51: DROP_SQL_MAP
52: TRUNCATE_TABLE
53: PURGE
54: COMMENT
55: FLASHBACK_TABLE
56: ALTER_SEQUENCE
57: ALTER_TABLESPACE
58: ALTER_TABLE
59: ALTER_INDEX
60: ALTER_USER
61: ALTER_SYSTEM
62: ALTER_SESSION
63: ALTER_DATABASE
64: ALTER_NODE
65: ALTER_PROFILE
66: ALTER_TRIGGER
67: ALTER_SQL_MAP
68: ANALYSE_TABLE
69: GRANT
70: REVOKE
72: ANONYMOUS_BLOCK
73: CREATE_PROC
74: CREATE_FUNC
75: CREATE_TRIG
76: DROP_PROC
77: DROP_FUNC
78: DROP_TRIG
79: PL_CALL

2 UID BINARY_INTEGER User ID

3 REF_COUNT BINARY_INTEGER Number of times the SQL


statement is referenced

4 VALID BOOLEAN Whether SQL soft parsing is


valid

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 296


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

5 CLEANED BOOLEAN Whether the SQL context has


been deleted

6 IS_FREE BOOLEAN Whether the SQL context has


been released

7 MCTX_PAGE_COUNT BINARY_INTEGER Number of memory pages


applied by the SQL statement
from the SQL pool. The
default page size is 16 KB.

8 MCTX_PAGE_FRIST BINARY_INTEGER First memory page applied


by the SQL statement from
the SQL pool

9 MCTX_PAGE_LAST BINARY_INTEGER Last memory page applied by


the SQL statement from the
SQL pool

10 CURRENT_PAGE_ID BINARY_INTEGER Current memory page applied


by the SQL statement

11 MCTX_PAGES VARCHAR(8000 Connection string for the


BYTE) SQL statement to apply for
pages from the SQL pool, for
example, "1==>2==>10"

12 LARGE_PAGE BINARY_INTEGER Number of large pages


applied by the SQL statement

13 FIRST_OPTMZ_VARS BINARY_INTEGER Number of variables


executed for the first time
during SQL expression
optimization

14 FIRST_OPTMZ_BUFF BINARY_INTEGER Size of the memory of


variables executed for the
first time during SQL
expression optimization

15 LAST_LOAD_TIME DATE Time when the SQL


statement was loaded to the
library cache for the first
time, usually the time when
hard parsing is performed for
the first time

16 LAST_ACTIVE_TIME DATE Time when the SQL


statement was active last
time, usually the time when
the SQL statement was
executed last time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 297


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

3.4.47 DV_SYS_STATS
Displays statistics about the current system.

Table 3-252 DV_SYS_STATS columns


No. Column Name Data Type Description

0 STATISTIC# BINARY_INTEGE Statistical item ID


R

1 NAME VARCHAR(64 Statistical item name


BYTE)

2 CLASS BINARY_INTEGE Statistical item type.


R Values are:
0: SQL
1: kernel
2: instance

3 VALUE BINARY_BIGINT Statistical item value

Table 3-253 lists supported statistical items.

Table 3-253 Supported statistical items of DV_SYS_STATS


STATISTIC# NAME NOTE

0 sql executions Number of times the SQL


statement is executed

1 sql execution total time Total execution time of the


SQL statement (unit: μs)

2 CPU time CPU time of the SQL


statement (CPU time = Total
time – Storage engine I/O
time – Storage engine lock
wait time) (unit: μs)

3 sql parses Number of times the SQL


statement is parsed

4 sql hard parses Number of times the SQL


statement is hard parsed (no
buffer pool involved)

5 SELECT executions Number of times the


SELECT statement is
executed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 298


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

STATISTIC# NAME NOTE

6 SELECT execution time Execution time of the


SELECT statement (unit:
μs)

7 UPDATE executions Number of times the


UPDATE statement is
executed

8 UPDATE execution time Execution time of the


UPDATE statement (unit:
μs)

9 INSERT executions Number of times the


INSERT statement is
executed

10 INSERT execution time Execution time of the


INSERT statement (unit:
μs)

11 DELETE executions Number of times the


DELETE statement is
executed

12 DELETE execution time Execution time of the


DELETE statement (unit:
μs)

13 fetched rows Number of rows in the result


set returned by the SQL
statement

14 processed rows Total number of rows


processed by the SQL
statement

15 disk reads Number of disk reads

16 disk read time Time of disk reads (unit: μs)

17 temporary tablespace Number of times a


allocates temporary tablespace is
applied for

18 buffer gets Number of buffer reads

19 sorts Number of sort operations

20 sort on disk Number of times disk


sorting is triggered

21 atomic operations Number of atomic


operations

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 299


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

STATISTIC# NAME NOTE

22 cn commits single shard Number of single-node


commits

23 cn rollbacks single shard Number of single-node


rollbacks

24 cn commits multi shard Number of multi-node


commits

25 cn rollbacks multi shard Number of multi-node


rollbacks

26 cn commit time single shard Single-node commit time


(unit: μs)

27 cn rollback time single shard Single-node rollback time


(unit: μs)

28 cn commit time multi shard Multi-node commit time


(unit: μs)

29 cn rollback time multi shard Multi-node rollback time


(unit: μs)

30 cn selects single shard Number of single-node


queries

31 cn select time single shard Single-node query time


(unit: μs)

32 cn updates single shard Number of single-node


updates

33 cn update time single shard Single-node update time


(unit: μs)

34 cn inserts single shard Number of single-node


inserts

35 cn insert time single shard Single-node insert time


(unit: μs)

36 cn deletes single shard Number of single-node


delete operations

37 cn delete time single shard Single-node delete time


(unit: μs)

38 cn selects multi shard Number of multi-node


queries

39 cn select time multi shard Multi-node query time (unit:


μs)

40 cn updates multi shard Number of multi-node


updates

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 300


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

STATISTIC# NAME NOTE

41 cn update time multi shard Multi-node update time


(unit: μs)

42 cn inserts multi shard Number of multi-node insert


operations

43 cn insert time multi shard Multi-node insert time (unit:


μs)

44 cn deletes multi shard Number of multi-node


delete operations

45 cn delete time multi shard Multi-node delete time


(unit: μs)

46 redo writes Number of redo log writes

47 redo write time Redo log write time (unit:


μs)

48 redo write size Write size of REDO LOG

49 redo write size count(4K) Number of redo log (4 KB)


writes

50 redo write size count(8K) Number of redo log (8 KB)


writes

51 redo write size count(16K) Number of redo log (16 KB)


writes

52 redo write size count(32K) Number of redo log (32 KB)


writes

53 redo write size count(64K) Number of redo log (64 KB)


writes

54 redo write size count(128K) Number of redo log (128


KB) writes

55 redo write size count(256K) Number of redo log (256


KB) writes

56 redo write size count(512K) Number of redo log (512


KB) writes

57 redo write size count(1M) Number of redo log (1 MB)


writes

58 redo write size count(> 1M) Number of redo log (> 1


MB) writes

59 commits Number of times the


transaction is committed

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 301


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

STATISTIC# NAME NOTE

60 nowait commits Number of transaction


commits in NOWAIT mode

61 XA commits Number of two-phase


transaction commits

62 rollbacks Number of transaction


rollbacks

63 XA rollbacks Number of two-phase


transaction rollbacks

64 local txn time Local transaction execution


time (unit: μs)

65 XA txn time Two-phase transaction


execution time (unit: μs)

66 DBWR double writes Number of times data is


written to the dual-write
area of the system
tablespace

67 DBWR double write time Time for writing data to the


dual-write area of the
system tablespace (unit: μs)

68 DBWR disk writes Number of times data is


written to the corresponding
data file

69 DBWR disk write time Time for writing data to the


corresponding data file
(unit: μs)

3.4.48 DV_SYSTEM
Displays information about CPU and memory usage in the current OS.

Table 3-254 DV_SYSTEM columns


No. Column Name Data Type Description

0 ID BINARY_INTEGE Statistical item ID


R

1 NAME VARCHAR(64 Statistical item name


BYTE)

2 VALUE VARCHAR(128 Statistical item value


BYTE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 302


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 COMMENTS VARCHAR(256 Statistical item


BYTE) description

4 ACCUMULATIVE BOOLEAN Whether the


statistical item is
accumulative

3.4.49 DV_SYS_EVENTS
Displays information about events in the current system.

Table 3-255 DV_SYS_EVENTS columns


No. Column Name Data Type Description

0 EVENT# BINARY_IN Wait event ID


TEGER

1 EVENT VARCHAR(6 Wait event name


4 BYTE)

2 P1 VARCHAR(6 Additional parameter


4 BYTE)

3 WAIT_CLASS VARCHAR(6 Wait event class


4 BYTE)

4 TOTAL_WAITS BINARY_BI Total number of wait events


GINT

5 TIME_WAITED BINARY_BI Time of the wait event (unit: μs)


GINT

6 TIME_WAITED_MIR BINARY_BI Time of the wait event (unit: ms)


CO GINT

7 AVERAGE_WAIT BINARY_DO Average time of wait events (unit: μs)


UBLE

8 AVERAGE_WAIT_M BINARY_BI Average time of wait events (unit:


IRCO GINT ms)

3.4.50 DV_TABLESPACES
Displays information about current tablespaces.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 303


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-256 DV_TABLESPACES columns

No Column Name Data Type Description


.

0 ID BINARY_INT Tablespace ID
EGER

1 NAME VARCHAR(6 Tablespace name


4 BYTE)

2 TEMPORARY VARCHAR(8 Whether the tablespace is a temporary


BYTE) tablespace

3 IN_MEMORY VARCHAR(8 Whether the tablespace is an in-memory


BYTE) tablespace

4 AUTO_PURGE VARCHAR(8 Whether recycle bin space is automatically


BYTE) reclaimed when the tablespace is extended

5 EXTENT_SIZE BINARY_INT Size of the extent


EGER

6 SEGMENT_CO BINARY_INT Number of segments


UNT EGER

7 FILE_COUNT BINARY_INT Number of files


EGER

8 STATUS VARCHAR(8 Tablespace status (ONLINE/OFFLINE)


BYTE)

9 AUTO_OFFLIN VARCHAR(8 Whether the automatic offline function is


E BYTE) enabled for tablespaces Valid value: ON and
OFF

3.4.51 DV_TEMP_POOLS
Displays information about current temporary pools.

Table 3-257 DV_TEMP_POOLS columns

No. Column Name Data Type Description

0 ID BINARY_INTEGE Temporary pool ID


R

1 TOTAL_VIRTUAL BINARY_INTEGE Total size of the


R temporary pool
(unit: byte)

2 FREE_VIRTUAL BINARY_INTEGE Idle size of the


R temporary pool
(unit: byte)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 304


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

3 PAGE_SIZE BINARY_INTEGE Size of each page of


R the temporary pool
(unit: byte)

4 TOTAL_PAGES BINARY_INTEGE Total number of


R pages in the
temporary pool

5 FREE_PAGES BINARY_INTEGE Number of free


R pages in the
temporary pool

6 PAGE_HWM BINARY_INTEGE High water mark of


R used pages in the
temporary pool

7 FREE_LIST BINARY_INTEGE ID of the first free


R page in the
temporary pool

8 CLOSED_LIST BINARY_INTEGE ID of the last free


R page in the
temporary pool

9 DISK_EXTENTS BINARY_INTEGE Number of virtual


R memory pages
(vmpages) that can
be swapped out to
disk

10 SWAP_COUNT BINARY_INTEGE Number of vmpages


R that have been
swapped out to the
temporary
tablespace

11 FREE_EXTENTS BINARY_INTEGE Number of free


R extents in the
temporary pool

3.4.52 DV_TEMP_UNDO_SEGMENT
Displays the status of all temporary undo segment queues.
The difference between a temporary undo segment and an undo segment is that the former
records undo information without redo information.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 305


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-258 DV_TEMP_UNDO_SEGMENT columns


No. Column Name Data Description
Type

0 ID BINARY Temporary undo segment ID


_INTEGE
R

1 SEG_ENTRY BINARY Temporary undo segment page ID


_BIGINT

2 TXN_PAGES BINARY Number of transaction pages on the temporary


_INTEGE undo segment
R

3 UNDO_PAGES BINARY Number of undo pages on the temporary undo


_INTEGE segment
R

4 UNDO_FIRST BINARY ID of the first undo page on the temporary


_BIGINT undo segment

5 UNDO_LAST BINARY ID of the last undo page on the temporary


_BIGINT undo segment

6 FIRST_TIME DATE Time when the first undo page on the


temporary undo segment is updated

7 LAST_TIME DATE Time when the last undo page on the


temporary undo segment is updated

8 RETENTION_TI BINARY Retention period of all undo pages on the


ME _INTEGE temporary undo segment (unit: second)
R

9 OW_SCN BINARY Overwritten SCN


_BIGINT

3.4.53 DV_TRANSACTIONS
Displays information about transactions.

Table 3-259 DV_TRANSACTIONS columns


No. Column Name Data Type Description

0 SEG_ID BINARY_IN Transaction segment ID


TEGER

1 SLOT BINARY_IN Transaction slot number in pages


TEGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 306


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Type Description

2 XNUM BINARY_IN Transaction version number


TEGER

3 SCN BINARY_BI Transaction SCN


GINT

4 SID BINARY_IN Transaction session ID


TEGER

5 STATUS VARCHAR( Transaction status


64 BYTE)

6 UNDO_COUNT BINARY_IN Number of undo pages used by the


TEGER transaction

7 UNDO_FIRST BINARY_IN First undo page used by the transaction


TEGER

8 UNDO_LAST BINARY_IN Last undo page used by the transaction


TEGER

9 BEGIN_TIME DATE Start time of the transaction

10 TXN_PAGEID BINARY_IN ID of the page where the transaction is


TEGER located

3.4.54 DV_UNDO_SEGMENTS
Displays the status of all undo segment queues.

Table 3-260 DV_UNDO_SEGMENTS columns

No. Column Name Data Description


Type

0 ID BINARY Undo segment ID


_INTEGE
R

1 SEG_ENTRY BINARY Undo segment page ID


_BIGINT

2 TXN_PAGES BINARY Number of transaction pages on the undo


_INTEGE segment
R

3 UNDO_PAGES BINARY Number of undo pages on the undo segment


_INTEGE
R

4 UNDO_FIRST BINARY ID of the first undo page on the undo segment


_BIGINT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 307


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

No. Column Name Data Description


Type

5 UNDO_LAST BINARY ID of the last undo page on the undo segment


_BIGINT

6 FIRST_TIME DATE Time when the first undo page on the undo
segment is updated

7 LAST_TIME DATE Time when the last undo page on the undo
segment is updated

8 RETENTION_TI BINARY Retention period of all undo pages on the undo


ME _INTEGE segment (unit: second)
R

9 OW_SCN BINARY Overwritten SCN


_BIGINT

3.4.55 DV_USER_ADVISORY_LOCKS
Displays information about all session-level advisory locks in use.

Table 3-261 DV_USER_ADVISORY_LOCKS columns


No. Column Name Data Type Description

0 SID BINARY_INTEGE ID of the session


R that holds the lock

1 LOCK_NAME VARCHAR(64 Name of the


BYTE) advisory lock

2 LOCK_TIMES BINARY_INTEGE Number of times the


R session is locked by
the advisory lock

3 LOCK_SCN BINARY_BIGINT SCN when the


session acquires the
lock

3.4.56 DV_USER_ASTATUS_MAP
Displays information about the views of the database user status type.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 308


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-262 DV_USER_ASTATUS_MAP columns


No. Column Name Data Type Description

0 STATUS# BINARY_INTEGE Status ID


R

1 STATUS VARCHAR(64 User status type


BYTE)

3.4.57 DV_USER_PARAMETERS
Displays the configuration items of the current database. This view is accessible to common
users.

Table 3-263 DV_USER_PARAMETERS columns


No. Column Name Data Type Description

0 NAME VARCHAR(64 Parameter name


BYTE)

1 VALUE VARCHAR(2048 Parameter value


BYTE)

2 DEFAULT_VALUE VARCHAR(2048 Default parameter value


BYTE)

3 ISDEFAULT VARCHAR(20 Whether the parameter is set to its


BYTE) default value

4 MODIFIABLE VARCHAR(20 Whether the parameter can be


BYTE) modified

5 DESCRIPTION VARCHAR(2048 Parameter description


BYTE)

6 RANGE VARCHAR(2048 Parameter value range


BYTE)

7 DATATYPE VARCHAR(20 Parameter type


BYTE)

8 EFFECTIVE VARCHAR(20 Parameter validation level. Values


BYTE) are reboot, reconnect, and
immediately.

3.4.58 DV_VERSION
Displays software versions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 309


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-264 DV_VERSION columns


No. Column Name Data Type Description

0 VERSION VARCHAR(80 Version information


BYTE)

3.4.59 DV_VM_FUNC_STACK
Displays the function stack information when the VM is not released.
When there is a VM leak suspect, you can configure _MAX_VM_FUNC_STACK_COUNT
to query this view.

Table 3-265 DV_VM_FUNC_STACK columns


Column Name Data Type Description

FUNC_STACK VARCHAR(2048 BYTE) Stack information when VM


application is not released

REF_COUNT BINARY_INTEGER Number of times that the


VM is in OPEN state

3.4.60 DV_WAIT_STATS
Displays statistics about all wait events when there is a large number of buffer busy waits
events.

Table 3-266 DV_WAIT_STATS columns


Column Name Data Type Description

CLASS VARCHAR(64 BYTE) Wait event name

COUNT BINARY_INTEGER Number of times the wait


event occurs

TIME BINARY_INTEGER Total wait time (unit: ms)

3.4.61 DV_XACT_LOCKS
Displays information about all transaction-level exclusive advisory locks in use.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 310


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Table 3-267 DV_XACT_LOCKS columns


Column Name Data Type Description

SID BINARY_INTEGER Session ID

SERIAL# BINARY_INTEGER Session sequence number,


used to uniquely identify a
session object

LOCK_NAME VARCHAR(64 BYTE) Name of the advisory lock


at the transaction level

LOCK_TIMES BINARY_INTEGER Number of times the


transactions is locked by the
advisory lock

3.4.62 DV_XACT_SHARED_LOCKS
Displays information about all transaction-level shared advisory locks in use.

Table 3-268 DV_XACT_SHARED__LOCKS columns


Column Name Data Type Description

SID BINARY_INTEGER Session ID

LOCK_NAME VARCHAR(64 BYTE) Name of the advisory lock


at the transaction level

TOTAL_LOCK_TIMES BINARY_INTEGER Total number of times that


the advisory lock is used by
transactions

3.5 View Descriptions


V$SYSSTAT

Statistics type.

0: SQL statistics

1: database kernel statistics

2. database instance statistics

Statistical Item Description Statistics Type Statistical Value

sql executions Number of SQL 0 353500


executions

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 311


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Statistical Item Description Statistics Type Statistical Value

sql execution time SQL execution time 0 46567998

CPU time CPU time 0 23283999

sql parses Number of times 0 295135


SQL soft parsing is
performed

sql hard parses Number of times 0 77


SQL hard parsing is
performed

SELECT executions Number of SELECT 0 330319


executions

SELECT execution SELECT execution 0 20199470


time time

UPDATE executions Number of UPDATE 0 22758


executions

UPDATE execution UPDATE execution 0 3076947


time time

INSERT executions Number of INSERT 0 8


executions

INSERT execution INSERT execution 0 7157


time time

DELETE executions Number of DELETE 0 11


executions

DELETE execution DELETE execution 0 425


time time

fetched rows Number of obtained 0 332790


rows

processed rows Number of processed 1 701532


rows

disk reads Number of disk reads 1 116

disk read time Disk read time 1 2351

temporary tablespace Temporary 1 0


allocates tablespace allocation

buffer gets Number of buffer 1 1480880


reads

sorts Number of sort 1 10346


operations

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 312


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Statistical Item Description Statistics Type Statistical Value

sort on disk Number of disk sort 1 0


operations

atomic operations Number of atomic 1 174824


operations

redo writes Number of redo log 1 23127


writes

redo write time Time spent in writing 1 64488540


redo logs

redo write size Total size of redo 1 22782788


logs

redo write size Number of redo logs 1 23032


count(4K) smaller than 4 KB

redo write size Number of redo logs 1 67


count(8K) in the range 4 KB to
8 KB

redo write size Number of rewrites 1 24


count(16K)

redo write size Number of rewrites 1 3


count(32K)

redo write size Number of rewrites 1 0


count(64K)

redo write size Number of rewrites 1 0


count(128K)

redo write size Number of rewrites 1 0


count(256K)

redo write size Number of rewrites 1 1


count(512K)

redo write size Number of rewrites 1 0


count(1M)

redo write size Number of rewrites 1 0


count(> 1M)

commits Number of times the 1 23093


transaction is
committed

nowait commits Number of times the 1 0


transaction is
committed in
NOWAIT mode

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 313


GaussDB 100
Database Reference (Standalone) 3 Data Dictionary and Views

Statistical Item Description Statistics Type Statistical Value

XA commits Number of times the 1 0


two-phase transaction
is committed

rollbacks Number of times the 1 0


transaction is rolled
back

XA rollbacks Number of times the 1 0


two-phase transaction
is rolled back

local txn time Duration of a 1 24999850


transaction

XA txn time Duration of the two- 1 0


phase transaction

DBWR double writes Number of dual- 1 326


writes

DBWR double write Dual-write time 1 6354074


time

DBWR disk writes Number of disk dual- 1 55815


writes

DBWR disk write Disk dual-write time 1 20933822


time

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 314


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

4 Monitoring Alarms

1078919217|InsufficientDataInstFileDesc
Alarm ID: 1078919217

Alarm name: InsufficientDataInstFileDesc

Alarm meaning: File handle resources of the Zengine process are insufficient, and the upper
limit of the resources needs to be raised.

Alarm principle: The system checks whether the file handle resources of the current database
are insufficient. If they are, the alarm is reported.

Alarm handling:

l In a Linux operating system, modify system parameters to increase the number of file
handles that can be opened by database processes. Alternatively, run the lsof command
to view the usage of system file handles, and terminate related processes to release
handle resources.
l In a Windows operating system, terminate unnecessary applications to release system
file handle resources.

1078919231|DeadLock
Alarm ID: 1078919231

Alarm name: DeadLock

Alarm meaning: There is a deadlock.

Alarm principle: The system checks whether there is a deadlock while a DN waits for lock
resources. If there is, the alarm is reported.

Alarm handling: Query trace_log for the statement causing the deadlock, and check whether
the statement logic is the cause of the deadlock. If it is, modify the statement.

1078919232|DataNodeNeedBuild
Alarm ID: 1078919232

Alarm name: DataNodeNeedBuild

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 315


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

Alarm meaning: The build command needs to be manually delivered to a DN to rebuild the
baseline.

Alarm principle: The system periodically checks the DN view V$DATABASE for the DN
status (dbcondition) at an interval of 5s. If the status is need repair, you need to manually
deliver the build command to rebuild the baseline.

Alarm handling: Manually deliver the build command to rebuild the baseline.

1078919234
Alarm ID: 1078919234

Alarm meaning: A logical replication process exits abnormally.

Alarm principle: When the logical replication process exits abnormally, the alarm is reported
by invoking the DM alarm sending interface.

Alarm handling: Check the run and audit log files of logical replication. Rectify the error
according to the logs, and then restart the logical replication tool. The run and audit log files
are stored in /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/
logicrep/logicrep/logicrep.

1078919235
Alarm ID: 1078919235

Alarm meaning: There is an error in writing a checkpoint.

Alarm principle: When checkpoint writing fails, the alarm is reported by invoking the DM
alarm sending interface. A checkpoint writing failure will lead to a checkpoint update failure.

Alarm handling: Check the status of the source database and query the run logs of logical
replication to obtain more information. The run logs are stored in /opt/software/tools/
GAUSSDB100-V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919236
Alarm ID: 1078919236

Alarm meaning: There is an error in the checkpoint thread.

Alarm principle: When a checkpoint thread exits, the alarm is reported by invoking the DM
alarm sending interface. A checkpoint thread exit will lead to a logical replication process
exit.

Alarm handling: Check the run logs of logical replication, rectify the error, and restart the
logical replication tool. The run logs are stored in /opt/software/tools/GAUSSDB100-
V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919237
Alarm ID: 1078919237

Alarm meaning: There is an error in extracting the log parsing thread.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 316


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

Alarm principle: When there is an error in extracting the log parsing thread, the alarm is
reported by invoking the DM alarm sending interface. An error in extracting the log parsing
thread will lead to a logical replication process exit.

Alarm handling: Check the run logs of logical replication, rectify the error, and restart the
logical replication tool. The run logs are stored in /opt/software/tools/GAUSSDB100-
V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919238
Alarm ID: 1078919238

Alarm meaning: There is an error in the replay thread.

Alarm principle: When SQL statement replay fails, the alarm is reported by invoking the
DM alarm sending interface. A SQL statement replay failure will lead to a logical replication
process exit.

Alarm handling: Check the run logs of logical replication, rectify the error, and restart the
logical replication tool. The run logs are stored in /opt/software/tools/GAUSSDB100-
V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919239
Alarm ID: 1078919239

Alarm meaning: Primary/standby detection shows an error.

Alarm principle: When there is a primary/standby switchover triggered by a database error,


the alarm is reported by revoking the DM alarm sending interface. At the same time, the
logical replication process of the primary database stops replaying SQL statements, and that
of the standby database starts to work.

Alarm handling: Check whether the source database is normal and query the run logs of
logical replication to obtain more information. The run logs are stored in /opt/software/tools/
GAUSSDB100-V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919240
Alarm ID: 1078919240

Alarm meaning: There is an error in the transaction distribution thread.

Alarm principle: When there is an error in transaction distribution, the alarm is reported by
invoking the DM alarm sending interface. An error in the transaction distribution thread will
lead to a logical replication process exit.

Alarm handling: Check whether the source database is normal and query the run logs of
logical replication to obtain more information. The run logs are stored in /opt/software/tools/
GAUSSDB100-V300R001C00-LOGICREP/logicrep/logicrep/logicrep/logicrep.

1078919241
Alarm ID: 1078919241

Alarm meaning: The target database is abnormal.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 317


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

Alarm principle: When there is an error in the target database, the alarm is reported by
invoking the DM alarm sending interface. An error in the target database will lead to a logical
replication process exit.
Alarm handling: Check whether the target database is normal, query the run logs of logical
replication to rectify the database error, and then restart the logical replication process. The
run logs are stored in /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/logicrep/logicrep/logicrep.

1078919243|backup failed
Alarm ID: 1078919243
Alarm name: backup failed
Alarm meaning: There is a backup failure.
Alarm principle: This alarm is reported when backup fails.
Alarm handling: Troubleshoot according to Roach logs, which are stored in $GAUSSLOG/
roach.

1078919244|Degrade
Alarm ID: 1078919244
Alarm name: Degrade
Alarm meaning: There is a demotion from synchronous standby to temporary asynchronous
standby.
Alarm principle: In maximum availability mode, if the synchronization log sending thread
does not receive a response from the standby database within the period of
REPL_WAIT_TIMEOUT multiplied by 2, the database will be demoted from synchronous
to temporary asynchronous.
Alarm handling: Check whether the network is abnormal or the standby database is
overloaded. Generally, self-healing works (restored from temporary asynchronous to
synchronous), except when the demotion is manually produced for fault tests.

1078919249|Archive
Alarm ID: 1078919249
Alarm name: Archive
Alarm meaning: There is an archive log failure.
Alarm principle: The alarm is reported when redo log archiving on a database instance fails.
It is a common error alarm. When the alarm is reported, logs cannot be archived. As a result,
the database is suspended and cannot provide services.
Alarm handling: Check the permission, attribute, and disk status of archive log files, and
check error information in run logs.

1078919250|FlushRedo
Alarm ID: 1078919250

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 318


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

Alarm name: FlushRedo


Alarm meaning: There is a redo log file write failure.
Alarm principle: The alarm is reported when flush-to-disk of redo data on a database
instance fails. It is a major error alarm. When the alarm is reported, the database immediately
stops client requests and the main process immediately exits.
Alarm handling: Check the permission, attribute, and disk status of redo log files, and check
error information in run logs.

1078919251|FlushBuffer
Alarm ID: 1078919251
Alarm name: FlushBuffer
Alarm meaning: There is a data file write failure.
Alarm principle: The alarm is reported when flush-to-buffer of redo data on a database
instance fails. It is a major error alarm. When the alarm is reported, the database immediately
stops client requests and the main process immediately exits.
Alarm handling: Check the permission, attribute, and disk status of data files, and check
error information in run logs.

1078919252|DataNodeLRInstAbonormal
Alarm ID: 1078919252
Alarm name: DataNodeLRInstAbonormal
Alarm meaning: A logical replication instance is abnormal.
Alarm principle: A CM Agent automatically periodically checks whether the logical
replication process is normal at an interval of 5s. If there is an exception, the CM Agent will
report the alarm and automatically start the abnormal process for a maximum of three times.
The alarm will not be repeatedly reported.
Alarm handling: Contact Huawei technical support.

1078919253|TablespaceUsage
Alarm ID: 1078919253
Alarm name: TablespaceUsage
Alarm meaning: The size of a tablespace needs to be adjusted when the tablespace usage
reaches the threshold.
Alarm principle: The system periodically checks the usage of database instance tablespaces
at an interval of 3s. If the tablespace usage reaches the user-specified threshold, the alarm is
reported. If the tablespace usage reaches the threshold again after the alarm is cleared by
manual intervention, a new alarm will be generated.
Alarm handling: Choose any one of the following methods according to the actual situation:
Method 1: Query the dv_data_files view. If the tablespace has data files where automatic
extension is not enabled, enable it for both the tablespace and data files.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 319


GaussDB 100
Database Reference (Standalone) 4 Monitoring Alarms

For example:
-- Enable automatic extension for a data file:
alter tablespace SPC_NAME autoextend on;
-- Enable automatic extension for a tablespace:
alter database datafile 'FILE_NAME' autoextend on;

Method 2: Query the dv_data_files view and adjust the maxsize value of automatic
extension.
For example:
alter database datafile 'FILE_NAME' autoextend on maxsize MAX_SIZE;

Method 3: Add new data files to the current tablespace.


For example:
alter tablespace SPC_NAME add datafile 'FILE_NAME' size FILE_SIZE;

Method 4: Shrink tables to release space.


For example:
alter table TABLE_NAME shrink space;

Alarm Directory Configuration


The alarm directory can be specified by ALARM_LOG_DIR. You can view alarm details in
this directory.

Example Alarm Details


2018-01-12 16:00:36|1078919217|InsufficientDataInstFileDesc|DN|dn_6005|dn_6005,
(Data instance %s file descriptor is insufficient)
2018-01-12 16:00:36|1078919231|DeadLock|DN|dn_6005|dn_6005,(Data instance %s
deadlock occurred)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 320


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

5 Interface Mapping (Basic Packages vs.


Compatible Packages)

5.1 Data Dictionary Tables


Table 5-1 Name mapping of data dictionary tables (basic packages vs. compatible packages)
Basic Package Compatible Package

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 321


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 322


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

5.2 DBA Views


Table 5-2 Name mapping of DBA views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 323


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 324


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

5.3 User Views


Table 5-3 Name mapping of user views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_ARGUMENTS ALL_ARGUMENTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 325


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 326


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 327


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

5.4 Dynamic Performance Views


Table 5-4 Name mapping of dynamic performance views (basic packages vs. compatible
packages)
Basic Package Compatible Package

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 328


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 329


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

5.5 Configuration Parameters


Table 5-5 Name mapping of configuration parameters (basic packages vs. compatible
packages)
Basic Package Compatible Package

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 330


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Database Reference (Standalone) Packages)

Basic Package Compatible Package

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 331


GaussDB 100
Database Reference (Standalone) 6 Glossary

6 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are a set of
features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a database. The
thread thread is used to archive database logs to a specified path.

atomicity One of the ACID features of database transactions. Atomicity means that a
transaction is composed of an indivisible unit of work. All operations
performed in a transaction must either be committed or uncommitted. If an
error occurs during transaction execution, the transaction will be rolled
back to the state when it was not committed.

backup A backup, or the process of backing up, refers to the copying and archiving
of computer data. Backup data can be used for restoration in case of data
loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false logical
condition. A bit is physically represented by an element such as high or low
voltage at one point in a circuit, or a small spot on a disk that is magnetized
in one way or the other. A single bit conveys little information a human
would consider meaningful. A group of eight bits, however, makes up a
byte, which can be used to represent many types of information, such as a
letter of the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at a certain
time. GaussDB 100 periodically stores the data of committed transactions
and data of uncommitted transactions to disks. The data and redo logs can
be used for database restoration if a database restarts or breaks down.

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands are entered
through keyboards or similar devices and are compiled and executed by
applications. The results are displayed in text or graphic forms on the
terminal interface.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 332


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

coding Coding is representing data and information using code so that it can be
processed and analyzed by a computer. Characters, digits, and other objects
can be converted into digital code, or information and data can be converted
into the required electrical pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or more


columns.

compression Data compression, source coding, or bit-rate reduction involves encoding


information that uses fewer bits than the original representation.
Compression can be either lossy or lossless. Lossless compression reduces
bits by identifying and eliminating statistical redundancy. No information is
lost in lossless compression. Lossy compression reduces bits by identifying
and removing unnecessary or less important information. The process of
reducing the size of a data file is commonly referred as data compression,
although its formal name is source coding (coding done at the source of
data, before it is stored or transmitted).

concurrency A DBMS service that ensures data integrity when multiple transactions are
control concurrently executed in a multi-user environment. In a multi-threaded
GaussDB 100 environment, concurrency control ensures that database
operations are safe and all database transactions remain consistent at any
given time.

consistency One of the ACID features of database transactions. Consistency is a


database state. In such a state, integrity constraints on tables are not
damaged.

convergence Downlink to uplink bandwidth ratio of a switch. A high convergence ratio


ratio indicates a highly converged traffic environment and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or system
dump records the state of working memory of the program at that point in
time. The states of key programs are often dumped at the same time. For
example, information about processor registers, including program metrics,
stack pointers, memory management, other processors, and OS flags are
often dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

core file A file that is created when memory overwriting, assertion failures, or access
to invalid memory occurs in a process, causing it to fail. This file is then
used for further analysis.
A core file stores memory dump data, and supports binary mode and
specified ports. The name of a core file consists of the word "core" and the
OS process ID.
The core file is available regardless of the type of platform.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 333


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

crash A crash (or system crash) is when a computer or program, such as a


software application or an operating system, stops functioning properly.
Often the program will exit after encountering this type of error. The
program experiencing the crash can hang or freeze until a crash reporting
service reports the crash and any details relating to it. If the program is a
critical part of the operating system and crashes, the entire system may be
paralyzed, often resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes constants,
variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored procedure
information, user rights, user statistics, database process information,
database increase statistics, and database performance statistics.

data flow An operator that exchanges data among query fragments. By their input/
operator output relationships, data flows can be categorized into Gather flows,
Broadcast flows, and Redistribution flows. Gather combines multiple query
fragments of data into one. Broadcast forwards the data of one query
fragment to multiple query fragments. Redistribution reorganizes the data
of multiple query fragments and then redistributes the reorganized data to
multiple query fragments.

data A division of a logical database or its constituent elements into multiple


partitioning parts (partitions) whose data does not overlap based on ranges or lists. The
target storage location is mapped based on the range of the values in the
column that is specified in the tuple.

database A collection of data that is stored together and can be accessed, managed,
and updated. Data in a view in a database can be classified into the
following types: numeral, full text, digit, and image.

database file A binary file that stores user data and the internal data of a database system.

database HA GaussDB 100 provides a highly reliable HA solution. Every logical node in
GaussDB 100 is identified as a primary or standby node. At the same time,
only one GaussDB 100 node is identified as the primary server. In
GaussDB 100, standby nodes first perform full synchronization from the
primary node and later incremental synchronization. When the HA system
is running, the primary node can receive data read and write requests in
GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database instances
to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database maintenance


operations.

DBLINK An object of the path from one database to another. A remote database
object can be queried with DBLINK.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 334


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a database.
It is a collection of programs that allows users to access, manage, and query
data in a database. A DBMS can be classified as memory DBMS or disk
DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data during an
event response, whereas a trace file contains continuously generated
diagnostic data.

durability One of the ACID features of database transactions. Transactions that have
been committed will permanently survive and not be rolled back.

encryption A function hiding information content during data transmission to prevent


unauthorized use of the information.

environment An environment variable defines a part of the environment in which a


variable process runs. For example, it can define a main directory, command search
path, terminal that is in use, or the current time zone.

error A technique that automatically detects and corrects errors in software and
correction data streams to improve system stability and reliability.

F–J

failover Automatic switchover from a faulty node to its standby node. Reversely,
automatic switchback from the standby node to the primary node is called
failback.

failover Automatic substitution of a functionally equivalent system component for a


failed one. The system component can be a processor, server, network, or
database.

free space A mechanism for managing free space in a table. This mechanism enables a
management database system to record free space in each table and establish an easy-to-
find data structure, accelerating operations (such as INSERT) performed on
the free space.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 335


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

freeze An operation automatically performed by the AutoVacuum Worker process


when transaction IDs are exhausted. GaussDB 100 records transaction IDs
in the row heading. When a transaction reads a row, the transaction ID in
the row heading and the actual transaction ID are compared to determine
whether this row is explicit. Transaction IDs are integers containing no
symbols. If exhausted, transaction IDs are re-calculated outside of the
integer range, causing the explicit rows to become implicit. To prevent such
a problem, the freeze operation marks a transaction ID as a special ID.
Rows marked with these special transaction IDs are explicit to all
transactions.

full A data synchronization mechanism specified in the GaussDB 100 HA


synchronizat solution. Used to synchronize all data from the primary server to a standby
ion server.

GNU The GNU Project was publicly announced on September 27, 1983 by
Richard Stallman, aiming at building an OS composed wholly of free
software. GNU is a recursive acronym for "GNU's Not Unix!". Stallman
announced that GNU should be pronounced as Guh-NOO. Technically,
GNU is similar to Unix in design, a widely used commercial OS. However,
GNU is free software and contains no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for each
node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration of


service interruptions caused by routine maintenance (planned) or sudden
system breakdowns (unplanned), improving system and application
usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on behalf of


all or some of the system users.

incremental Incremental backup stores all file changes since the last valid backup.
backup

index An ordered data structure in a DBMS. An index accelerates data query and
update in database tables.

isolation One of the ACID features of database transactions. Isolation means that the
operations inside a transaction and data used are isolated from other
concurrent transactions. Concurrent transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java APIs of
SQL statements. It provides unified access to multiple relational databases,
consisting of a set of classes and interfaces written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements. When
deleting a tuple, GaussDB 100 only marks the tuples that are to be cleared.
The VACUUM thread will then periodically clear these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 336


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

metadata Data that provides information about other data. Metadata describes the
source, size, format, or other characteristics of data. In database columns,
metadata explains the content of a data warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that allows a


tuple to have multiple versions, on which different query operations can be
performed. One basic advantage is that read and write operations do not
conflict.

network Network backup provides a comprehensive, flexible data protection


backup solution for Microsoft Windows, UNIX, and Linux platforms. Network
backup can back up, archive, and restore files, folders, directories, volumes,
and partitions on a computer.

OS An operating system (OS) manages applications or application programs on


a computer.

P–T

page Smallest memory unit for row storage in the relational object structure in
GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature of


GaussDB 100. Data can be restored to a specified point in time if backup
data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB 100 HA
server system and works with all standby servers. At any time, only one node in
the HA system is identified as the primary server.

process An instance of a computer program that is being executed. A process may


be made up of one or more threads. A process cannot use a thread occupied
by another process.

QPS Query Per Second (QPS) means the number of queries that a server can
respond to per second.

query Each query job can be split into one or more query fragments. Each query
fragment fragment consists of one or more query operators and can independently
run on a node. Query fragments exchange data through data flow operators.

query An iterator or a query tree node, which is a basic unit for the execution of a
operator query. Execution of a query can be split into one or more query operators.
Common query operators include scan, join, and aggregation.

record In a relational database, a record corresponds to data in each row of a table.

redo log A log that contains information required for performing an operation again
in a database. If a database is faulty, redo logs can be used to restore the
database to its original state.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 337


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

relational A database created using the relational model. It processes data using
database methods of set algebra.

resource A collection of resources that can be accessed to obtain information.


library

RPO Recovery point objective (RPO) refers to the latest status that a database
system and the data can be restored to after a disaster, and it is usually
represented by time.

RTO Recovery time objective (RTO) refers to the duration between the database
system failure caused by a disaster and its restoration to proper running.

schema A database object set that includes the logical structure, such as tables,
views, sequences, stored procedures, synonyms, clusters, and database
links.

segment A segment in a database indicates a part containing one or more extents. An


extent is the smallest range of a database and consists of data blocks. One
or more segments comprise a tablespace.

session A job created by a database system for connection purposes when an


application attempts to connect to the database. Sessions are managed by
the session manager. They execute initial jobs to perform all user
operations.

SGA System global area (SGA). It is the cache management framework of


GaussDB 100. It contains most cache management components of the
storage engine and SQL engine, including PlanCache, DataBuffer,
DcCache, RedoBuffer, CkptBuffer, LockBuffer, TransactionBuffer, and
ReplicationBuffer.

shared pool A shared pool is created for repeatedly executed SQL statements to save
memory. It contains the explain trees and execution plans of given SQL
statements.

SQL Structured Query Language (SQL) is a standard database query language. It


consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used by
Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides three
basic security services, all of which use the public key technology. SSL
ensures the security of service communication through a network by
establishing a secure connection between a client and a server and then
sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup of the


server primary server. If the primary server is behaving abnormally, the standby
server is promoted to primary, ensuring uninterrupted data services.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 338


GaussDB 100
Database Reference (Standalone) 6 Glossary

Term Description

statistics Information that is automatically collected by databases, including table-


level information (number of tuples and number of pages) and column-level
information (column value range distribution histograms). Statistics in
databases are used to estimate the costs of query plans to find the plan with
the lowest cost.

stop word In computing, stop words are words which are filtered out before or after
processing of natural language data (text), saving storage space and
improving search efficiency.

stored A group of SQL statements compiled into a single execution plan and
procedure stored in a large database system. Users can specify a name and parameters
(if any) for a stored procedure to execute the procedure.

system A table storing meta information about a database. The meta information
catalog includes user tables, indexes, columns, functions, and data types in a
database.

table A set of columns and rows. Each column is referred to as a field. Values in
each field represent a data type. For example, if a table contains three fields
of person names, cities, and states, it has three columns: Name, City, and
State. In every row in the table, the Name column contains a name, the City
column contains a city, and the State column contains a state.

tablespace A tablespace is a logical storage structure that contains tables, indexes, and
objects. A tablespace provides an abstract layer between physical data and
logical data, and provides storage space for all database objects. When you
create an object, you can specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and are used
for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a database. A


transaction consists of a limited database operation sequence, and must
have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information library. A


WSR is generated by comparing statistics collected by two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively enter
queries, issue them to GaussDB 100, and view the query results. Queries
can also be entered from files. zsql supports many meta commands and
shell-like commands, allowing you to conveniently compile scripts and
automate jobs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 339


GaussDB 100
V300R001C00

DataSync User Guide (Standalone)

Issue 01
Date 2019-12-28

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties, guarantees
or representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
DataSync User Guide (Standalone) Contents

Contents

1 About This Document.............................................................................................................1


2 About DataSync....................................................................................................................... 4
2.1 System Architecture................................................................................................................................................................ 6
2.2 Software Requirements......................................................................................................................................................... 6
2.3 Constraints and Limitations................................................................................................................................................. 7
2.4 Structure of the Release Package...................................................................................................................................... 9

3 DataSync Syntax.................................................................................................................... 13
4 Working with DataSync....................................................................................................... 18
4.1 Configuration Files............................................................................................................................................................... 18
4.1.1 cfg.ini..................................................................................................................................................................................... 19
4.1.2 exp_obj.ini............................................................................................................................................................................ 38
4.1.3 exclusive_obj.ini.................................................................................................................................................................. 40
4.1.4 ignore_ddl.ini....................................................................................................................................................................... 41
4.1.5 exclusiveDataOnly_obj.ini............................................................................................................................................... 42
4.1.6 diff_ddl_obj.ini.................................................................................................................................................................... 43
4.2 Processes.................................................................................................................................................................................. 44
4.2.1 Export Process..................................................................................................................................................................... 44
4.2.2 Import Process.................................................................................................................................................................... 47
4.2.3 Export and Import Process............................................................................................................................................. 49
4.3 Reports...................................................................................................................................................................................... 51
4.3.1 Report for Automatic Table Creation......................................................................................................................... 51
4.3.2 DDL Synchronization Report......................................................................................................................................... 52
4.3.3 Data Export Report........................................................................................................................................................... 53
4.3.4 Data Import Report.......................................................................................................................................................... 54
4.3.5 Report for Export and Import........................................................................................................................................55
4.3.6 Incremental Migration Report.......................................................................................................................................56
4.4 Logs........................................................................................................................................................................................... 56
4.5 Data and File Clearing........................................................................................................................................................ 58
4.5.1 Clearing the Target Database....................................................................................................................................... 58
4.5.2 Deleting Local Files........................................................................................................................................................... 58

5 Data Migration.......................................................................................................................59

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
DataSync User Guide (Standalone) Contents

6 Security.................................................................................................................................... 63
6.1 Account Security....................................................................................................................................................................63
6.2 Security Statement............................................................................................................................................................... 64
6.3 Integrity Verification............................................................................................................................................................ 64
6.4 Data Transmission Security............................................................................................................................................... 65
6.5 Database SSL Connection.................................................................................................................................................. 65

7 Glossary................................................................................................................................... 67

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
DataSync User Guide (Standalone) 1 About This Document

1 About This Document

Overview
DataSync is a data migration tool provided by GaussDB 100 to securely, efficiently
synchronize data with other commercial databases. It can migrate data from
Sybase, Oracle, MySQL, GaussDB 100 V100R003C10, and SQL Server to GaussDB
100 V300R001. This document describes how to migrate data from Sybase, Oracle,
MySQL, GaussDB 100 V100R003C10, and SQL Server to GaussDB 100 V300R001
(standalone).

Intended Audience
This document is intended for:
● GaussDB 100 database administrators
● GaussDB 100 engineers

GaussDB 100 database administrators must:


● Be familiar with basic knowledge of GaussDB 100
● Be able to install, perform database operations in, and rectify faults in
GaussDB 100

GaussDB 100 engineers must:


● Understand basic knowledge of GaussDB 100
● Be able to perform database operations and rectify faults

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not


avoided, will result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in death or serious injury.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
DataSync User Guide (Standalone) 1 About This Document

Symbol Description

Indicates a potentially hazardous situation which, if not


avoided, could result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in equipment damage, data loss,
performance deterioration, or unanticipated results.
NOTICE is used to address practices not related to personal
injury.

Calls attention to important information, best practices, and


tips.
NOTE is used to address information not related to personal
injury, equipment damage, and environment deterioration.

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are


in italics.

[] Items (keywords and parameters) in brackets [ ] are


optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more


options or no item is selected.

{ x | y | ... } Indicates that one item is selected from two or more


options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
commas (,).

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
DataSync User Guide (Standalone) 1 About This Document

Change History
Version Update Date

01 This issue is the 2019-06-18


first official
release.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

2 About DataSync

DataSync supports online migration for GaussDB 100 V100R003C10 and offline
migration for Sybase, Oracle, MySQL, GaussDB 100 V100R003C10, and SQL Server.
To migrate data, you simply need to configure the source and target databases
before starting the tool. Related log files and reports are generated during
migration to facilitate routine management and maintenance.

DataSync provides the following functions:

● Offline data export


– Data can be exported to a local or remote directory.
– Databases, schemas, and tables to be exported can be specified and fuzzy
match is supported.
– Databases, schemas, and tables not to be exported can be specified and
fuzzy match is supported.
– WHERE and ORDER BY can be used to filter data to be exported.
– Column separator and row separator can be specified.
– Row-level data check is supported.
– Data files can be compressed during transmission.
– Concurrent export is supported for multiple tables and the number of
concurrent threads can be configured.
– Data export reports can be viewed.
● Offline data import
– Data can be imported from a local or remote directory.
– Data can be imported when the database, schema, or table name of the
source database is different from that of the target database.
– Databases, schemas, and tables to be imported can be specified and
fuzzy match is supported.
– Databases, schemas, and tables not to be imported can be specified and
fuzzy match is supported.
– Concurrent import is supported for a single table and multiple tables and
the number of concurrent threads can be configured.
– Target tables can be cleared before import.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

– Tables that do not exist in the target database can be ignored.


– Whether to disable triggers and foreign keys can be configured.
– Data can be imported in nologging mode.
– Row-level data check is supported.
– Data import reports can be viewed.
● Export+Import in online (GaussDB 100 V100R003C10) or offline mode
● Table structure check for offline migration. You can perform the check before
data migration or let DataSync automatically check table structures during
data migration.
– The following items are checked: whether the column sequence, column
lengths, and NOT NULL constraints in the source table are consistent
with those in the target table; and whether column types in the two
tables are compatible with each other.
– Whether to check the table structure can be configured.
– Whether to ignore the check of the column length, column type
compatibility, and NOT NULL constraint consistency for certain databases
and tables.
● Automatic table creation. Currently, if the source database is Sybase, MySQL,
Oracle, or SQL Server and the target database has no tables, the tool can
automatically create target tables based on the source table structures and
column mapping files, and automatically create indexes and constraints for
the tables.
– When a table is automatically created in the target database, the column
names, column types, and column lengths of the target table must be
consistent with those of the source table. If the target database does not
support a column data type of the source table, the tool will create the
table based on the data type specified in the mapping file. The mapping
file specifies the mappings of data types between source and target
databases.
– Tables that are automatically created in the target database are stored in
the tablespace specified by the table_space parameter in the cfg.ini file.
Indexes of each table are stored in the tablespace specified by the
index_table_space parameter in the cfg.ini file. If the two parameters
are not set, they are stored in the default tablespace of the user who
creates the tables.
– During automatic table creation, primary keys, foreign keys, NOT NULL
constraints, indexes, auto-increment sequences, and range partitions can
be created for Sybase, MySQL, and SQL Server tables, but comments and
DEFAULT constraints cannot. For Oracle tables, primary keys, foreign
keys, NOT NULL constraints, indexes, range partitions, and global
temporary tables can be created, but comments cannot. Also, for Oracle,
MySQL, and SQL Server tables, the clause for creating a foreign key
constraint must be ON DELETE { CASCADE | SET NULL }.
– If the name or column name of a source table contains GaussDB 100
keywords or special characters, the target table cannot be automatically
created in the target database. In this case, you need to manually create
the target table.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

– DataSync cannot synchronize the views, stored procedures, functions,


sequences, triggers, and homonyms of the source database to the target
database.

2.1 System Architecture


DataSync uses only a software architecture and does not have any hardware
characteristics. Figure 2-1 illustrates its architecture.

Figure 2-1 DataSync system architecture

2.2 Software Requirements


Table 2-1 describes the requirements of the DataSync deployment for the OS and
file system. Ensure that the OS is properly installed.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

Table 2-1 OS and user configuration requirements


Item Requirement

OS type and The x86 architecture supports the following OSs:


version ● Red Hat Enterprise Linux Server release 7.2 x86_64
● Red Hat Enterprise Linux Server release 7.4 x86_64
● Red Hat Enterprise Linux Server release 7.5 x86_64
● SUSE Linux Enterprise Server 11.3 (SUSE 11 for short),
x86_64
● SUSE Linux Enterprise Server 12.2 (SUSE 12 for short),
x86_64
● SUSE Linux Enterprise Server 12.4 (SUSE 12 for short),
x86_64
● EulerOS Server V2.0SP3 x86_64
● EulerOS Server V2.0SP5 x86_64
The ARM architecture supports the following OSs:
EulerOS Server V2.0SP8 ARM_64

File system Software installation: Ext4


Data storage: Ext4

2.3 Constraints and Limitations


Comply with the following constraints and limitations before using DataSync:
● The servers where the source and target databases are deployed are properly
connected.
● Identify the table structure of the target database in advance to ensure that
the column length, column type, and column non-null check of the source
table are compatible with those of the target table.
● The configured IP address, port number, username, and password can be used
to connect to the database.
● Space is sufficient to store the target database and to perform the migration.
● Java 1.8 or later has been installed on the device running DataSync.
● The JDBC driver of the source database is in the dependency-jars directory,
and the driver package name is the same as the specified one. Otherwise,
connecting to the database will fail. Alternatively, the tool can be called by
specifying the JAR package path. The following is an example:
java -Xbootclasspath/a:/sybaseDriver/jconn4_sybase.jar:/sybaseDriver/bcprov-jdk16-1.46.jar -jar
DSS.jar

● The password of a GaussDB 100 V300R001 database does not include spaces
or semicolons (;). Otherwise, the tool cannot use the zsql command to
connect to a database. For details, see "SQL Syntax Reference > SQL Syntax"
in GaussDB 100 V300R001 R&D Documentation (Standalone).

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

● The configuration user has sufficient permissions to perform required


operations. Table 2-2 describes permissions required for the configuration
user.
● All paths in the data_path configuration item must comply with the whitelist
rules of the migration tool. Specifically, a path cannot start with a hyphen (-)
or contain both / and \. It can contain only uppercase letters, lowercase
letters, digits, and the following special characters: \/:-_

Table 2-2 Configuration user permissions


Database Permission Operation Mandatory

Oracle create session Connect to a Yes


database.

select any Query system Yes


dictionary views and system
catalogs.

select any table Query the tables No, unless tables


of other users. of non-
configuration
users need to be
exported

MySQL select on Query databases No, unless tables


[Database-name]. and tables. of non-
[Table-name] configuration
users need to be
exported

Sybase select on [Table- Query tables. Yes


name] Involved tables
are as follows:
● sysindexes
● sysobjects
● syssegments
● syspartitions
● syscomments
● syspartitionkey
s
● syscolumns
● sysreferences
● systypes
● systabstats
● master..sysdata
bases

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

Database Permission Operation Mandatory

SQL Server select on [Table- Query tables. Yes


name] Involved tables
are as follows:
● sysobjects
● syscolumns
● systypes
● sysindexes
● master..sysdata
bases

GaussDB 100 create session Connect to a Yes


V300R001 database.

create any table Create a table. No, unless tables


need to be
automatically
created

select any table View the tables Yes


and DBA data
dictionaries of
other users.

create procedure Create a stored Yes


procedure.

alter system Modify database Yes


system
parameters.

DBA Provide all No, unless tables


database of non-
permissions. configuration
users need to be
imported

2.4 Structure of the Release Package


The installation package and integrity check file are provided together to protect
the package from being maliciously tampered with or damaged during
transmission, as described in Table 2-3.
The name of the DataSync release package is GAUSSDB100-V300R001C00-
DATASYNC.tar.gz. Table 2-4 describes its content.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

Table 2-3 Level-1 directories


Folder/File Description

DataSync.tar.gz DataSync tool package

DataSync.tar.gz.sha256 File used for Integrity Verification.

Table 2-4 Tool package


Folder/File Description

config DataSync configuration files, including:


● cfg.ini, used to configure server and database information
● exp_obj.ini, used to configure the databases and tables to
be exported or imported
● exclusive_obj.ini, used to configure the databases or
tables to be excluded during the migration.
● ignore_ddl.ini, used to configure the databases or tables
where DDL verification of table structures can be ignored.
● exclusiveDataOnly_obj.ini, used to configure the
databases or tables where only DDL-defined table
structures are exported or verified, and not actual data
(Note that all table structures are defined by DDL, so
below table structures all refer to DDL-defined table
structures.)
● diff_ddl_obj.ini, used to configure the tables (with a
different structure) to be exported or imported

DSS.jar JAR package used to deploy the server

log4j2.properties Configuration file used to generate logs

readme.txt Precautions

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

Folder/File Description

dependency-jars This folder stores Huawei-developed packages, open-source


third-party packages, and source database driver packages
required for tool running.
● Huawei-developed packages required for tool running:
dss_configmgr-0.0.1.jar, used by the data migration tool
dss_datacleanup-0.0.1.jar, used by the data migration
tool
dss_dataverify-0.0.1.jar, used by the data migration tool
dss_envconvert-0.0.1.jar, used by the data migration tool
dss_reportmgr-0.0.1.jar, used by the data migration tool
gsjdbc4-V100R003C10SPC118.jar, used by the GaussDB
100 V100R003C10 JDBC driver to connect to another
database
ZenithDriver-V300R001C00SPC100B137.jar, used by the
GaussDB 100 V300R001C10 JDBC driver to connect to
another database
● Open-source, third-party packages required for tool
running:
commons-beanutils-1.9.3.jar, used by the data migration
tool
commons-collections4-4.2.jar, used to generate CSV files
commons-compress-1.18.jar, used to compress files
commons-io-2.6.jar, used by the data migration tool
commons-lang3-3.9.jar, used by the data migration tool
commons-math3-3.6.1.jar, used by the data migration
tool
commons-net-3.6.jar, used by the data migration tool
commons-text-1.6.jar, used to generate CSV files
fastjson-1.2.56.jar, used to parse JSON files
gson-2.8.5.jar, used to parse JSON files
jsch-0.1.55.jar: used by users to create SSH connections
log4j-api-2.11.2.jar, used to print logs
log4j-core-2.11.2.jar, used to print logs
lombok-1.18.6.jar, used to simplify entities
opencsv-4.5.jar, used to generate CSV files
● Source database driver packages:
If the source database is Sybase, Oracle, MySQL, or SQL
Server, you need to copy the source database driver
package to this folder and change the package owner.
Ensure that the tool has execute permissions for the
folder.
Currently, the names of driver packages are fixed.
Sybase: jconn4-4.0.jar

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
DataSync User Guide (Standalone) 2 About DataSync

Folder/File Description

Oracle: ojdbc8-12.2.0.1.jar
MySQL: mysql-connector-java-5.1.44.jar
SQL Server: sqljdbc4-4.2.jar
If the source database is Sybase, you also need to copy
the driver package bcprov-jdk16-1.46.jar to this folder
and change the owner to that of the tool package.
The driver package name, bcprov-jdk16-1.46.jar, cannot
be modified.

TypeMappers Files used to configure database column type compatibility,


including:
● MysqlToGauss.json
Compatibility between MySQL and GaussDB 100
V300R001
● OracleToGauss.json
Compatibility between Oracle and GaussDB 100
V300R001
● SqlServerToGaussv3r1.json
Compatibility between SQL Server and GaussDB 100
V300R001
● Sybase157ToGaussdbv3r1.json
Compatibility between Sybase and GaussDB 100
V300R001
● V1R3C10ToGaussv3r1.json
Compatibility between GaussDB 100 V100R003C10 and
GaussDB 100 V300R001

FuncMappers Function configuration files that need to be converted when


default values are created, including:
● Oracle2V3R1.json
Compatibility between Oracle and GaussDB 100
V300R001

version.md Version construction information

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
DataSync User Guide (Standalone) 3 DataSync Syntax

3 DataSync Syntax

Syntax
● View help information.
java -jar DSS.jar -h | -help

Example:
java -jar DSS.jar -h
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Usage: java [JVM] -jar DSS.jar [options] filePath
JVM: Set jvm parameters if necessary,
eg:-Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./log
Options:
-h, -help
Show this help message and exit
-pwd <password type>, -password <password type>
Enter the clear text password for encryption
password type:
1--export database
2--import database
3--import server
4--export remote server
5--import remote server
6--export database trustStore
7--export database keyStore
8--import database trustStore
9--import database keyStore
-p <basic config file path>
Set basic config file path,use default if not specified
-i <export/import database or table config file path>
Set export database or table config file path,export all if not specified
-e <exclude database or table config file path>
Set exclude database or table config file path,exclude nothing if not specified
-l <log and report path>
Set export log and report path,use default path if not specified
-imp_b <import data failed path>
Set import data failed log file path,use default path if not specified
-t <incremental migration operation>
Set mission will execute incremental migration process and set trigger will create table and
trigger for business table.
-d <ignore DDL verification items file>
Set Ignore partial DDL verification of the database and tables
-o <only export/verify DDL>
Set the database and tables only export or verify DDL
-s <different DDL table export/import>
Set the tables which DDL is different between dest database and source database export
or import

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
DataSync User Guide (Standalone) 3 DataSync Syntax

If an invalid parameter is specified in a command, for example, java -jar


DSS.jar -a aaaa, the system displays the help information and the incorrect
parameter (highlighted in bold in the information) for your reference to make
corrections.
java -jar DSS.jar -a aaaa
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Error: Unrecognized option: -a
Usage: java [JVM] -jar DataSync.jar [options] filePath
JVM: Set jvm parameters if necessary,
eg:-Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./log
Options:
-h, -help
Show this help message and exit
-pwd <password type>, -password <password type>
Enter the clear text password for encryption
password type:
1--export database
2--import database
3--import server
4--export remote server
5--import remote server
6--export database trustStore
7--export database keyStore
8--import database trustStore
9--import database keyStore
-p <basic config file path>
Set basic config file path,use default if not specified
-i <export/import database or table config file path>
Set export database or table config file path,export all if not specified
-e <exclude database or table config file path>
Set exclude database or table config file path,exclude nothing if not specified
-l <log and report path>
Set export log and report path,use default path if not specified
-imp_b <import data failed path>
Set import data failed log file path,use default path if not specified
-t <incremental migration operation>
Set mission will execute incremental migration process and set trigger will create table and
trigger for business table.
-d <ignore DDL verification items file>
Set Ignore partial DDL verification of the database and tables
-o <only export/verify DDL>
Set the database and tables only export or verify DDL
-s <different DDL table export/import>
Set the tables which DDL is different between dest database and source database export
or import

● Generate the password ciphertext to be configured in the cfg.ini file.


In the directory where DSS.jar is located, run the java -jar DSS.jar -pwd
password_type command (-pwd can be replaced by -password here), and
enter the password as prompted. Then, the ciphertext password will be
generated.
In the above command, password_type indicates the type of the password (in
the cfg.ini file) for which the ciphertext will be generated. The value must be
an integer in the range [1, 9]. Value meanings are as follows:
– 1: password of the database user for export
– 2: password of the database user for import
– 3: password of the database installation user on the destination server for
import
– 4: password of the remote server where the data file used for the export
operation is located

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
DataSync User Guide (Standalone) 3 DataSync Syntax

– 5: password of the remote server where the data file used for the import
operation is located
– 6: password of the truststore file generated by the database for export
– 7: password of the keystore file generated by the database for export
– 8: password of the truststore file generated by the database for import
– 9: password of the keystore file generated by the database for import
Passwords must be encrypted one by one based on the type, and the
ciphertext cannot be reused. For example, if the plaintext password of the
database for export is the same as that of the database for import, you need
to run the java -jar DSS.jar -pwd 1 and java -jar DSS.jar -pwd 2 commands
to encrypt the two passwords. (-password can also be used in place of -pwd.)
Example:
dbuse@plat:~/gppTest/verf0603/DataSync> java -jar DSS.jar -pwd 1
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Please enter the password to be encrypted and press Enter to confirm!
The encrypted password is : O5gs+S9n18P3uVFohVhpEA==
Note: After a password of the same type has a new ciphertext generated, the
one generated last time will become invalid.
● Migrate data offline.
java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-d
ignore_ddl.ini_path] [-o exclusiveDataOnly_obj.ini] [-s diff_ddl_obj.ini] [-l /data/gaussdba/log_path] [-
imp_b importerrorlog_path]
Example:
In the directory where DSS.jar is located, run the following command:
java -jar DSS.jar -p ./config/cfg.ini -i ./config/exp_obj.ini -e exclusive_obj.ini
DataSync (1.1.1), From Huawei !
Copyright ©@ Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start syncing data................................[ok]
Data exporting....................................[0/1]
Data export completed.............................[1/1]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 14:10:58]
Task end time.....................................[2019-06-13 14:11:13]
Total spent time..................................[15.109s]
Export successful data (rows).....................[100]
Export failed data (rows).........................[0]
Export data failed table count....................[0]
For details about how to migrate data offline, see Offline Migration.
● Migrate data online.
– Create a trigger, which is used to create incremental tables in the source
database.
java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-l /data/
gaussdba/log_path] [-imp_b importerrorlog_path] -t trigger
Example:
In the directory where DSS.jar is located, run the following command:
java -jar DSS.jar -p ./config/cfg.ini -i ./config/exp_obj.ini -e exclusive_obj.ini -t trigger
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start init increments
increment initializing............................[0/1]
increment initializing............................[1/1]
increment initialize done.........................[1/1]

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
DataSync User Guide (Standalone) 3 DataSync Syntax

Task start time...................................[2019-06-13 14:24:37]


Task end time.....................................[2019-06-13 14:24:39]
Total spent time..................................[2.556s]
Log details path..................................[./logs/reports_2019-06-13/14h-24m-37s/]

– Perform incremental table migration.


java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-l /data/
gaussdba/log_path] [-imp_b importerrorlog_path] -t mission
Example:
In the directory where DSS.jar is located, run the following command:
java -jar DSS.jar -p ./config/cfg.ini -i ./config/exp_obj.ini -e exclusive_obj.ini -t mission
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing increments..........................[ok]
commited/failed/remaining.........................[1/0/0]
spent :1.002s
Task start time...................................[2019-06-13 14:28:29]
Task end time.....................................[2019-06-13 14:28:33]
Total spent time..................................[3.731s]
Logs details path.................................[./logs/reports_2019-06-13/14h-28m-29s/]

For details about how to migrate data online, see Online Migration.

Parameter Description

Table 3-1 DataSync parameters


Parameter Description

-h, -help Shows help information.

-pwd, -password Generates the password ciphertext to


be configured in the cfg.ini file.

-p Specifies the path of the cfg.ini


configuration file. If this parameter is
not specified, the data migration tool
automatically accesses Current tool
directory/config/cfg.ini.
This parameter is optional.

-i Specifies the path of the exp_obj.ini


configuration file. If this parameter is
not specified, the data migration tool
does not use the exp_obj.ini file.
This parameter is optional.

-e Specifies the path of the


exclusive_obj.ini configuration file. If
this parameter is not specified, the
data migration tool does not use the
exclusive_obj.ini file.
This parameter is optional.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
DataSync User Guide (Standalone) 3 DataSync Syntax

Parameter Description

-l Specifies the path for generating data


migration logs. If this parameter is not
specified, migration logs are generated
in the path of the data migration tool.
This parameter is optional.

-imp_b Specifies the error information file of


import operations. If this parameter is
not specified, the file is generated in
the home directory of the target
database installation user configured
in the cfg.ini file by default.
This parameter is optional.

-t This parameter can be used only to


migrate data online from GaussDB 100
V100R003C10. Its value can be trigger
(creating an incremental trigger) or
mission (performing incremental
migration).

-d Specifies the path of the


ignore_ddl.ini configuration file. If this
parameter is not specified, the data
migration tool does not use the
ignore_ddl.ini file.
This parameter is optional.

-o Specifies the path of the


exclusiveDataOnly_obj.ini
configuration file. If this parameter is
not specified, the data migration tool
does not use the exclusiveDataOn-
ly_obj.ini file.
This parameter is optional.

-s Specifies the path of the


diff_ddl_obj.ini configuration file. If
this parameter is not specified, the
data migration tool does not use the
diff_ddl_obj.ini file.
This parameter is optional.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

4 Working with DataSync

4.1 Configuration Files


DataSync has the following configuration files:
● cfg.ini, used to configure server and database information. This configuration
file is mandatory.
● exp_obj.ini, used to configure the databases, schemas, and tables to be
exported or imported. This configuration file is optional.
● exclusive_obj.ini, used to configure the databases, schemas, or tables to be
excluded during the migration. This configuration file is optional.
● ignore_ddl.ini, used to configure the databases, schemas, or tables excluded
from verification of the DDL-defined table structure during the migration. This
configuration file is optional.
● exclusiveDataOnly_obj.ini, used to specify that only the DDL-defined table
structure is exported or verified, and databases, schemas, and tables are not
exported or imported. This configuration file is optional.
● diff_ddl_obj.ini, used to configure the columns to be migrated in the source
table. The DDL of the source table does not need to be the same as that of
the target table. This configuration file is optional.
DataSync checks these configuration files. If any errors are detected, DataSync will
stop running, write the error information to the dss_info_log.log file, and display
the error information in the command output. You can correct the errors
accordingly and restart DataSync.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

● Ensure the cfg.ini path is correct. If the specified file is empty, an error will be reported.
● Data import and export operations vary based on the first three configuration files you
use. The rules are as follows:
● If cfg.ini alone is used, all data will be imported or exported.
● If both cfg.ini and exp_obj.ini are used, only data of the databases, schemas, and
tables specified in exp_obj.ini is imported or exported.
● If both cfg.ini and exclusive_obj.ini are used, data of the databases, schemas, and
tables specified in exclusive_obj.ini is excluded from the import or export.
● If cfg.ini, exp_obj.ini, and exclusive_obj.ini are all used, data of the databases,
schemas, and tables that are specified in exp_obj.ini and not specified in
exclusive_obj.ini is exported.
● By default, data in the system database, system tables, and temporary databases is
excluded. You need to specify the databases and tables to export such data. Table 4-1
describes the databases and tables excluded by default.

Table 4-1 Automatically excluded databases and tables


Database Database Name/ Table Name
Username

mysql information_schema, -
mysql,
performance_schema,
sys, test

oracle sys, system A table name contains


the dollar sign ($).

SqlSever master, tempdb, model,


msdb

Sybase master, model, tempdb, A table name starts with


sybsystemdb, a number sign (#).
sybsystemprocs,
sybmgmtdb

V1R3 TEMP A table name starts with


PG_ or SQL_.

4.1.1 cfg.ini
Server and database information is configured in the cfg.ini file. Before data
migration, ensure the information is correct. Table 4-2 describes the parameters in
the cfg.ini file.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Table 4-2 Parameters in the cfg.ini file


Parameter Description Value Range Default Value

flow_type System process 1, 2, 3, 4, and 5 3


type ● 1: Export data
from the
source
database. That
is, Export
Process.
● 2: Import data
to the target
database. That
is, Import
Process.
● 3: Export data
from the
source
database and
import it to the
target
database. That
is, Export and
Import
Process.
● 4: Check
whether the
structures of
source and
target tables
are the same
without
importing or
exporting data
● 5: Verify table
structures
before import,
without
importing data.
(Note: In this
scenario, the
tool cannot
verify source
data. You need
to ensure the
data
consistency.)

export_db Source database - -


information

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

import_db Target database - -


information

database_type Database type 1, 2, 3, 4, 5, and 6 The default type


● 1: Sybase of the source
database is 1. The
● 2: Oracle default type of
● 3: MySQL the target
● 4: GaussDB database is 6.
100
V100R003C10
● 5: SQL Server
● 6: GaussDB
100 V300R001

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

db Basic parameters - -
of source and
target databases,
including:
● ip: database IP
address
● port: database
port
● username:
database
username. Do
not set it to
SYS for
GaussDB 100.
● password:
database
password
● server_name:
service name.
It is mandatory
if the source
database is
Oracle.
● db_name:
database
name. This
parameter is
mandatory
when the
source
database is
MySQL,
GaussDB 100
V100R003C10,
or SQL Server.
● trust_store:
Java-identified
truststore file,
where
OpenSSL or
Keytool
imports the
root certificate
● trust_store_pa
ssword:
ciphertext of
the generated
truststore file

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

● key_store:
Java-identified
keystore file,
where
OpenSSL or
Keytool
imports the
client
certificate and
private key
● key_store_pas
sword:
ciphertext of
the generated
keystore file
● table_space:
name of the
tablespace
specified for
automatically
created tables.
● index_table_s
pace: name of
the index
tablespace
specified for
automatically
created tables.
Note: If SSL is
enabled on
database servers,
select and
configure these
parameters based
on the SSL
configuration to
ensure that the
migration tool is
connected
properly.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

server Basic parameters - -


of the server
where the target
database is
located, including:
● ip: server IP
address
● port: server
port. The
default value is
22.
● username:
name of the
user installing
the target
database
● password:
password of
the user
installing the
target
database
● pub_key_file:
path of the
certificate file
which is used
for password-
free login
Note 1: You can
set either
password or
pub_key_file for
DataSync to
connect to the
server. If both
password and
pub_key_file are
set, pub_key_file
prevails for the
server connection.
Note 2: If
DataSync is
deployed in the
directory of the
GaussDB 100
installation user,
you can configure
only ip, port, and
username, but

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

not password or
pub_key_file. In
this case, ip can
be set to
127.0.0.1.

data_path Path from which - -


data files are
imported or to
which data files
are exported

export_local_path Local storage - -


path of exported
data. By default,
it is the home
directory of the
Datasync
installation user.
Ensure that the
installation user
has read and
write permissions
for the path.
Note: It is a path
on the server
where Datasync is
deployed.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

export_remote_pa Remote storage - -


th path of exported
data. The
following
information is
required:
● ip: IP address
of the remote
server
● port: remote
server port.
The default
value is 22.
● username:
server
username
● password:
server
password
● pub_key_file:
path of the
certificate file
which is used
for password-
free login
● path: file
export path
Note: You can set
either password
or pub_key_file
for DataSync to
connect to the
server. If both
password and
pub_key_file are
set, pub_key_file
prevails for the
server connection.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

import_local_path Local path of data - -


files to be
imported. By
default, it is the
home directory of
the database
installation user.
Ensure that the
Datasync
installation user
has read and
write permissions
for the directory.
Note: It is a path
on the Gauss 100
database server.
Ensure that the
data files to be
imported exist in
this path.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

import_remote_pa Remote path of - -


th data files to be
imported. The
following
information is
required:
● ip: IP address
of the remote
server
● port: remote
server port.
The default
value is 22.
● username:
server
username
● password:
server
password
● pub_key_file:
path of the
certificate file
which is used
for password-
free login
● path: path of
the data files
to be imported
Note: You can set
either password
or pub_key_file
for DataSync to
connect to the
server. If both
password and
pub_key_file are
set, pub_key_file
prevails for the
server connection.

column_separator Column delimiter - ~~~~~

row_separator Row delimiter - @#\n#@

data_check_type Data check mode. 1 1


Currently, it can
only be set to 1
(row-level check).

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

compression_befo Whether to true and false false


re_translate compress data ● true:
files during data Compress.
transmission
● false: Do not
compress.

disable_foreign_ke Whether to true and false true


y disable foreign ● true: Disable.
keys before
importing data. If ● false: Do not
foreign keys are disable.
disabled, they will
be enabled after
the import is
complete.

check_ddl Whether to check true and false true


the consistency of ● true: Check.
column names,
column ● false: Do not
quantities, and check.
NOT NULL
constraints as well
as the data type
and column
length
compatibility
between the
source and target
tables.

nls_lang Character set of utf8 and gbk utf8


imported data

delete_file Whether to delete true and false true


local files after ● true: Delete.
the import is
successful. ● false: Do not
delete.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

ignore_lost_table Whether to ignore 1, 2, and 3 2


tables that do not ● 1: Ignore. No
exist in the target error is
database reported, and
the import or
export process
continues.
● 2: Do not
ignore. An
error is
reported, and
the import or
export process
stops.
● 3: If a table
does not exist
in the target
database, the
table will be
automatically
created based
on the table
information in
the source
database. In
addition, the
primary key,
indexes,
foreign keys,
auto-increment
columns, and
range
partitions will
be created.
Currently, only
Sybase, Oracle
(default values
are supported),
MySQL, and
SQL Server
support
automatical
table creation.
Note:
● Information
required for
creating tables
is obtained
from the

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

source
database only
when this
parameter is
set to 3.
● If a table in the
target
database is
created by the
user, the tool
will not modify
the table
structure or
other
information.
For example, if
a source table
in the source
database has
indexes and
the user has
not created
indexes when
creating the
target table in
the target
database, the
tool will not
create indexes
on the target
table during
data migration.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

disable_trigger Whether to true and false true


disable triggers. ● true: Disable.
Determine ● false: Do not
whether to disable.
disable triggers
before importing
data to the target
database. If
triggers will be
disabled, before
the import
operation, the
tool will create
two stored
procedures to
disable and
enable all triggers
in the target
database,
respectively; and
then run one to
disable all
triggers. After the
import operation,
the tool will run
the other to
enable all
triggers.

check_obj_exists Whether to check true and false true


for the existence ● true: Check.
of tables and
databases in the ● false: Do not
source and target check.
databases

ignore_sync_ddl Whether to true and false false


continue ● true: Continue
importing tables the import.
that pass the
DDL-based table ● false:
structure check Terminate the
when there are import.
tables failing the
check

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

ignore_case_in_ex Whether to ignore true and false false


c the case ● true: Ignore.
sensitivity in the
exclusive_obj.ini ● false: Do not
and ignore.
diff_ddl_obj.ini
configuration files

multiple_schema Whether GaussDB true and false false


100 V100R003C10 ● true: Support.
supports cross-
schema migration ● false: Do not
support.

fetch_size Number of rows Positive integer 2000


to be fetched in a
query through
JDBC

disable_index Whether to true and false false


disable indexes ● true: Disable.
Before an import,
the system ● false: Do not
determines disable.
whether to
disable indexes. If
indexes are
disabled, enable
them after the
import.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

create_tab_with_d Whether to true and false false


efault provide default ● true: Default
values for values are
columns of an provided.
automatically
created table ● false: Default
values are not
provided.
Currently, default
column values can
be provided
during
automatical table
creation only
when the source
database is the
Oracle database.
If the default
value is
represented by a
function, you
need to identify
the mapping
between the
source database
function and the
target database
function and
configure the
mapping in the
FuncMappers/
Oracle2V3R1.json
file.
In Oracle, run the
following SQL
statement to
query for the
default values of
table columns:
SELECT t.table_name
oname,c.column_id
cid,c.column_name
cname,c.data_type
yname, c.nullable
allownulls,
c.DATA_DEFAULT
FROM all_tables t LEFT
JOIN all_tab_columns c
ON t.table_name =
c.table_name WHERE
t.owner = '[owner]'
AND c.owner =
'[owner]' AND
c.DATA_DEFAULT is

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value


not null ORDER BY
t.table_name,c.column_i
d;

import_nologging Whether to true and false false


import data in ● true: Use the
nologging mode nologging
mode.
● false: Do not
use the
nologging
mode.

import_threads_p Number of An integer in the 10


er_obj concurrent range [1, 100]
threads for
importing a table.
Log in to the
target database
and run the
SHOW
PARAMETER
SESSIONS and
SHOW
PARAMETER
OPTIMIZED_WO
RKER_THREADS
command to
check the
maximum
number of
sessions and the
number of
optimal work
threads,
respectively.
Ensure that the
value of
import_total_tas
k is no greater
than either of the
two values and
that the number
of available
sessions is greater
than the specified
parameter value.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

import_total_task Number of An integer in the 5


concurrent range [1, 100]
threads for
importing all
tables.
On the target
database server,
check the value of
MaxSessions in
the /etc/ssh/
sshd_config file.
Then, log in to
the target
database and run
the SHOW
PARAMETER
SESSIONS and
SHOW
PARAMETER
OPTIMIZED_WO
RKER_THREADS
command to
check the
maximum
number of
sessions and the
number of
optimal work
threads,
respectively.
Ensure that the
value of
import_total_tas
k is no greater
than any of the
three values and
that the number
of available
sessions is greater
than the specified
parameter value.

import_allow_max Allowed ≥0 0
_errors maximum
number of rows
that fail to be
imported to a
single table

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

import_force Whether to true and false true


continue ● true: Continue.
importing data
after the import ● false: Do not
fails continue.

import_check_row Whether to true and false false


_count calculate the ● true: Calculate.
number of rows
in the target table ● false: Do not
after the export calculate.
and import
process is
complete

truncate_before_i Whether to clear true and false true


mport_db_data the target table ● true: Clear.
before the import
process or the ● false: Do not
export+import clear.
process

export_system_ro Offset of row ≥0 10


wcount_offset count obtained by
querying the
system view
during export

export_total_task Table-level An integer in the 10


concurrency range [1, 100]
during export
On the source
database server,
check the value of
MaxSessions in
the /etc/ssh/
sshd_config file.
The value of
export_total_task
cannot be greater
than the value of
this parameter.

export_allow_max Allowed ≥0 0
_errors maximum
number of rows
that fail to be
exported from a
single table

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Value Range Default Value

export_force Whether to true and false true


continue ● true: Continue.
exporting data
after the import ● false: Do not
fails continue.

export_check_row Whether to true and false false


_count calculate the ● true: Calculate.
number of rows
in the source ● false: Do not
table during calculate.
export

export_append_on Whether to true and false false


import the data ● true: Import
separately data at a time.
exported from the
source database ● false: Do not
to the target import data at
database at a a time.
time

export_max_rown Maximum ≥-1 -1 (all rows are


um number of rows exported)
that can be
exported from a
table

4.1.2 exp_obj.ini
You can configure databases and tables to be migrated. This file is optional.

Description
Databases and tables to be migrated are configured as follows:
Source-database-name[.Source-table-name][:Target-database-name.[Target-table-name]] [Filter-criteria]

● Content in square parentheses ([]) is optional.


● Filter conditions must be placed behind the new name or table name of the
mapping and separate from it by a space.
● Each mapping occupies one line.
● Configuration information can be added only to the blank area above ###
Parameter Description.
● If no mapping is configured, the database and table names of the source
database are considered the same as those of the target database by default.
● A filter condition must start with WHERE or ORDER BY. If both of them are
used, the condition must start with WHERE.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

● Databases and table names support fuzzy match. \% matches multiple


characters, and \_ matches a single character. For example, haha\% exports
all databases and tables starting with haha.
● If this file is empty or not configured, all the databases and tables, excluding
system databases, system catalogs, and temporary tables, are exported.
● If cross-schema migration is not supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name[.Schema-name_Table-
name][:Target-database-name.Table-name]. (In this case, only the public
schema is supported.)
● If cross-schema migration is supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name[.Schema-name][.Table-
name][:Target-database-name.Table-name]. (The mapping is mandatory for
synchronization of the public schema.)
● If no source table names are configured, all tables in the specified source
database are imported.

Precautions
● If no tables are specified in the exp_obj.ini file, all tables in the source
database (excluding system catalogs and temporary tables) are exported.
● In Oracle and GaussDB 100 V100R003, database names and table names are
case-insensitive in database or table creation statements, but uppercase is
adopted for statement execution by default. Therefore, database names and
table names must be in upper case in the configuration file. (If a database
name or table name is enclosed in double quotation marks ("") in the
statement, the name is case-sensitive. In this case, the letter case of the name
in the configuration file must be the same as that in the statement.)
● In Sybase, MySQL, and SQL Server, database names and table names are
case-sensitive in database or table creation statements. Therefore, the letter
case of a name in the configuration file must be the same as that in the
statement.
● If cross-schema migration is supported by GaussDB 100 V100R003, the
schema name of the source database is mapped to that of the target
database by default. Incremental migration does not support cross-schema
migration.

Examples
● Export databases db1 and db2. The database and table names to be imported
are the same as those exported.
db1
db2

● Export databases db1 and db2, and map db1 to db3.


db1:db3
db2

● Export the t_test table of the db1 database, specify the filter criteria for
exporting the t_test2 table of the db2 database, and map db2.t_test2 to
db3.t_test3.
db1.t_test
db2.t_test2:db3.t_test3 where rownum<=10

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

4.1.3 exclusive_obj.ini

Scenario
You can configure databases and tables that are excluded from migration.

Description
The databases and tables excluded from migration are configured as follows:
Source-database-name[.Table-name]

● Content in square parentheses ([]) is optional.


● Use commas (,) to separate multiple conditions.
● Add the configuration to the blank area above ### Parameter Description.
● If cross-schema migration is not supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name_Table-name.
(In this case, only the public schema is supported.)
● If cross-schema migration is supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name.Table-name.
● The databases and tables support fuzzy match.
\%: any number of characters or no characters, for example, haha\%
\_: an unknown character, for example, hah\_

Precautions
● If this file is not configured, no databases or tables will be excluded during
migration.
● In Oracle and GaussDB 100 V100R003, database names and table names are
case-insensitive in database or table creation statements, but uppercase is
adopted for statement execution by default. Therefore, database names and
table names must be in upper case in the configuration file. (If a database
name or table name is enclosed in double quotation marks ("") in the
statement, the name is case-sensitive. In this case, the letter case of the name
in the configuration file must be the same as that in the statement.)
● In Sybase, MySQL, and SQL Server, database names and table names are
case-sensitive in database or table creation statements. Therefore, the letter
case of a name in the configuration file must be the same as that in the
statement.
● Mapping cannot be configured in the file.

Examples
● Exclude the DB1 and DB2 databases during data import. (example for Oracle
and GaussDB 100 V100R003).
DB1,DB2

● Exclude the t_test table of the db1 database and the t_test table of the db2
database during data import. (example for Sybase, MySQL, and SQL Server)
db1.t_test,db2.t_test2

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

4.1.4 ignore_ddl.ini
Scenario
You can configure databases and tables in which DDL-based table structure
verification can be ignored during migration.

Description
The database or table ignoring table structure verification is configured as follows:
Source-database-name[.Table-name]
● Content in square parentheses ([]) is optional.
● Use commas (,) to separate multiple databases or tables.
● Configure some databases and tables to ignore certain DDL verification items.
● The databases and tables support fuzzy match.
\\%: any number of characters or no characters, for example, haha\\%
\\_: an unknown character, for example, hah\\_

Precautions
● If this file is not configured, DDL verification is always needed during the
migration.
● In Oracle and GaussDB 100 V100R003, database names and table names are
case-insensitive in database or table creation statements, but uppercase is
adopted for statement execution by default. Therefore, database names and
table names must be in upper case in the configuration file. (If a database
name or table name is enclosed in double quotation marks ("") in the
statement, the name is case-sensitive. In this case, the letter case of the name
in the configuration file must be the same as that in the statement.)
● In Sybase, MySQL, and SQL Server, database names and table names are
case-sensitive in database or table creation statements. Therefore, the letter
case of a name in the configuration file must be the same as that in the
statement.
● Mapping cannot be configured in the file.
● If cross-schema migration is not supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name_Table-name.
(In this case, only the public schema is supported.)
● If cross-schema migration is supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name.Table-name.
● The file is in JSON format. Therefore, you only need to add databases and
tables in square parentheses ([]). Any other changes may cause damage to
the file or ignorance failure.

Examples
● Database names and table names must be in upper case in the configuration
file.
During DDL verification, for all tables of the DB1 and DB2 databases,
verifications of type compatibility are ignored.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

"notCheckType":["DB1","DB2"]

● The letter case of a name in the configuration file must be the same as that
in the creation statement.
During DDL verification, for the t_test table of the db1 database and the
t_test table of the db2 database, verifications on whether the length of the
target column is less than that of the source column are ignored. (example
for Sybase, MySQL, and SQL Server)
"notCheckLength":["db1.t_test","db2.t_test"]

4.1.5 exclusiveDataOnly_obj.ini
Scenario
If some databases or tables only need to export or verify their table structures and
do not need to import or export their data during data migration, you can
configure these databases and tables in the exclusiveDataOnly_obj.ini file.

Description
The databases and tables that only need to export or verify DDL-defined table
structures are configured as follows:
Source-database-name[.Table-name]
● Content in square parentheses ([]) is optional.
● Use commas (,) to separate multiple conditions.
● Add the configuration to the blank area above ### Parameter Description
in the configuration file.
● If cross-schema migration is not supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name_Table-name.
(In this case, only the public schema is supported.)
● If cross-schema migration is supported by GaussDB 100 V100R003, the
configuration is as follows: Source-database-name.Schema name.Table-name.
● The databases and tables support fuzzy match.
\%: any number of characters or no characters, for example, haha\%
\_: an unknown character, for example, hah\_

Precautions
● If the exclusiveDataOnly_obj.ini file is not configured, no databases or tables
will be processed as follows: only DDL-defined table structures are exported
or verified and no data is exported or imported.
● In Oracle and GaussDB 100 V100R003, database names and table names are
case-insensitive in database or table creation statements, but uppercase is
adopted for statement execution by default. Therefore, database names and
table names must be in upper case in the configuration file. (If a database
name or table name is enclosed in double quotation marks ("") in the
statement, the name is case-sensitive. In this case, the letter case of the name
in the configuration file must be the same as that in the statement.)
● In Sybase, MySQL, and SQL Server, database names and table names are
case-sensitive in database or table creation statements. Therefore, the letter

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

case of a name in the configuration file must be the same as that in the
statement.
● Mapping cannot be configured in the file.

Examples
● Only export or verify structures of tables in the DB1 and DB2 databases
(example for Oracle and GaussDB 100 V100R003).
DB1,DB2
● Only export or verify the structure of the t_test table in the db1 database and
the t_test2 table in the db2 database (example for Sybase, MySQL, and SQL
Server).
db1.t_test,db2.t_test2

4.1.6 diff_ddl_obj.ini
Scenario
If source and target tables have different DDLs and you want to migrate data of
certain columns in the source table, configure the involved table and column
names in the diff_ddl_obj.ini file to migrate such data.

Description
Configure the migration as follows:
Source-database-name.Source-table-name:Source-database-column-name[(Target-database-column-
name)]
● Content in square parentheses ([]) is optional.
● You can configure multiple column names that are separated with commas
(,).
● You can configure multiple table names and each table has its configuration
information in a separate line.
● Add the configuration to the blank area above ###Parameter Description.
● If cross-schema migration is not supported by GaussDB 100 V100R003C10,
the configuration is as follows: Database-name.Schema-name_Table-
name:Source-database-column-name[(Target-database-column-name)]. (In
this case, only the public schema is supported.)
● If cross-schema migration is supported by GaussDB 100 V100R003C10, the
configuration is as follows: Database-name.Schema name.Table-name:Source-
database-column-name[(Target-database-column-name)].
● This file does not support fuzzy match.
● Column names configured in this file are case insensitive. However, for
columns with the same name but different letter cases in source or target
tables, configure the column names as they are.

Precautions
● If this file is not configured, mapping between the source and target table will
not be specified.
● By default, database and table names are created in uppercase in Oracle and
GaussDB 100 V100R003C10 databases. Therefore, the database and table

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

names configured in the configuration file must be also in uppercase. (If


names are enclosed in double quotation marks ("") in database or table
creation statements, use the names as specified in statements.)
● In Sybase, MySQL, and SQL Server, database and table names are case-
sensitive in creation statements. Therefore, the letter case of a name in the
configuration file must be the same as that in the statement.
● Only column mapping is supported in this file.
● If the target table contains NOT NULL columns or primary keys, configure
NOT NULL columns without auto-increment or default values and primary
keys without auto-increment. Otherwise, the import will fail.
● If the diff_ddl_obj.ini file is used for a separate import or export, load this file
for both the import and export.
● If a column configured in the diff_ddl_obj.ini file does not exist in the source
or target table, but the corresponding column data exists during the import or
export, Datasync automatically deletes the data. Therefore, after the
migration is complete, refer to the DDLReport.csv file to check whether
columns are deleted by Datasync by mistake.

Examples
● Migrate only the ID and NAME columns of TABLE1 in the DB1 database
(example for Oracle and GaussDB 100 V100R003).
DB1.TABLE1:ID,NAME

● Migrate only the id and name columns of table2 in the db2 database to the
num and nickname columns of the table in the target database, respectively
(example for Sybase, MySQL, and SQL Server).
db2.table2:id(num),name(nickname)

4.2 Processes
Data migration supports the following processes: export process, import process,
and export and import process. You can choose from them as needed.

4.2.1 Export Process


Scenario
This process is applicable to the scenario where the DataSync server can connect
to only the source database or users only need to export data from the source
database.
Note: The DataSync server must be able to connect to the source database.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

cfg.ini File Example

● You do not need to configure the target database and server information in the export
process. Ensure that the file is in JSON format.
● Set flow_type=1 for the export process.
● The local export path under data_path is optional. If it is not specified, the exported file
is generated in the home directory of the user who started DataSync. To specify the
path, ensure that the path is accessible to the user running DataSync.
● A remote path can be configured. The exported file is generated in the configured
remote path and the local file is automatically deleted.
{
"flow_type":1,
"export_db":{
"database_type":2,
"db":{
"ip":"192.168.0.1",
"username":"onetypeuser",
"password":"urEkRwfVrNKEQ4dMeRvj8g==",
"port":1521,
"db_name":"",
"server_name":"orcl",
"trust_store":"",
"trust_store_password":"",
"key_store":"",
"key_store_password":""
}
},
"import_db":{
"database_type":6,
"db":{
"ip":"",
"username":"",
"password":"",
"port":1888,
"trust_store":"",
"trust_store_password":"",
"key_store":"",
"key_store_password":""
"table_space":"",
"index_table_space":""
},
"server":{
"ip":"",
"username":"",
"password":"",
"pub_key_file":"",
"port":22
}
},
"data_path":{
"export_local_path":"",
"export_remote_path":{
"ip":"192.168.0.1",
"username":"dbuser",
"password":"O5gs+S9n18P3uVFohVhpEA==",
"pub_key_file":"",
"port":22,
"path":"/home/dbuser/haha"
},
"import_local_path":"",
"import_remote_path":{
"ip":"",
"username":"",
"password":"",
"pub_key_file":"",

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

"port":22,
"path":""
}
},
"option":{
"column_separator":"~~~~~",
"row_separator":"@#\n#@",
"data_check_type":1,
"compression_before_translate":false,
"disable_foreign_key":true,
"check_ddl":true,
"nls_lang":"utf8",
"delete_file":true,
"ignore_lost_table":2,
"disable_trigger":true,
"check_obj_exists":true,
"ignore_sync_ddl":false,
"import_nologging":false,
"create_tab_with_default":false,
"import_threads_per_obj":10,
"import_total_task":5,
"import_allow_max_errors":0,
"import_force":false,
"import_check_row_count":false,
"truncate_before_import_db_data":true,
"export_system_rowcount_offset":10,
"export_total_task":10,
"export_allow_max_errors":0,
"export_force":false,
"export_check_row_count":false,
"export_append_on":false,
"export_max_rownum":-1
}
}

Export Process Output


Implement the export process.
java -jar DSS.jar -p config/cfg.ini -i config/exp_obj.ini -e config/exclusive_obj.ini

After the export is complete, the following information is displayed:


DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start syncing data................................[ok]
Data exporting....................................[0/1]
Data export completed.............................[1/1]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 15:01:36]
Task end time.....................................[2019-06-13 15:01:45]
Total spent time..................................[9.143s]
Export successful data (rows).....................[100]
Export failed data (rows).........................[0]
Export ddl failed table count................[0]
Export data failed table count....................[0]
Report details path...............................[./logs/reports_2019-06-13/15h-01m-36s/]

The information Export ddl failed table count.....................[0] in bold is displayed only
when the source database is Sybase.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

4.2.2 Import Process


Scenario
This process applies when the server where DataSync is installed can only connect
to the target database or data only needs to be imported to the target database.
Note:
● The server of the tool must be able to connect to the target database.
● If DataSync is deployed on a Gauss database server, only the GaussDB 100
installation user can run it.
● The export process must be executed beforehand by using the tool, and the
ddlResult folder generated in the export process needs to be copied to the
directory of the tool for import, at the same level as the DSS.jar folder.

cfg.ini File Example

● You do not need to configure the source database information during the import
process. Ensure that the file is in JSON format.
● Set flow_type=2 for the import process.
● Ensure server and database information is correctly configured. Otherwise, DataSync
cannot properly connect to the server and database.
● The data_path parameter can be set to a local data file path used for the import. The
path must be accessible to the user running DataSync, and the data files to be exported
must exist in the path. You can also set a remote path. If the parameter is not set, the
home directory of the user running DataSync is used by default.
● If both the password and pub_key_file parameters are configured, pub_key_file will be
used for connecting to the server. You are advised to select only one of the two.
● If pub_key_file is used and if DataSync, data files, and GaussDB 100 V300R001C00 are
deployed on three different servers, you need to manually configure the password-free
connection between the servers of GaussDB 100 V300R001C00 and the data files so that
GaussDB 100 V300R001C00 can obtain data files through SCP in password-free mode.
{
"flow_type":2,
"export_db":{
"database_type":1,
"db":{
"ip":"",
"username":"",
"password":"",
"port":4100,
"db_name":"",
"server_name":"",
"trust_store":"",
"trust_store_password":"",
"key_store":"",
"key_store_password":""
}
},
"import_db":{
"database_type":6,
"db":{
"ip":"192.168.0.1",
"username":"testsybase1",
"password":"U06lpFo5LlP9wvL4Kt4E4A==",
"port":1888,

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

"trust_store":"",
"trust_store_password":"",
"key_store":"",
"key_store_password":""
"table_space":"",
"index_table_space":""
},
"server":{
"ip":"192.168.0.1",
"username":"dbuser",
"password":"O5gs+S9n18P3uVFohVhpEA==",
"pub_key_file":"",
"port":22
}
},
"data_path":{
"export_local_path":"",
"export_remote_path":{
"ip":"",
"username":"",
"password":"",
"pub_key_file":"",
"port":22,
"path":""
},
"import_local_path":"/home/dbuser/haha",
"import_remote_path":{
"ip":"",
"username":"",
"password":"",
"pub_key_file":"",
"port":22,
"path":""
}
},
"option":{
"column_separator":"~~~~~",
"row_separator":"@#\n#@",
"data_check_type":1,
"compression_before_translate":false,
"disable_foreign_key":true,
"check_ddl":true,
"nls_lang":"utf8",
"delete_file":true,
"ignore_lost_table":2,
"disable_trigger":true,
"check_obj_exists":true,
"ignore_sync_ddl":false,
"import_nologging":false,
"create_tab_with_default":false,
"import_threads_per_obj":10,
"import_total_task":5,
"import_allow_max_errors":0,
"import_force":false,
"import_check_row_count":false,
"truncate_before_import_db_data":true,
"export_system_rowcount_offset":10,
"export_total_task":10,
"export_allow_max_errors":0,
"export_force":false,
"export_check_row_count":false,
"export_append_on":false,
"export_max_rownum":-1
}
}

Import Process Output


Implement the import process.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

java -jar DSS.jar -i config/exp_obj.ini

After the import is complete, the following information is displayed:


DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start converting environment......................[ok]
Start syncing data................................[ok]
Data importing....................................[0/1]
Data import completed.............................[1/1]
Start recovering envrionment......................[ok]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 15:29:04]
Task end time.....................................[2019-06-13 15:29:17]
Total spent time..................................[13.402s]
Import successful data (rows).....................[10]
Import failed data (rows).........................[0]
Import failed table(tables).......................[0]
Report details path...............................[./logs/reports_2019-06-13/15h-29m-04s/]

4.2.3 Export and Import Process


Scenario
This process applies when the server where DataSync is installed can connect to
both the target database and source database or data needs to be migrated all at
a time.
Note:
● The server of the tool must be able to connect to both the source database
and target database.
● If DataSync is deployed on the server of a target database, only the GaussDB
100 installation user can run it.

cfg.ini File Example

● Set flow_type=3 for the export and import process.


● If both the password and pub_key_file parameters are configured, pub_key_file will be
used for connecting to the server. You are advised to select only one of the two.
● If pub_key_file is used and if DataSync, data files, and GaussDB 100 V300R001C00 are
deployed on three different servers, you need to manually configure the password-free
connection between the servers of GaussDB 100 V300R001C00 and the data files so that
GaussDB 100 V300R001C00 can obtain data files through SCP in password-free mode.
{
"flow_type":3,
"export_db":{
"database_type":1,
"db":{
"ip":"192.168.0.1",
"username":"sa",
"password":"U06lpFo5LlP9wvL4Kt4E4A==",
"port":4100,
"db_name":"",
"server_name":"",
"trust_store":"",
"trust_store_password":"",
"key_store":"",

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

"key_store_password":""
}
},
"import_db":{
"database_type":6,
"db":{
"ip":"192.168.0.1",
"username":"testsybase1",
"password":"U06lpFo5LlP9wvL4Kt4E4A==",
"port":1888,
"trust_store":"",
"trust_store_password":"",
"key_store":"",
"key_store_password":""
"table_space":"",
"index_table_space":""
},
"server":{
"ip":"192.168.0.1",
"username":"dbuser",
"password":"O5gs+S9n18P3uVFohVhpEA==",
"pub_key_file":"",
"port":22
}
},
"data_path":{
"export_local_path":"",
"export_remote_path":{
"ip":"",
"username":"",
"password":"",
"port":22,
"pub_key_file":"",
"path":""
},
"import_local_path":"/home/dbuser/import_path",
"import_remote_path":{
"ip":"",
"username":"",
"password":"",
"port":22,
"pub_key_file":"",
"path":""
}
},
"option":{
"column_separator":"~~~~~",
"row_separator":"@#\n#@",
"data_check_type":1,
"compression_before_translate":false,
"disable_foreign_key":true,
"check_ddl":true,
"nls_lang":"utf8",
"delete_file":true,
"ignore_lost_table":2,
"disable_trigger":true,
"check_obj_exists":true,
"ignore_sync_ddl":false,
"import_nologging":false,
"create_tab_with_default":false,
"import_threads_per_obj":10,
"import_total_task":5,
"import_allow_max_errors":0,
"import_force":false,
"import_check_row_count":false,
"truncate_before_import_db_data":true,
"export_system_rowcount_offset":10,
"export_total_task":10,
"export_allow_max_errors":0,

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

"export_force":false,
"export_check_row_count":false,
"export_append_on":false,
"export_max_rownum":-1
}
}

Output of the Export and Import Process


Implement the export and import process.
java -jar DSS.jar -i config/exp_obj.ini

After the export and import are complete, the following information is displayed:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start converting environment......................[ok]
Start syncing data................................[ok]
Data syncing......................................[0/1]
Data sync completed...............................[1/1]
Start recovering envrionment......................[ok]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 15:50:59]
Task end time.....................................[2019-06-13 15:51:48]
Total spent time..................................[48.885s]
Export successful data (rows).....................[10]
Export failed data (rows).........................[0]
Export ddl failed table count...............[0]
Export data failed table count....................[0]
Import successful data (rows).....................[10]
Import failed data (rows).........................[0]
Import failed table(tables).......................[0]
Report details path...............................[./logs/reports_2019-06-13/15h-50m-59s/]

The information Export ddl failed table count.....................[0] in bold is displayed only
when the source database is Sybase.

4.3 Reports
At the end of each DDL synchronization, export, import, and export+import
process, DataSync generates a report to provide users with information such as
execution results and execution time consumption.

4.3.1 Report for Automatic Table Creation


A report named CreateTblReport.csv is generated, describing the details about
each automatically created table. Users can view it.

Report Contents
CreateTblReport.csv records the creation result, index, index creation result,
foreign key, foreign key creation result, and rollback result of each automatically
created table.
The creation results can be:
Results of creating a table:

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

● SUCCESS: The table is created successfully.


● FAILED: The table failed to be created.
● ERROR: An error occurs during the execution of the table-creation SQL
statement.
Results of creating an index:
● Y: The index is created successfully.
● N: The index failed to be created.
● E: An error occurs during the execution of the index-creation SQL statement.
Results of creating a foreign key:
● Y: The foreign key is successfully created.
● N: The foreign key failed to be created.
Rollback results:
● SUCCESS: The rollback is successful.
● FAILED: The rollback failed.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[failed]
[Msg]:./logs/reports_2019-06-13/19h-48m-40s/

Example Contents
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
SOURCEDB,SOURCETBL,TARGETDB,TARGETTBL,TBLCREATEDRESULT,INDEXES,IDXCREATEDRESULT,FOREI
GNKEYS,FKCREATEDRESULT,ROLLBACK
testsybase3,tbl_test1000W6,TESTSYBASE3,TBL_TEST1000W6,ERROR,--,--,--,--,--

4.3.2 DDL Synchronization Report


During DDL synchronization, a report named DDLReport.csv is generated,
describing the verification of databases and tables to be exported, imported, or
exported and imported. Users can modify table definitions based on the report.

Report Contents
During DDL synchronization, the following information is verified:
● Database-level data verification
Check whether the source database and target database exist.
● Table-level data verification
Check whether the source table and target table exist.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

● Column-level data verification


– Check whether the column names in the source table are the same as
those in the target table.
– Check whether the number of columns in the source table is the same as
that in the target table.
– Check whether the column types in the source table are compatible with
those in the target table.
– Check whether the column lengths in the source table are compatible
with those in the target table.
– Check whether the NOT NULL constraints in the source table are
compatible with those in the target table.
– Check whether the column sequence in the source table is the same as
that in the target table.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[failed]
[Msg]:./logs/reports_2019-06-13/19h-45m-40s/

Example Contents
SOURCEDB,TARGETDB,SOURCETBL,TARGETTBL,SOURCEFIELD,TARGETFIELD,SOURCETYPE,TARGETTYPE,
SOURCENULLABLE,TARGETNULLABLE,SOURCEFIELDLENGTH,TARGETFIELDLENGTH,LEVEL,RESULT,TIME
DSS,DSS,PUBLIC_TABLE1,TABLE1,C_DATE,--,TIMESTAMP WITHOUT TIME ZONE,--,NOT NULL,--,4,0,error,
[reasons]1.The target table is missing this column;,2019-06-13 19:45:43

4.3.3 Data Export Report


A report named DumpReport.csv is generated, describing the details about
exporting each table.

Report Contents
DumpReport.csv records the time consumption of export, number of total rows,
number of rows that are successfully exported, number of rows that fail to be
exported, and export result of each table.
The export result can be:
● SUCCESSED: All data is exported successfully.
● PARTSUCCESSED: The amount of data that failed the export is less than or
equal to the value of export_allow_max_errors.
● FAILED: The amount of data that failed the export is greater than the value
of export_allow_max_errors.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

DataSync (1.1.1), From Huawei !


Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start syncing data................................[ok]
Data exporting....................................[0/1]
Data export completed.............................[1/1]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 15:01:36]
Task end time.....................................[2019-06-13 15:01:45]
Total spent time..................................[9.143s]
Export successful data (rows).....................[100]
Export failed data (rows).........................[0]
Export data failed table count....................[0]
Report details path...............................[./logs/reports_2019-06-13/15h-01m-36s/]

Example Contents
REPORTTYPE,DBNAME,TBLNAME,EXPORTSTART,EXPORTEND,EXPORTCOST(MS),EXPORTEDROWS,EXPO
RTFAILEDROWS,EXPORTRESULT
dump,ONETYPEUSER,ONE_TYPE_1,2019-06-13 15:01:40,2019-06-13 15:01:41,830ms,100,0,SUCCESSED

4.3.4 Data Import Report


A report named LoadReport.csv is generated, describing the details about
importing each table.

Report Contents
LoadReport.csv records the time consumption of import, number of total rows,
number of rows that are successfully imported, number of rows that fail to be
imported, and import result of each table.
The import result can be:
● SUCCESSED: All data is imported successfully.
● PARTSUCCESSED: The amount of data that failed the import is less than or
equal to the value of import_allow_max_errors.
● FAILED: The amount of data that failed the import is greater than the value
of import_allow_max_errors.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start converting environment......................[ok]
Start syncing data................................[ok]
Data importing....................................[0/0]
Data import completed.............................[1/0]
Start recovering envrionment......................[ok]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 20:33:53]
Task end time.....................................[2019-06-13 20:34:08]
Total spent time..................................[14.789s]
Import successful data (rows).....................[0]
Import failed data (rows).........................[10]
Import failed table(tables).......................[1]
Report details path........................[./logs/reports_2019-06-13/20h-33m-53s/]

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Example Contents
REPORTTYPE,SOURCEDB,TARGETDB,SOURCETBL,TARGETTBL,IMPORTSTART,IMPORTEND,IMPORTCOST(
MS),IMPORTEDROWS,IMPORTFAILEDROWS,IMPORTRESULT,ISFKENABLED
load,testsybase2,TESTSYBASE2,tbl_test1000W3,TBL_TEST1000W3,2019-06-13 20:36:27,2019-06-13
20:36:29,2329ms,10,0,SUCCESSED,No ForeignKey

4.3.5 Report for Export and Import


A report named CompleteReport.csv is generated, describing the details about
exporting and importing each table.

Report Contents
CompleteReport.csv records the time consumption, number of total rows,
number of successful rows, number of failed rows, and execution result in an
export process and an import process of each table.

The execution result can be:

● SUCCESSED: All data is exported or imported successfully.


● PARTSUCCESSED: The amount of data that failed the export or import is less
than or equal to the value of import_allow_max_errors.
● FAILED: The amount of data that failed the export or import is greater than
the value of import_allow_max_errors.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing DDL.................................[ok]
Start converting environment......................[ok]
Start syncing data................................[ok]
Data syncing......................................[0/1]
Data sync completed...............................[1/1]
Start recovering envrionment......................[ok]
Start collecting results..........................[ok]
Task start time...................................[2019-06-13 15:55:10]
Task end time.....................................[2019-06-13 15:55:59]
Total spent time..................................[48.690s]
Export successful data (rows).....................[10]
Export failed data (rows).........................[0]
Export data failed table count....................[0]
Import successful data (rows).....................[10]
Import failed data (rows).........................[0]
Import failed table(tables).......................[0]
Report details path...............................[./logs/reports_2019-06-13/15h-55m-10s/]

Example Contents
REPORTTYPE,SOURCEDB,TARGETDB,SOURCETBL,TARGETTBL,EXPORTSTART,EXPORTEND,EXPORTCOST(
MS),EXPORTTOTALROWS,EXPORTEDROWS,EXPORTFAILEDROWS,EXPORTRESULT,IMPORTSTART,IMPOR
TEND,IMPORTCOST(MS),IMPORTEDROWS,IMPORTFAILEDROWS,IMPORTRESULT,ALLCOSTS(MS),ISFKE
NABLED
dump&load,testsybase2,TESTSYBASE2,tbl_test1000W3,TBL_TEST1000W3,2019-06-13 20:39:35,2019-06-13
20:40:08,32162ms,10,10,0,SUCCESSED,2019-06-13 20:40:08,2019-06-13 20:40:10,2306ms,10,0,SUCCESSED,
34468ms,No ForeignKey

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

4.3.6 Incremental Migration Report


A report named IncrementReport.csv is generated, describing the details about
incremental migration of each table.

Report Contents
IncrementReport.csv records the time consumption, number of table rows,
number of successful rows, number of failed rows, migration result, and path of
files about failed SQL executions for each table in an incremental migration.

The migration result can be:

● SUCCESSED: The incremental migration is successful.


● FAILED: The incremental migration fails. You can query the SQL file for the
cause.
● --: There is no incremental table, or the database or table does not exist.

Report Path
DataSync displays the report path after its execution is complete, as shown in the
following information in bold:
DataSync (1.1.1), From Huawei !
Copyright © Huawei Technologies Co , Ltd 2019 All Rights Reserved.
Start checking config.............................[ok]
Start syncing increments..........................[ok]
commited/failed/remaining.........................[0/0/0]
spent :0.000s
Task start time...................................[2019-06-22 20:02:35]
Task end time.....................................[2019-06-22 20:02:37]
Total spent time..................................[2.231s]
Logs details path.................................[./logs/reports_2019-06-22/20h-02m-35s/]

Example Contents
REPORTTYPE,SOURCEDB,TARGETDB,SOURCETBL,TARGETTBL,TASKSTART,TASKEND,TASKCOST(MS),TOTA
LROWS,IMPORTEDROWS,FAILEDROWS,RESULT,FAILEDSQLSFILE
increment,DSS,DSS,TESTCLOB,TESTCLOB,--,--,--,-1,-1,-1,--,table does not exists or the table don't have
increment table in source DB

4.4 Logs
Log files are generated during the execution of DataSync. You can refer to these
logs for routine management and maintenance.

Log Types
The following logs are generated during the execution of DataSync:

● dss_info_log.log: Records important steps during DataSync execution. It is


used for maintenance personnel to locate and analyze problems.
● dss_error_log.log: Records exceptions and errors during DataSync execution.
It is used for maintenance personnel to locate and analyze problems.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Log Policies
dss_info_log.log and dss_error_log.log are generated for each execution of
DataSync. The two logs are stored in a folder named after the running time of
DataSync. In addition, all log folders in a day are stored in a folder named after
the current date, as shown in the following information in bold:
syncusr@plaat:/home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync> cd logs/
syncusr@plaat:/home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync/logs> ll
drwx------ 4 syncusr syncgrp 4096 Jun 11 17:44 reports_2019-06-11
drwx------ 16 syncusr syncgrp 4096 Jun 13 20:39 reports_2019-06-13
syncusr@plaat:/home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync/logs> cd
reports_2019-06-13/
syncusr@plaat:/home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync/logs/reports_2019-06-13>
ll
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:25 15h-25m-59s
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:27 15h-27m-13s
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:29 15h-29m-04s
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:32 15h-32m-39s
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:50 15h-50m-27s
drwx------ 2 syncusr syncgrp 4096 Jun 13 15:51 15h-50m-59s
drwx------ 2 syncusr syncgrp 4096 Jun 13 17:39 15h-55m-10s
drwx------ 2 syncusr syncgrp 4096 Jun 13 17:40 17h-40m-18s
drwx------ 2 syncusr syncgrp 4096 Jun 13 19:24 19h-24m-13s
drwx------ 2 syncusr syncgrp 4096 Jun 13 20:30 20h-30m-06s
drwx------ 2 syncusr syncgrp 4096 Jun 13 20:34 20h-33m-53s
drwx------ 2 syncusr syncgrp 4096 Jun 13 20:35 20h-35m-11s
drwx------ 2 syncusr syncgrp 4096 Jun 13 20:36 20h-36m-18s
drwx------ 2 syncusr syncgrp 4096 Jun 13 20:48 20h-39m-27s

By default, the size of each log file is 100 MB. A maximum of 500 log files can be
generated. When the number of log files reaches the maximum, the earliest log
files will be overwritten.

The log level can be changed as needed by changing the value of


appender.info.filter.threshold.level in the log4j2.properties file.

The default log configuration basically meets the requirements of problem


location and analysis in actual services. If the configuration needs to be modified
in special scenarios, you are advised to modify only the following parameters.
Otherwise, logs may fail to be recorded or other exceptions may occur.

Table 4-3

Parameter Description Configuration Def


aul
t
Val
ue

appender.info.policies.s Maximum size of the The unit can be KB, 100


ize.size info file MB, or GB. MB

appender.info.strategy. Maximum number of The value must be a 500


max info files that can be number.
generated

appender.error.policies. Maximum size of the The unit can be KB, 100


size.size error file MB, or GB. MB

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
DataSync User Guide (Standalone) 4 Working with DataSync

Parameter Description Configuration Def


aul
t
Val
ue

appender.error.strategy. Maximum number of The value must be a 500


max error files that can be number.
generated

appender.info.filter.thr Whether to print other The value can be info


eshold.level types of logs in the debug, info, warn,
info file error, or fatal.

Log Path
The log path can be specified by the -l parameter in the command line. If the log
path is not specified, logs will be generated in the Running package path./logs
directory by default.

4.5 Data and File Clearing

4.5.1 Clearing the Target Database


To ensure that data in the target database is complete and accurate, you are
advised to clean up data in the target table before importing data using DataSync.

To clear the target database, set truncate_before_import_db_data in the cgf.ini


file to true. After the execution of DataSync is complete, you can run SQL
statements to query the source table and target table. If the number of rows in
the target database is the same as that in the source database, the target
database was successfully cleared.

4.5.2 Deleting Local Files


When DataSync is used to migrate data, the generated data files may cause
insufficient server space. Therefore, you are advised to delete local files.

To delete local files, set delete_file in the cgf.ini file to true. Note that no matter
whether the value of delete_file in the cgf.ini file is set to true, local files will be
deleted after DataSync transfers the exported data from the local directory to the
configured remote directory if any.

In an export+import process, the remote path for export is invalid. In this case,
DataSync generates the exported data files in the configured directory, and then
transfers the files to the home directory of the user who installed the GaussDB
100 V300R001 database. If delete_file is set to true, the data files in the home
directory of the database installation user will be deleted after the import is
successful. Otherwise, the data files will not be deleted.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
DataSync User Guide (Standalone) 5 Data Migration

5 Data Migration

DataSync supports online and offline migration.


An export process or an import process supports only offline migration. An export
+import process supports online and offline migration. If DataSync and GaussDB
100 are deployed on different servers during offline migration, run commands by
using a non-database installation user. If DataSync and GaussDB 100 are deployed
on the same server, run commands by using the database installation user.

Offline Migration
Step 1 Log in as user root to the server where DataSync resides.
Step 2 If DataSync and GaussDB 100 are deployed on different servers during offline
migration, run commands by using a non-database installation user.
To create a user, perform the following steps:
Create the user and user group for running DataSync on the server.
groupadd syncgrp
useradd -g syncgrp -d /home/syncusr -m -s /bin/bash syncusr

Set the password of user syncusr.


passwd syncusr

Step 3 Switch to the user who executes data migration.


● If DataSync and GaussDB 100 are deployed on different servers, run the
following command by using the user created in Step 2.
su - syncusr

● If DataSync and GaussDB 100 are deployed on the same server, run the
following command by using the database installation user (for example, the
GaussDB 100 database installation user is omm).
su - omm

Step 4 Upload the DataSync package GAUSSDB100-V300R001C00-DATASYNC.tar.gz to


the /home/syncusr directory.
Step 5 Decompress the GAUSSDB100-V300R001C00-DATASYNC.tar.gz package.
cd /home/syncusr
tar -zxvf GAUSSDB100-V300R001C00-DATASYNC.tar.gz

[syncusr@plaat syncusr]\>ll

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
DataSync User Guide (Standalone) 5 Data Migration

total 11684
drwx------ 2 syncusr syncgrp 4096 May 28 23:26 GAUSSDB100-V300R001C00-DATASYNC
-rw-r--r-- 1 root root 18350870 May 28 23:26 GAUSSDB100-V300R001C00-DATASYNC.tar.gz

Step 6 Decompress the DataSync.tar.gz package.


cd GAUSSDB100-V300R001C00-DATASYNC/
tar -zxvf DataSync.tar.gz

[syncusr@plaat syncusr]\>ll
total 11680
drwx------ 5 syncusr syncgrp 4096 May 28 23:26 DataSync
-rw------- 1 syncusr syncgrp 11934916 May 28 23:26 DataSync.tar.gz
-rw------- 1 syncusr syncgrp 82 May 28 23:26 DataSync.tar.gz.sha256

Step 7 Configure files such as cfg.ini, exp_obj.ini, and exclusive_obj.ini.


1. Go to the configuration file directory.
cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync/config

2. Configure the files.


For details about how to configure files such as cfg.ini, exp_obj.ini, and
exclusive_obj.ini, see Configuration Files.
For details about the cfg.ini configuration for each process (such as import,
export, and export+import), see Processes. For details about the parameters
in cfg.ini, see cfg.ini.

Step 8 (Optional) Synchronize table structures.

Before data migration, you can synchronize table structures and modify DDL
statements for the tables based on the synchronization report. For details about
the DDL synchronization report, see DDL Synchronization Report.

1. In cfg.ini, set flow_type to 4.


2. Go to the directory containing DSS.jar.
cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync

3. Execute DataSync.
In this case, only table structures are synchronized, and data is not imported
or exported.
java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-d
ignore_ddl.ini_path] [-o exclusiveDataOnly_obj.ini] [-l /data/gaussdba/log_path] [-imp_b
importerrorlog_path]

For details about the syntax supported by DataSync, see DataSync Syntax.

Step 9 Go to the directory containing DSS.jar.


cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync

Step 10 Perform offline migration.


java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-d ignore_ddl.ini_path] [-
o exclusiveDataOnly_obj.ini] [-l /data/gaussdba/log_path] [-imp_b importerrorlog_path]

The operation type (export, import, or export+import) is determined by the


flow_type parameter in cfg.ini. If flow_type=1 is set, export will be performed; if
flow_type=2, import will be performed; If flow_type=3 is set, export+import will
be performed.

----End

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100
DataSync User Guide (Standalone) 5 Data Migration

Online Migration
Step 1 Log in as user root to the server where DataSync resides.

Step 2 Create the user and user group for running DataSync on the server.
groupadd syncgrp
useradd -g syncgrp -d /home/syncusr -m -s /bin/bash syncusr

Set the password of user syncusr.


passwd syncusr

Step 3 Switch to user syncusr.


su - syncusr

Step 4 Upload the DataSync package DataSync.tar.gz to the /home/syncusr directory.

Step 5 Decompress the GAUSSDB100-V300R001C00-DATASYNC.tar.gz package.


cd /home/syncusr
tar -zxvf GAUSSDB100-V300R001C00-DATASYNC.tar.gz

[syncusr@plaat syncusr]\>ll
total 11684
drwx------ 2 syncusr syncgrp 4096 May 28 23:26 GAUSSDB100-V300R001C00-DATASYNC
-rw-r--r-- 1 root root 18350870 May 28 23:26 GAUSSDB100-V300R001C00-DATASYNC.tar.gz

Step 6 Decompress the DataSync.tar.gz package.


cd GAUSSDB100-V300R001C00-DATASYNC/
tar -zxvf DataSync.tar.gz

[syncusr@plaat syncusr]\>ll
total 11680
drwx------ 5 syncusr syncgrp 4096 May 28 23:26 DataSync
-rw------- 1 syncusr syncgrp 11934916 May 28 23:26 DataSync.tar.gz
-rw------- 1 syncusr syncgrp 82 May 28 23:26 DataSync.tar.gz.sha256

Step 7 Configure cfg.ini, exp_obj.ini, and exclusive_obj.ini.


1. Go to the directory containing cfg.ini, exp_obj.ini, and exclusive_obj.ini.
cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync/config

2. Configure cfg.ini, exp_obj.ini, and exclusive_obj.ini as needed.


For details about how to configure cfg.ini, exp_obj.ini, and exclusive_obj.ini,
see Configuration Files.
For details about the cfg.ini configuration for each process (import, export,
and export+import), see Processes. For details about the parameters in
cfg.ini, see cfg.ini.

Step 8 (Optional) Synchronize table structures.

Before data migration, you can synchronize table structures and modify DDL
statements for the tables based on the synchronization report. For details about
the DDL synchronization report, see DDL Synchronization Report.

1. In cfg.ini, set flow_type to 4.


2. Go to the directory containing DSS.jar.
cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync

3. Execute DataSync.
In this case, only table structures are synchronized, and data is not imported
or exported.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100
DataSync User Guide (Standalone) 5 Data Migration

java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-d
ignore_ddl.ini_path] [-o exclusiveDataOnly_obj.ini] [-l /data/gaussdba/log_path] [-imp_b
importerrorlog_path]

Step 9 Go to the directory containing DSS.jar.


cd /home/syncusr/GAUSSDB100-V300R001C00-DATASYNC/DataSync

Step 10 Create a trigger.


java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-l /data/gaussdba/
log_path] [-imp_b importerrorlog_path] -t trigger

For details about the syntax supported by DataSync, see DataSync Syntax.
Step 11 Perform full migration.
java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-o
exclusiveDataOnly_obj.ini] [-l /data/gaussdba/log_path] [-imp_b importerrorlog_path]

Step 12 When data is not used by users, perform incremental migration.


java -jar DSS.jar [-p cfg.ini_path] [-i exp_obj.ini_path] [-e exclusive_obj.ini_path] [-l /data/gaussdba/
log_path] [-imp_b importerrorlog_path] -t mission

----End

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100
DataSync User Guide (Standalone) 6 Security

6 Security

The key measures for DataSync security management are as follows:


● DataSync encrypts user passwords.
● According to service security requirements, the security level of DataSync does
not need to be defined in each security zone when an intranet is used.
● Ensure that the SSL certificate is valid for the application domain and is
signed by the certificate authority or a trusted third party.
● The Java version must be JDK1.8 or later.

6.1 Account Security


For details about all accounts used for installing, operating, and maintaining
DataSync, see Table 6-1.

Table 6-1 DataSync accounts


Account Type User Password Remarks Anti-Brute-
Force-
Cracking
Mechanism

Source Database user Encrypted For details -


database user name about
permissions
of the user,
see Table 2-2
in
Constraints
and
Limitations.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100
DataSync User Guide (Standalone) 6 Security

Account Type User Password Remarks Anti-Brute-


Force-
Cracking
Mechanism

Target Database user Encrypted For details -


database user name about
permissions
of the user,
see Table 2-2
in
Constraints
and
Limitations.

Target server Name of the Encrypted - -


user user who
installed the
Gauss100
database

Remote Server user Encrypted - -


server user for name
export

Remote Server user Encrypted - -


server user for name
import

6.2 Security Statement


This section describes security statements of DataSync, including security
operations, passwords, and encryption algorithms.

Security Operations
According to service security requirements, the security level of DataSync does not
need to be defined in each security zone when an intranet is used.

Passwords
DataSync encrypts user passwords.

Encryption Algorithms
DataSync encrypts sensitive data using standard encryption algorithms, meeting
security requirements.

6.3 Integrity Verification


The installation package and integrity check file are provided together to protect
the package from being maliciously tampered or damaged during transmission.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100
DataSync User Guide (Standalone) 6 Security

After obtaining the installation package, verify the package integrity. The package
can be deployed only after it passes the verification.
Run the following statement in the directory containing the DataSync package. If
OK is returned, the package passes the verification. Otherwise, the package fails
the verification. In the latter case, contact Huawei technical support.
sha256sum -c DataSync.tar.gz.sha256

6.4 Data Transmission Security


For security purposes, DataSync uses SSH File Transfer Protocol (SFTP) and Secure
Copy (SCP) to transfer data files. SCP is used only when data is imported and data
files are stored in a remote directory. In other cases, SFTP is used.

6.5 Database SSL Connection


DataSync supports SSL connection. This section uses GaussDB 100 V300R001 as a
target database to describe how to configure related parameters when SSL
connection is used. For details about how to configure parameters for other
databases, see the corresponding guide.
Assuming that GaussDB 100 V300R001 needs to be connected in SSL mode and
the database installation user is omm, add the following environment variables
for omm:
export ZSQL_SSL_CERT="/home/omm/app/client.crt"
export ZSQL_SSL_KEY="/home/omm/app/client.key"
export ZSQL_SSL_CA="/home/omm/app/cacert.pem"
export ZSQL_SSL_MODE="preferred"

The parameters are as follows:


● ZSQL_SSL_CERT
Specifies the client certificate file, including the public key of the client. The
certificate proves the legal identity of the client and the public key is sent to
the peer end for data encryption. The value must be an absolute path, for
example, export ZSQL_SSL_CERT= '/home/xxx/client.crt'. xxx indicates the
database installation user.
● ZSQL_SSL_CA
Specifies the root certificate file for issuing client certificates. The root
certificate is used to verify the server certificate. The value must be an
absolute path, for example, export ZSQL_SSL_CA='/home/xxx/cacert.pem'.
xxx indicates the database installation user.
● ZSQL_SSL_MODE
Specifies whether to negotiate with the server about SSL connection and also
specifies the priority of the SSL connection. The value can be:
– disabled: Try only non-SSL connection.
– preferred: If the server supports SSL connection, the SSL connection is
preferred.
– required: Try only SSL connection. If there is a CA file, the verification is
performed in the same way it is performed when ZSQL_SSL_KEY is set to
verify_ca.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100
DataSync User Guide (Standalone) 6 Security

– verify_ca: Try only SSL connection and check whether the server
certificate is issued by a trusted CA.
– verify_full: Try only SSL connection and check whether the server
certificate is issued by a trusted CA and whether the host name of the
server is the same as that in the certificate.
● ZSQL_SSL_KEY
Specifies the private key file of the client, used to decrypt data encrypted
using the public key. The value must be an absolute path, for example, export
ZSQL_SSL_KEY='/home/xxx/client.key'. xxx indicates the database
installation user.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100
DataSync User Guide (Standalone) 7 Glossary

7 Glossary

This chapter describes the glossary, acronyms, and abbreviations used in this
document.

Term Description

DataSync Data synchronous migration

DDL Data Definition Language

DML Data Manipulation Language

full synchronization A data synchronization mechanism specified in the


GaussDB 100 HA solution. It is used to synchronize all
data from the primary server to a standby server.

log file A file to which a computer system writes a record of


its activities.

database A database stores a collection of related data that


can be accessed, managed, and updated by users.
Data in a view in a database can be classified into the
following types: numeral, full text, digit, and image.

database instance A database instance consists of a GaussDB 100


process and database files controlled by it. GaussDB
100 installs multiple database instances on one
physical node. The CMs, CNs, and DNs installed on
cluster nodes are all database instances. A database
instance is also called a logical node.

data partitioning A division of a logical database or its constituent


elements into multiple parts (partitions) whose data
does not overlap based on ranges or lists. The target
storage location is mapped based on the range of the
values in the column that is specified in the tuple.

index An ordered data structure in a DBMS. An index


accelerates data query and update in database tables.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100
DataSync User Guide (Standalone) 7 Glossary

Term Description

trigger A trigger is a special type of stored procedure that is


fired by a specified event. It is generally used for
auditing and backing up data.

table A set of columns and rows. Each column is referred to


as a field. The value in each field represents a data
type. For example, if a table contains three fields of
person names, cities, and states, it has three columns:
Name, City, and State. In each row in the table, the
Name column contains a name, the City column
contains a city, and the State column contains a
state.

concurrency control A DBMS service that ensures data integrity when


multiple transactions are concurrently executed in a
multi-user environment. In a multi-threaded GaussDB
100 environment, concurrency control ensures that
database operations are safe and all database
transactions remain consistent at any given time.

SSL Secure Sockets Layer (SSL) is a network security


protocol first used by Netscape. It is based on the
TCP/IP protocol and uses public key technology. SSL
supports a wide range of networks and provides three
basic security services, all of which use the public key
technology. SSL ensures the security of service
communication through a network by establishing a
secure connection between a client and a server and
then sending data through this connection.

Issue 01 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100
V300R001C00

Error Code Reference (Standalone)

Issue 04
Date 2019-12-28

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties, guarantees
or representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Error Code Reference (Standalone) Contents

Contents

1 About This Document.............................................................................................................1


2 Error Code Reference.............................................................................................................. 3
2.1 Number Descriptions for Error Codes.............................................................................................................................. 3
2.2 zsql Error Codes....................................................................................................................................................................... 3
2.3 GS-00001 -- GS-00099.......................................................................................................................................................... 4
2.3.1 GS-00001 -- GS-00010....................................................................................................................................................... 4
2.3.2 GS-00011 -- GS-00020....................................................................................................................................................... 5
2.3.3 GS-00021 -- GS-00030....................................................................................................................................................... 7
2.3.4 GS-00031 -- GS-00040....................................................................................................................................................... 8
2.3.5 GS-00051 -- GS-00060....................................................................................................................................................... 9
2.4 GS-00100 -- GS-00199.......................................................................................................................................................... 9
2.4.1 GS-00100 -- GS-00110....................................................................................................................................................... 9
2.4.2 GS-00111 -- GS-00120.................................................................................................................................................... 11
2.4.3 GS-00121 -- GS-00130.................................................................................................................................................... 12
2.4.4 GS-00131 -- GS-00140.................................................................................................................................................... 12
2.5 GS-00200 -- GS-00299........................................................................................................................................................ 13
2.5.1 GS-00200 – GS-00210......................................................................................................................................................13
2.5.2 GS-00211 -- GS-00220.................................................................................................................................................... 14
2.5.3 GS-00221 -- GS-00230.................................................................................................................................................... 15
2.5.4 GS-00231 -- GS-00240.................................................................................................................................................... 15
2.5.5 GS-00241 -- GS-00250.................................................................................................................................................... 15
2.5.6 GS-00251 -- GS-00260.................................................................................................................................................... 16
2.5.7 GS-00291 -- GS-00299.................................................................................................................................................... 18
2.6 GS-00300 -- GS-00399........................................................................................................................................................ 18
2.6.1 GS-00300 -- GS-00310.................................................................................................................................................... 18
2.6.2 GS-00311 -- GS-00320.................................................................................................................................................... 19
2.6.3 GS-00321 -- GS-00330.................................................................................................................................................... 21
2.6.4 GS-00331 -- GS-00340.................................................................................................................................................... 22
2.6.5 GS-00341 -- GS-00350.................................................................................................................................................... 24
2.7 GS-00400 -- GS-00499........................................................................................................................................................ 27
2.7.1 GS-00400 -- GS-00410.................................................................................................................................................... 27
2.8 GS-00500 -- GS-00599........................................................................................................................................................ 28
2.8.1 GS-00500 -- GS-00510.................................................................................................................................................... 28

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Error Code Reference (Standalone) Contents

2.8.2 GS-00511 -- GS-00520.................................................................................................................................................... 29


2.8.3 GS-00521 -- GS-00530.................................................................................................................................................... 30
2.9 GS-00600 -- GS-00699........................................................................................................................................................ 31
2.9.1 GS-00600 -- GS-00610.................................................................................................................................................... 31
2.9.2 GS-00611 -- GS-00620.................................................................................................................................................... 32
2.9.3 GS-00621 -- GS-00630.................................................................................................................................................... 32
2.9.4 GS-00631 -- GS-00640.................................................................................................................................................... 33
2.9.5 GS-00641 -- GS-00650.................................................................................................................................................... 34
2.9.6 GS-00651 -- GS-00660.................................................................................................................................................... 35
2.9.7 GS-00661 -- GS-00670.................................................................................................................................................... 36
2.9.8 GS-00671 -- GS-00680.................................................................................................................................................... 37
2.9.9 GS-00681 -- GS-00690.................................................................................................................................................... 39
2.9.10 GS-00691 -- GS00699.................................................................................................................................................... 40
2.10 GS-00700 -- GS-00799..................................................................................................................................................... 41
2.10.1 GS-00700 -- GS-00710.................................................................................................................................................. 41
2.10.2 GS-00711 -- GS-00720.................................................................................................................................................. 42
2.10.3 GS-00721 -- GS-00730.................................................................................................................................................. 43
2.10.4 GS-00731 -- GS-00740.................................................................................................................................................. 44
2.10.5 GS-00741 -- GS-00750.................................................................................................................................................. 45
2.10.6 GS-00751 -- GS-00760.................................................................................................................................................. 46
2.10.7 GS-00761 -- GS-00770.................................................................................................................................................. 47
2.10.8 GS-00771 -- GS-00780.................................................................................................................................................. 48
2.10.9 GS-00781 -- GS-00790.................................................................................................................................................. 50
2.10.10 GS-00791 -- GS-00799................................................................................................................................................ 51
2.11 GS-00800 -- GS-00899..................................................................................................................................................... 52
2.11.1 GS-00800 -- GS-00810.................................................................................................................................................. 52
2.11.2 GS-00811 -- GS-00820.................................................................................................................................................. 53
2.11.3 GS-00821 -- GS-00830.................................................................................................................................................. 54
2.11.4 GS-00831 -- GS-00840.................................................................................................................................................. 55
2.11.5 GS-00841 -- GS-00850.................................................................................................................................................. 56
2.11.6 GS-00851 -- GS-00860.................................................................................................................................................. 58
2.11.7 GS-00861 -- GS-00870.................................................................................................................................................. 59
2.11.8 GS-00871 -- GS-00880.................................................................................................................................................. 60
2.11.9 GS-00881 -- GS-00890.................................................................................................................................................. 61
2.12 GS-00900 -- GS-00999..................................................................................................................................................... 62
2.12.1 GS-00900 -- GS-00910.................................................................................................................................................. 62
2.12.2 GS-00911 -- GS-00920.................................................................................................................................................. 63
2.12.3 GS-00921 -- GS-00930.................................................................................................................................................. 63
2.12.4 GS-00931 -- GS-00940.................................................................................................................................................. 64
2.12.5 GS-00941 -- GS-00950.................................................................................................................................................. 66
2.12.6 GS-00951 -- GS-00960.................................................................................................................................................. 67
2.12.7 GS-00961 -- GS-00970.................................................................................................................................................. 68

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Error Code Reference (Standalone) Contents

2.12.8 GS-00971 -- GS-00980.................................................................................................................................................. 69


2.13 GS-01000 -- GS-01099..................................................................................................................................................... 70
2.13.1 GS-01000 -- GS-01010.................................................................................................................................................. 70
2.14 GS-01100 -- GS-01199..................................................................................................................................................... 71
2.14.1 GS-01100 -- GS-01110.................................................................................................................................................. 71
2.14.2 GS-01111 -- GS-01120.................................................................................................................................................. 72
2.15 GS-01200 -- GS-01299..................................................................................................................................................... 73
2.15.1 GS-01200 -- GS-01210.................................................................................................................................................. 73
2.15.2 GS-01211 -- GS-01220.................................................................................................................................................. 73
2.15.3 GS-01221 -- GS-01230.................................................................................................................................................. 74
2.16 GS-01300 -- GS-01399..................................................................................................................................................... 75
2.16.1 GS-01300 -- GS-01310.................................................................................................................................................. 75
2.16.2 GS-01311 -- GS-01320.................................................................................................................................................. 76
2.16.3 GS-01321 -- GS-01330.................................................................................................................................................. 77
2.16.4 GS-01331 -- GS-01340.................................................................................................................................................. 78
2.16.5 GS-01341 -- GS-01350.................................................................................................................................................. 79
2.16.6 GS-01351 -- GS-01360.................................................................................................................................................. 81
2.16.7 GS-01361 -- GS-01370.................................................................................................................................................. 81
2.17 GS-01400 -- GS-01499..................................................................................................................................................... 81
2.17.1 GS-01400 -- GS-01410.................................................................................................................................................. 81

3 Interface Mapping (GaussDB 100 Native Interface Names vs. Mainstream


Database Interface Names)................................................................................................... 83
3.1 Data Dictionary Tables........................................................................................................................................................ 83
3.2 DBA Views............................................................................................................................................................................... 85
3.3 User Views............................................................................................................................................................................... 88
3.4 Dynamic Performance Views............................................................................................................................................ 90
3.5 Configuration Parameters.................................................................................................................................................. 93

4 Glossary................................................................................................................................... 94

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
Error Code Reference (Standalone) 1 About This Document

1 About This Document

Purpose
This document describes error information that may be displayed when you use
GaussDB 100.

Each piece of error information contains a GaussDB 100-specific error code


number (format: GS-XXXXX), an SQL-based error code number (format:
SQLSTATE: XXXXX), error descriptions, possible causes, and recommended
handling methods.

If errors are reported in the compilation phase of stored procedures, the specified
error codes will be summarized and output in PLC-XXXXX format (specific to
stored procedures), which is equivalent to GS-XXXXX.

GaussDB 100 is compatible with the user habits of mainstream databases. You can
use native GaussDB 100 interface names or their corresponding names in the
mainstream databases. For details, see Interface Mapping (GaussDB 100 Native
Interface Names vs. Mainstream Database Interface Names). The interfaces
mentioned in this document use their native GaussDB 100 names.

Intended Audience
This document is designed for all GaussDB 100 users.

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not


avoided, will result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in minor or moderate injury.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Error Code Reference (Standalone) 1 About This Document

Symbol Description

Indicates a potentially hazardous situation which, if not


avoided, could result in equipment damage, data loss,
performance deterioration, or unanticipated results.
NOTICE is used to address practices not related to personal
injury.

Calls attention to important information, best practices, and


tips.
NOTE is used to address information not related to personal
injury, equipment damage, and environment deterioration.

Change History
Version Change Description Date

04 This issue is the fourth official release. 2019-07-18

03 Added: 2019-06-26
● GS-00877 in GS-00871 -- GS-00880
● GS-01258 in GS-00251 -- GS-00260

02 Added: 2019-04-05
● zsql Error Codes
● GS-01345 in GS-01341 -- GS-01350
Modified:
● GS-00927 in GS-00921 -- GS-00930

01 This issue is the first official release. 2018-10-30

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2 Error Code Reference

2.1 Number Descriptions for Error Codes


● OS error: 0–99, an error in OS interface invocation
● Common error: 100–199, an error in common service invocation
● Configuration error: 200–299, an error in configuration management
● Network error: 300–399, an error in networks
● Instance error: 400–499, an error in database instances
● Client error: 500–599, an error in client-side user input or invocation
● SQL engine error: 600–699 and 1300–1399, an error in SQL engine invocation
● Storage engine error: 700–899, an error in storage engine invocation
● Stored procedure error: 900–999, an error in stored procedure invocation
● Permission error: 1000–1099, an error in permission granting
● Partitioned table error: 1100–1199, an error in partitioned table invocation
● Distributed invoking error: 1200–1299, an error in nodes
● Scheduled job error: 1400-1499, an error in scheduled jobs

2.2 zsql Error Codes


Errors raised by the same zsql module use the same error code, and the error
messages vary according to specific errors. The error code format is ZS-Error code:
Error message. Table 2-1 describes relevant error codes.

Table 2-1 zsql error codes

Error Code Function

ZS-00001 An error in the zsql client during gsql processing

ZS-00002 An error in the dump module of the zsql client

ZS-00003 An error in the load module of the zsql client

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Error Code Function

ZS-00004 An error in the export module of the zsql client

ZS-00005 An error in the import module of the zsql client

ZS-00006 An error in the main module of the zsql client

2.3 GS-00001 -- GS-00099

2.3.1 GS-00001 -- GS-00010


GS-00001: Failed to allocate %u bytes for %s
Description: Failed to allocate memory (malloc error).
Solution:
● Ensure that the host has free memory.
● If the host has free memory but the fault persists, contact Huawei technical
support.

GS-00002: Failed to open the file %s, the error code was %d
Description: Failed to open the file.
Solution:
● Ensure that the file exists, the user has read permission, and the disk is not
damaged.
● If the fault persists after the above measure is taken, contact Huawei
technical support.

GS-00003: Failed to create the file %s, the error code was %d
Description: Failed to create the file.
Solution:
● Ensure that the disk has free space.
● If the disk has free space but the fault persists, contact Huawei technical
support.

GS-00004: Failed to read data from the file, the error code was %d
Description: Failed to read the file.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00005: Failed to write the file, the error code was %d


Description: Failed to write the file.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

GS-00006: The file name (%s) exceeded the maximum length (%u)
Description: The file name was invalid.
Solution: Proceed according to the error information.

GS-00008: Failed to create the path %s


Description: Failed to create the directory.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

GS-00009: Failed to rename the file %s to %s


Description: Failed to rename the file.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

GS-00010: Failed to remove file %s, error code %d


Description: Failed to delete the file.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

2.3.2 GS-00011 -- GS-00020


GS-00011: failed to create a new thread
Description: Failed to create the thread.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00012: Failed to init thread attribute


Description: Failed to initialize the attributes of a thread.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00013: Failed to set thread stacksize


Description: Failed to set the thread stack size.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00014: Failed to create IPC semaphore


Description: Failed to create the semaphore.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00015: Failed to attach IPC semaphore


Description: Failed to attach to the semaphore.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00016: failed to create IPC shared memory


Description: Failed to create the shared memory.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00017: Failed to initialize event notification for agent, error code %d.
Description: Failed to create the event.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00018: Failed to load library '%s': error code %d

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: Failed to load the dynamic library.


Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00019: Failed to load symbol '%s': error reason %s


Description: Failed to load the symbol table.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00020: Failed to get program name: error code %d


Description: The system failed to read the process name, process ID, and OS
username for initialization due to reasons such as the names or IDs are too long
(exceeding 255 bytes).
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

2.3.3 GS-00021 -- GS-00030


GS-00021: Failed to generate guid: error code %d
Description: There was an error when the system invoked the Windows SDK
function, CoCreateGuid.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00022: Failed to generate sha1 hash for '%s'


Description: Failed to generate the SHA1 hash from any string.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00023: File %s already exist, failed to rename datafile %s to %s


Description: The data file was renamed to an existing name.
Solution: Ensure that the new file name does not conflict with any existing one.

GS-00024: Directory '%s' not exist or not reachable or invalid


Description: The path does not exist, is not reachable, or is invalid.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Ensure that the path exists and is valid and ensure that the user has the
access permission.

GS-00027: Stack depth limit exceeded


Description: The stack depth exceeded the maximum value supported by the
memory.
Solution: Ensure that no infinite loop occurs during SQL invoking. If there is no
infinite loop but the fault persists, contact Huawei technical support.

GS-00028: Write size %d, expected size %d, mostly because file size is larger than
disk, please delete the incomplete file
Description: Failed to completely write the file.
Solution:
● Ensure that the system disk has sufficient space.
● If the system disk has sufficient space but the fault persists, contact Huawei
technical support.

GS-00029: Failed to reset %s


Description: Failed to initialize the memory.
Solution: Ensure that the size of the object to be initialized is the same as that
specified in the memset function.

GS-00030: Read size %d, expected size %d, please check incomplete file
Description: Failed to completely read the file.
Solution: Ensure that the file is correct and intact.

2.3.4 GS-00031 -- GS-00040


GS-00032: Failed to seek file, offset:%llu, origin:%d, error code %d
Description: Failed to seek the file.
Solution:
● Ensure that the host disk is normal.
● If the host disk is normal but the fault persists, contact Huawei technical
support.

GS-00033: Failed to truncate file, offset:%llu, error code %d


Description: Failed to truncate the file.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00035: Failed to lock file, error code %d

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: Failed to lock the file to be read.


Solution:
● Check whether configuration files, control files, and other files have been
locked together.
● If they have not been locked but the fault persists, contact Huawei technical
support.

2.3.5 GS-00051 -- GS-00060


GS-00051: Failed to fsync the file, the error code was %d
Description: Failed to synchronize file data or metadata to disk.
Solution: Proceed according to the error information.

GS-00052: Failed to fdatasync the file, the error code was %d


Description: Failed to synchronize file data to disk.
Solution: Proceed according to the error information.

2.4 GS-00100 -- GS-00199

2.4.1 GS-00100 -- GS-00110


GS-00101: Capability: %s not supported
Description: The feature was not supported.
Solution: Proceed according to the error information.

GS-00102: %s out of index, limits is %uX


Description: Internal error. The subscript was invalid.
Solution: Contact Huawei technical support.

GS-00103: Can't allocate page from %s


Description: Failed to allocate memory from the global area.
Solution: Contact Huawei technical support.

GS-00104: Session stack overflow


Description: Running the INSERT, SELECT, or UPDATE statement will use the
thread data stack to buffer messages. The size of the thread data stack is
controlled by the _AGENT_STACK_SIZE parameter. When the size of column
values following VALUE in the statement exceeds the value of
_AGENT_STACK_SIZE, this error is reported.
Solution: Use the following formula to estimate the amount of data that can be
processed at a time:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

_AGENT_STACK_SIZE = Size of each column value x Number of parameters + Size of data in two rows to
be pushed + Size of data for type conversion

The maximum data size of a single row is 64,000 bytes, and type conversion requires 1600
bytes.
For details about the _AGENT_STACK_SIZE parameter, see "Parameters > Advanced
Optimization > Thread Processing" in GaussDB 100 V300R001C00 Database Reference
(Standalone).
● Handle the data in batches according to the estimation result.
● Run the following statement to change the value of _AGENT_STACK_SIZE,
and restart the database for the change to take effect:
ALTER SYSTEM SET _AGENT_STACK_SIZE = value;

GS-00105: Invalid format of %s


Description: The text format string was incorrect.
Solution: Select the correct text format string according to the error information.

GS-00106: The size of row is too large, max_row_size=%u


Description: The size of a row was too large.
Solution: Contact Huawei technical support.

GS-00107: Text buffer is too small, expected(%d+), actual %d


Description: There was a buffer overflow.
Solution: Contact Huawei technical support.

GS-00108: Lob size limits to %s


Description: The LOB size was too large.
Solution: Contact Huawei technical support.

GS-00109: Column count exceeded the limit %d


Description: The number of columns exceeded the allowed maximum.
Solution: The number of columns is specified by the MAX_COLUMN_COUNT
parameter. The default value of this parameter is 1024. When the number of
columns exceeds 1023, this error is reported.
You can adjust the value of MAX_COLUMN_COUNT as needed or adjust the
number of columns.
For details about the MAX_COLUMN_COUNT parameter, see "Parameters >
Databases > Maximum Number of Columns Allowed" in GaussDB 100
V300R001C00 Database Reference (Standalone).

GS-00110: Failed to encrypt password


Description: Failed to encrypt the password.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Proceed according to the error information.

2.4.2 GS-00111 -- GS-00120


GS-00111: Can not reused the password

Description: An old password was used.

Solution: Use a new password.

GS-00112: Failed to init deflate or inflate, errno=%d

Description: Failed in initialization before decompression or compression.

Solution: Proceed according to the error information.

GS-00113: Failed to deflate, errno=%d

Description: Failed to perform compression.

Solution: Proceed according to the error information.

GS-00114: Failed to inflate, errno=%d

Description: Failed to perform decompression.

Solution: Proceed according to the error information.

GS-00117: Too many tables or subqueries or triggers exceeds maximum stack


depth

Description: The stack depth exceeded the allowed maximum, which is 127.

Solution: Modify the SQL statement according to the error information.

GS-00118: Failed to decode password

Description: Failed to decode the password.

Solution: Proceed according to the error information.

GS-00119: There were duplicate strings in the time format

Description: There were duplicate strings in the time format.

Solution:

● Ensure that the characters and columns are correctly entered.


● If the characters and columns are correct but the fault persists, contact
Huawei technical support.

GS-00120: Unrecognized format code

Description: The format code was unrecognized.

Solution:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

● Ensure that the characters and columns are correctly entered.


● If the characters and columns are correct but the fault persists, contact
Huawei technical support.

2.4.3 GS-00121 -- GS-00130


GS-00121: Too many bytes to converting as %s
Description: Too many bytes were involved in string conversion.
Solution: Ensure that the length of the string to be converted is within the allowed
range.

GS-00122: Can't malloc %d bytes


Description: Failed to apply for memory.
Solution: Ensure that the system memory is sufficient.

GS-00123: Malloc number(%d) already be max


Description: The requested memory exceeded the specified upper limit.
Solution: Ensure that the system memory application is correctly configured.

GS-00127: The device type was not supported


Description: The device type is not supported.
Solution: Use a supported device type.

GS-00128: Protocol not supported


Description: The protocol is not supported.
Solution: Use a supported protocol.

GS-00129: Invalid %s command


Description: The command was invalid.
Solution: Modify the command according to the error information.

GS-00130: Operation %s is not supported on %s


Description: The operation on the target is not supported.
Solution: Modify the SQL statement according to the error information.

2.4.4 GS-00131 -- GS-00140


GS-00131: The size of part key exceed max column size: %u
Description: The size of a partition key exceeded the allowed maximum.
Solution: Change the partition key size to less than or equal to the allowed
maximum.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00133: RAFT: raft is not enabled, or raft module is not inited

Description: The RAFT function was not enabled, the Raft module was not
initialized, or the initialization failed.

Solution: Enable ENABLE_RAFT, or view logs to fix the initialization failure.

GS-00134: Assert raised, expect: %s

Description: There was an assertion error, which led to an unexpected situation.

Solution: Contact Huawei technical support.

2.5 GS-00200 -- GS-00299

2.5.1 GS-00200 – GS-00210


GS-00200: The size of config file %s is too large

Description: The size of the configuration file exceeded the allowed maximum.

Solution: Change the file size according to the error information.

GS-00201: The parameter name \"%s\" was invalid

Description: The parameter name was invalid.

Solution: Set a valid parameter name.

GS-00202: The parameter value \"%s\" was invalid

Description: The parameter value was invalid.

Solution: Provide a valid parameter value.

GS-00203: %s is an readonly parameter

Description: There was an attempt to modify a read-only parameter.

Solution: Ensure that the to-be-modified parameter is not read-only.

GS-00204: Configuration buf is full

Description: Internal error. The configuration buffer was full.

Solution: Contact Huawei technical support.

GS-00205: The length of row %d is too long

Description: The length of a row exceeded the allowed maximum.

Solution: Proceed according to the error information.

GS-00207: Duplicate or conflicting parameter %s

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The configured parameter was a duplicate of or conflicted with an


existing one.
Solution: Proceed according to the error information.

GS-00208: Parameter \"%s\" is not supported in an embedded parameter file


Description: There was an unsupported parameter in the embedded configuration
file.
Solution: Proceed according to the error information.

GS-00209: The value of parameter \"%s\" is too small, at least %lld


Description: The parameter value was too small.
Solution: Increase the parameter value according to the error information.

GS-00210: The value of parameter \"%s\" is too large, at most %lld


Description: The parameter value was too large.
Solution: Reduce the parameter value according to the error information.

2.5.2 GS-00211 -- GS-00220


GS-00211: The value of parameter \"%s\" should be in [%lld, %lld]
Description: The parameter value exceeded its valid range.
Solution: Change the parameter value according to the error information.

GS-00212: The value of parameter \"%s\" cannot be recognized: \"%s\"


Description: The value of the parameter that uses enumerated values cannot be
recognized.
Solution: Change the value to a valid one by referring to the parameter manual.

GS-00213: Parameter \"%s\" must be set


Description: A mandatory parameter was not configured.
Solution: Configure the mandatory parameter by referring to the manual.

GS-00217: Nls internal error, invalid \"%s\"


Description: The internal character set was invalid.
Solution: Check the error information and ensure that the internal character set is
correct.

GS-00220: Hba line(%d) format is not correct


Description: The whitelist format was incorrect.
Solution: Check the username length, character set, and IP address format.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2.5.3 GS-00221 -- GS-00230


GS-00222: Duplicate or conflicting file %

Description: The name of the configuration file was a duplicate of an existing one.

Solution: Ensure that the name of the new configuration file is different from any
existing one.

GS-00230: %s is not an existing folder

Description: The entered path does not exist.

Solution: Enter an existing path.

2.5.4 GS-00231 -- GS-00240


GS-00231: %s is not a readable or writable folder

Description: The entered path was not readable or writable.

Solution: Ensure that the user has read and write permissions for the entered path.

GS-00232: Cipher \"%s\" is invalid or not supported

Description: The selected encryption mode is not supported.

Solution: Select a GaussDB 100-supported encryption mode by referring to the


encryption manual.

GS-00233: Empty string is not allowed here

Description: The parameter value was an empty string.

Solution: Change the parameter value by referring to the parameter manual.

GS-00240: null is not allowed for the function argument

Description: NULL was specified in an SQL function that does not allow for NULL.

Solution: Modify the SQL statement by referring to the SQL function manual.

2.5.5 GS-00241 -- GS-00250


GS-00241: The argument %d should be type %s

Description: The parameter type in the SQL function was incorrect.

Solution: Modify the SQL statement by referring to the function manual.

GS-00242: The function argument is out of range

Description: The value of the SQL function parameter was out of range.

Solution: Modify the SQL statement by referring to the description of the function
in GaussDB 100 V300R001C00 Database Reference.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00245: Invalid parameters for \"REGEXP_INSTR\", offset=%d, occur=%d,


subexpr=%d, return_opt=%d
Description: Invalid parameters were specified in the REGEXP_INSTR function.
Solution: Modify the SQL statement by referring to the REGEXP_INSTR function
manual.

GS-00246: Invalid parameters for \"REGEXP_INSTR\", offset=%d, occur=%d,


subexpr=%d
Description: Invalid parameters were specified in the REGEXP_INSTR function.
Solution: Modify the SQL statement by referring to the REGEXP_INSTR function
manual.

GS-00247: Argument %d for \"%s\" is needed


Description: The number of parameters specified in an SQL function was
insufficient.
Solution: Modify the SQL statement by referring to the function manual.

GS-00250: There must be at least one clause for the analytic function
Description: No clause was specified in the analytical function.
Solution: Modify the SQL statement by referring to the function manual.

2.5.6 GS-00251 -- GS-00260


GS-00251: Invalid separator specified in \"%s\"
Description: The delimiter specified in the SQL function was incorrect.
Solution: Modify the SQL statement by referring to the SQL function manual.

GS-00252: The 1st argument of table function needs a table name


Description: The first parameter in the table function was not specified as a table
name.
Solution: Specify the first parameter in the table function as a table name.

GS-00253: Order-by clause should be specified for the function \"%s\"


Description: The ORDER BY clause was not specified in the SQL function.
Solution: Modify the SQL statement by referring to the SQL function manual.

GS-00254 : For invited and excluded nodes is both empty, ip whitelist function
can't be enabled
Description: The whitelist and blacklist were both empty, and the whitelist
checking function was not enabled.
Solution: Configure the whitelist or blacklist, and then enable the whitelist
checking function.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00255: Ip whitelist function is enabled, invited and excluded nodes can't set to
both empty

Description: The whitelist checking function was enabled, but the whitelist and
blacklist were both empty.

Solution: Disable the whitelist checking function.

GS-00256: Cmd whitelist is enabled, cmd \"%s\" is not allowed to execute

Description: Whitelist verification proved that the injected command was not in
the whitelist.

Solution: Confirm the system environment variable settings returned by the error
code.

GS-00257: Path whitelist is enabled, path \"%s\" is not allowed to access

Description: Whitelist verification proved that the entered file path was not in the
whitelist.

Solution: Confirm the system environment variable settings returned by the error
code.

GS-00258: It is the only listening IP address and cannot be deleted.

Description: The database has only one listening IP address, which cannot be
deleted.

Solution: Check the floating IP address configuration. First add one IP address and
then delete another one. Ensure that there is at least one listening IP address in
the database.

GS-00259: IP address %s is not local ip, please check your ifconfig.

Description: The floating IP address added in the database configuration was not a
local IP address.

Solution: Use the ifconfig tool to check the IP addresses of the local NIC. Ensure
that the floating IP address added in the current database configuration is an
existing local IP address.

GS-00260: Can not get valid replication port for peer node.

Description: The REPL_PORT parameter was not configured on the peer database
or the local database was disconnected from the peer one.

Solution:

● Check whether the REPL_PORT parameter is configured on the peer database.


If it is not, configure it and restart the database.
● Check whether the primary and standby databases were disconnected. If they
were, try again. (After a disconnection, the peer database will reconnect to
the local one.)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2.5.7 GS-00291 -- GS-00299


GS-00299: "Internal logical error, message: %s"
Description: Internal error.
Solution: Modify the SQL statement according to the error information. If you still
require assistance, contact Huawei technical support.

2.6 GS-00300 -- GS-00399

2.6.1 GS-00300 -- GS-00310


GS-00301: Failed to start up Windows Sockets Asynchronous
Description: Failed to initialize the network interface.
Solution:
● Ensure that the host is normal.
● If the host is normal but the fault persists, contact Huawei technical support.

GS-00302: The protocol version of client and server is incompatible


Description: The protocol version of the client was incompatible with that of the
server.
Solution: Contact Huawei technical support.

GS-00303: Failed to establish tcp connection to [%s]:[%u]


Description: Failed to establish the TCP socket.
Solution:
● Ensure that the host network is normal.
● Reestablish the connection.
● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00304: %s connection is closed


Description: The socket of the peer process was closed.
Solution:
● Ensure that the socket of the peer process is normal.
● Reestablish the connection.
● If the socket of the peer process is normal but the fault persists, contact
Huawei technical support.

GS-00305: %s timeout
Description: The API timed out upon a network exception.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution:

● Ensure that the host network is normal.


● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00306: The packet is invalid, packet type: %u, size: %u

Description: The received message was invalid.

Solution: Contact Huawei technical support.

GS-00307: Failed to create new socket, errno %d

Description: Failed to create the network socket.

Solution:

● Ensure that the host network is normal.


● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00308: Failed to set SO_REUSEADDR option for listener socket

Description: Failed to set the socket option.

Solution:

● Ensure that the host network is normal.


● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00309: Tcp port conflict %s:%u

Description: The port was occupied by another process.

Solution: Ensure that the port is not occupied.

GS-00310: Failed to bind socket for %s:%u, error code %d

Description: Failed to bind the socket.

Solution:

● Ensure that the host network is normal.


● If the host network is normal but the fault persists, contact Huawei technical
support.

2.6.2 GS-00311 -- GS-00320


GS-00311: Failed to %s, error code %d

Description: Failed to listen to the socket.

Solution:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

● Ensure that the host network is normal.


● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00312: Failed to create new %s


Description: Failed to create the agent.
Solution:
● Ensure that the host network is normal.
● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00313: Unknown request, protocol error


Description: The communication protocol was abnormal.
Solution: Contact Huawei technical support.

GS-00314: Socket wait timeout, timeout=[%ds]


Description: Socket communication timed out.
Solution: Contact Huawei technical support.

GS-00315: Ipc listener is closed


Description: The IPC listener was closed.
Solution: Contact Huawei technical support.

GS-00316: Failed to connect to ipc server, reason: %s


Description: Failed to connect to the IPC server.
Solution: Contact Huawei technical support.

GS-00317: Ipc uninitialized


Description: IPC was not initialized.
Solution: Contact Huawei technical support.

GS-00318: The server process does not exist


Description: The server process does not exist.
Solution: Ensure that the corresponding process exists.

GS-00319: The server start timeout(3s), or the shm block is invalid


Description: Failed to start IPC.
Solution: Contact Huawei technical support.

GS-00320: Failed to generate login cipher

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: Failed to encrypt the login password.


Solution: Contact Huawei technical support.

2.6.3 GS-00321 -- GS-00330


GS-00321: Failed to recv from %s pipe, errno %d
Description: There was an error in receiving data by a TCP server.
Solution: Reestablish the connection. If the reestablishment succeeds but the fault
persists, contact Huawei technical support.

GS-00322: %s, stop accepting new connection any more


Description: The connection was closed.
Solution:
● Check the error information and ensure that the operation is proper.
● If the operation is proper but the fault persists, contact Huawei technical
support.

GS-00323: RFS is not ready, can not get %s


Description: The host was invalid.
Solution:
● Ensure that the host is valid.
● If the host is valid but the fault persists, contact Huawei technical support.

GS-00324: %s packet size(%u) exceeds the max value(%u)


Description: The sending packet size exceeded the allowed maximum.
Solution: Contact Huawei technical support.

GS-00325: Receive packet has no more data to read, packet size: %u, offset: %u,
read: %u
Description: The packet had no data for reading.
Solution: Contact Huawei technical support.

GS-00326: Replica agent error, remote ip [%s] not configured in archive


destination
Description: The remote IP address was not configured.
Solution: Contact Huawei technical support.

GS-00327: The user password has expired


Description: The user password expired.
Solution: Change the user password.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00328: The account was locked.


Description:
● The username or password was incorrect. The user account was locked after
10 incorrect consecutive login attempts.
● The account was manually locked.
Solution:
● Wait for one day, and then use the correct username and password to log in
again.
● Unlock the account.

GS-00329: Incorrect user or password


Description: The login username or password was incorrect.
Solution: Use the correct username and password to log in.

GS-00330: Invalid IP address: %s


Description: The listening IP address specified by LSNR_ADDR was incorrect.
Solution: Use a correct IP address.

2.6.4 GS-00331 -- GS-00340


GS-00331: The connecting IP is invalid according to IP white list, IP: %s, current
date: %s
Description: The client IP address was not in the whitelist, and the connection was
not allowed.
Solution: Use the host with an IP address in the whitelist to connect to the
database, or contact an administrator to add the current IP address to the
whitelist.

GS-00332: Failed to establish uds connection to [%s]


Description: Failed to establish the UDS connection.
Solution:
● Ensure that the host network is normal.
● If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00333: SSL init error: %s


Description: There was an error in creating the SSL context. The possible causes
are as follows: the memory is insufficient, the SSL certificate format is incorrect,
the SSL private key password is incorrect, or the CA certificate format is incorrect.
Solution:
Select a solution based on the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

● If the error is caused by insufficient memory, expand the memory.


● If the error is caused by an incorrect SSL certificate format, correct the format.
● If the error is caused by an incorrect SSL private key password, use OpenSSL
to verify the password. If the password is correct, use the zencrypt tool to
generate an encrypted password again, ensuring the ciphertext correctness.
● If the error is caused by an incorrect CA certificate format, correct the format
to ensure that keyUsage in the CA certificate contains the keyCertSign
option.

GS-00334: Number of sessions per user exceeds the maximum %d


Description: The number of user sessions exceeded the allowed maximum.
Solution: Increase the value of SESSIONS_PER_USER or stop connection creation.

GS-00335: Invalid IP address length: %u


Description: The length of the IP address was invalid.
Solution: Ensure that the entered IP address is in the correct format.

GS-00336: Number of IP address exceeds the maximum(%u)


Description: The number of IP addresses exceeded the allowed maximum.
Solution: Ensure that the number of IP addresses does not go beyond the allowed
maximum.

GS-00337: Database is in restricted status, only allow %s user access


Description: Only specified users are allowed to access a database when it is in the
restricted status.
Solution: Adjust the number of access users or change the database status.

GS-00338: Waiting for request head(size) timeout, %d bytes remained


Description: Waiting for the request timed out.
Solution:
1. Ensure that the host network is normal.
2. If the host network is normal but the fault persists, contact Huawei technical
support.

GS-00339: %s connection is closed, reason: %d


Description: The TCP/SSL connection was abnormally broken. The possible causes
are as follows: the server process exits abnormally, the session is killed by another
user, or the query times out.
Solution:
● Check whether the server process exits abnormally. If it does, restart it.
● If the session is killed by another user, check for the cause and reconnect to
the database.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

● If a query statement was executed, check whether the


GSC_ATTR_SOCKET_TIMEOUT attribute of the client (for the JDBC client,
check the socketTimeout attribute) is set too small, or locate the cause of
slow SQL execution. Resolve the corresponding problems and reconnect to the
database.

GS-00340: Failed to verify %s


Description: Login authentication failed.
Solution: This error is internal and not raised in the normal process. It is raised
only when packets are tampered with or forged during login.

2.6.5 GS-00341 -- GS-00350


GS-00341: Failed to verify SSL certificate, reason %s
Description: The client failed to authenticate the server's SSL device certificate
through the CA.
Solution: Fix the fault by referring to the error causes and handling suggestions in
Table 2-2.

Table 2-2 Error code reference for certificate verification


Error Code Information Error Description and Solution
Location

unable to get issuer This error is reported in 1. Load the trust


certificate multi-level certificate certificate of the device
chaining scenarios. certificate sent from the
Specifically, only the peer end.
device certificate is sent 2. Set the device
from the peer end, and certificate of the peer
the corresponding trust end to a device
certificate is not loaded certificate issued by the
on the local end, or the trust certificate of the
loaded trust certificate is local end, and update
not the issuer certificate the corresponding
of the device certificate private key.
of the peer end.

unable to get certificate Check whether the issuer To check the certificate
CRL of the CRL is the same as revocation status, load
that of the device the CRL with the same
certificate. issuer as the device
certificate.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Error Code Information Error Description and Solution


Location

self signed certificate in The certificate chain sent Load the root trust
certificate chain from the peer end has a certificate on the local
root trust certificate, but end, and ensure that the
this certificate is not trust certificate loaded
loaded on the local end, on the local end and the
or the loaded root trust device certificate chain
certificate is not the sent from the peer end
issuer certificate of the form a complete
device certificate of the certificate chain, that is,
peer end. all certificates from the
self-issued certificate to
the device certificate
have issuing
relationships.

unable to get local issuer 1. The certificate chain 1. Load the root trust
certificate sent from the peer end certificate on the local
has no root trust end, and ensure that the
certificate, and no root trust certificate loaded
trust certificate is loaded on the local end and the
on the local end, or the device certificate chain
loaded root trust sent from the peer end
certificate is not the form a complete
issuer certificate of the certificate chain, that is,
device certificate of the all certificates from the
peer end. self-issued certificate to
2. The number of the device certificate
certificates in the have issuing
certificate chain is relationships.
greater than 10. 2. Reduce the number of
certificates in the
certificate chain. A
database supports a
maximum of 10
certificates in the chain.

certificate revoked The issuer certificate of If the product has the


the device certificate of CRL mechanism enabled,
the peer end is revoked, it needs to update the
the CRL is loaded on the device certificate loaded
local end, and the device on the peer end.
certificate is in the CRL.

certificate has expired The UTC time of the If the validity period is
current system is later incorrectly set, generate
than the end of the a new certificate and
certificate validity period. ensure that the validity
period of the certificate
is later than the current
time.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00342: REPL_PORT is used for replication only, external service will be rejected

Description: The port REPL_PORT was used by the client to connect to the
database.

Solution: REPL_PORT is used for primary/standby replication and cannot provide


external services. Use LSNR_PORT to connect to the database.

GS-00343: SSL is required but the server doesn't support it

Description: The client requested to establish an SSL connection, but the server did
not support SSL authentication.

Solution:

1. Configure SSL certificates and enable SSL authentication on the server. For
details, see "Database Usage > Connecting to a Database in GaussDB 100
V300R001C00 User Guide (Standalone)..
2. Set the SSL authentication mode of the client to DISABLED to disable SSL
connections. For a JDBC client, use useSSL=false in the URL. Note that disabling
SSL connections reduces the security of data communication.

GS-00344: SSL CA certificate is required when ssl_mode is SSL_VERIFY_CA or


SSL_VERIFY_FULL

Description: The CA certificate was not configured on the client.

Solution:

1. Ensure that the CA certificate is correctly configured on the client.


2. Change the SSL authentication mode of the client to REQUIRED or lower.
Note that reducing the SSL authentication level prohibits the server identity
from being authenticated.

GS-00345: The SSL connection failed, %s

Description: Failed to establish the SSL connection. Generally, this error is raised in
the SSL handshake phase, indicating a failure in authenticating the client
certificate by the server. For details about the failure cause, see Table 2-2 based
on '%s'.

Solution:

1. Use OpenSSL to check the validity of the client device certificate. If the
authentication fails, update the SSL certificate.
2. Disable client authentication on the server and use SSL_VERIFY_PEER=FALSE.
Note that disabling the authentication prohibits the client identity from being
authenticated.

GS-00346: SSL certificate file \"%s\" has execute, group or world access permission

Description: The SSL certificate access permission exceeded 600.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Run the chmod command to change the access permission for the SSL
certificate to 400 (read-only for the owner) or 600 (read-write for the owner).

GS-00347: SSL encrypted connection is required for "<user_name>" from


"<ip_addr>"
Description: The IP address whitelist was configured for the SSL user on the server,
requiring SSL connection. However, the SSL connection was disabled on the client.
As a result, the connection failed.
Solution: Enable the SSL function on the client and reestablish the connection.
● For the zsql client, set ZSQL_SSL_MODE to PREFERRED or higher.
● For the c/python/go driver, set GSC_ATTR_SSL_MODE to 1 or higher.
● For the JDBC driver, set useSSL for URL connection to true.

GS-00348: Failed to bind unix domain socket for %s, error code %d
Description: Failed to bind the Unix domain socket file.
Solution: Check whether the path of the Unix domain socket file already exists and
whether the user has required permissions.
● Check error code in the error information. If it is followed by 13, the user
does not have file permissions, and UDS_FILE_PERMISSIONS has been
incorrectly configured.
● If it is followed by 19, UDS_FILE_PATH has been configured, but the file path
does not exist.

GS-00349: unix domain socket conflict %s


Description: Unix domain socket path listening conflicted.
Solution: Multiple database instances listen to the same UDS path. Modify
UDS_FILE_PATH.

2.7 GS-00400 -- GS-00499

2.7.1 GS-00400 -- GS-00410


GS-00401: Environment variant %s not found
Description: The GSDB_HOME directory does not exist.
Solution: Correctly configure a GSDB_HOME directory.

GS-00403: Too many connections exceed pool maximum


Description: There were too many connections.
Solution: Close some connections or increase the value of SESSIONS.

GS-00404: There were too many autonomous transactions.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: There were too many autonomous transactions.


Solution: Contact Huawei technical support.

GS-00405: Can not release normal session as autonomous session


Description: Autonomous transaction processing failed.
Solution: Contact Huawei technical support.

GS-00406: Can not begin nested autonomous session


Description: There was a nested transaction.
Solution: Proceed according to the error information.

GS-00407: Start kernel instance failed


Description: Failed to start the database instance.
Solution: Proceed according to the error information.

GS-00408: The resource requested in NOWAIT mode was being occupied or not
released after the request timed out.
Description: The resource requested in NOWAIT mode was being occupied or not
released after the request timed out.
Solution: Perform a commit or rollback operation in the session that occupies the
current resource to release the resource lock.

GS-00409 : Unknown mode of select for update


Description: An unsupported wait mode was specified for SELECT FOR UPDATE.
Solution: Specify a supported mode for SELECT FOR UPDATE.

2.8 GS-00500 -- GS-00599

2.8.1 GS-00500 -- GS-00510


GS-00500: Unknown error
Description: Unknown error.
Solution: Contact Huawei technical support.

GS-00501: Invalid %s: %s


Description: The SQL attribute name setting was invalid.
Solution: Proceed according to the error information.

GS-00502: Invalid %s: %u


Description: The SQL attribute value setting was invalid.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Proceed according to the error information.

GS-00503: %s %u as string buffer is too small


Description: The bind column buffer provided by the client was too small.
Solution: Contact Huawei technical support.

GS-00504: Failed to bind parameter, %s


Description: The bind parameter value was invalid.
Solution: Bind a valid value according to the error information.

GS-00505: Row column count(%u) is not equal to stmt %s count(%u)


Description: There was an invalid column.
Solution: Proceed according to the error information.

GS-00506: There was out-of-range behavior on the index: %s


Description: There was out-of-range behavior on the client, for example, invalid
column IDs or bind parameters were used.
Solution: Input correct parameter values.

GS-00507: Size of bindings exceed the maximum(%u)


Description: The number of bind parameters set on the client exceeded the
allowed maximum.
Solution: Specify allowed bind parameters in the SQL statement.

GS-00508: Out of API sequence, %s


Description: APIs were not invoked in the correct sequence.
Solution: Invoke the APIs in the correct sequence.

GS-00509: Column %u binding buffer is too small, buffer size: %u, size required:
%u
Description: The program-provided buffer was too small.
Solution: Contact Huawei technical support.

GS-00510: Column %u %s buffer is too small, buffer size: %u


Description: The program-provided buffer for the column was too small.
Solution: Contact Huawei technical support.

2.8.2 GS-00511 -- GS-00520


GS-00511: Buffer is too small to %s
Description: The buffer was too small.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Contact Huawei technical support.

GS-00512: %s is null
Description: The operation object was null.
Solution: Proceed according to the error information.

GS-00513: Failed to translate charset, column: %s, value: %s


Description: Failed to convert the string based on character sets.
Solution: Ensure that the character sets configured on the client and server are
supported.

GS-00514: Connect is not established


Description: The connection was closed.
Solution: Open the connection, and then perform related operations.

GS-00515: Multiple sql must use query mode to execute


Description: Executing multiple SQL statements did not use the gsc_query_multiple
interface.
Solution: Use the correct GSC interface to execute multiple SQL statements.

GS-00517: Parallel operation is not supported, sid=[%u], tid=[%u], current


tid=[%u]
Description: There were concurrent operations on the DBLINK object over the
interface.
Solution: Correctly use the GSC interface. Multithreading, concurrent operations
are not allowed on the same DBLINK object.

GS-00519: Err occur when write file


Description: There was an error in writing the file.
Solution: Ensure that the disk space is sufficient and do not perform improper
write operations on the file.

GS-00520: Import error occur when %s, detail: %s


Description: There was an error in importing the file.
Solution: Proceed according to the error information.

2.8.3 GS-00521 -- GS-00530


GS-00522: Unix domain socket path is empty
Description: UDS_SERVER_PATH had not been specified when UDS was used to
connect to the database.
Solution: Use the zsql server to specify UDS_SERVER_PATH.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00524: Unexpected packet cmd, expect %u, receive %u

Description: The client received an unexpected packet. That is, the command
keywords do not match.

Solution: Contact Huawei technical support.

2.9 GS-00600 -- GS-00699

2.9.1 GS-00600 -- GS-00610


GS-00601: Sql syntax error: %s

Description: The SQL syntax was incorrect.

Solution: Modify the SQL statement according to the error information.

GS-00602: Sql text is too long, length = %u

Description: The SQL statement was too long. Currently, the allowed maximum
size of an SQL statement is 1 MB.

Solution: Modify the SQL statement to ensure a proper length.

GS-00604: Duplicate %s name %s

Description: There were duplicate object names in the SQL statement.

Solution: Ensure that object names are unique.

GS-00606: Inconsistent datatypes, expected %s - got %s

Description: The data type in the SQL statement does not match the expected one.

Solution: Change the data type according to the error information.

GS-00607: Invalid datatype for %s

Description: The data type was invalid.

Solution: Use a GaussDB 100-supported data type.

GS-00608: Invalid expression

Description: The SQL expression syntax was incorrect.

Solution: Use a valid SQL expression.

GS-00609: Invalid number text %s

Description: The SQL operator was invalid.

Solution: Correct the SQL syntax according to the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2.9.2 GS-00611 -- GS-00620


GS-00611: No sql %s
Description: APIs were not invoked in the correct sequence.
Solution: Properly invoke APIs. For details, see "Development Based on C APIs" in
GaussDB 100 V300R001C00 R&D Documentation (Standalone).
GS-00613: Invalid operation
Description: The current operation was invalid.
Solution: Proceed according to the error information.

GS-00614: Parameter error: %s


Description: Invalid parameters were used in the SQL function.
Solution: Use valid parameters.

GS-00615: Invalid argument number for %s, min=%u, max=%u


Description: The number of parameters in the function was incorrect.
Solution: Use valid parameters.

GS-00618: The column '%s' was invalid


Description: The column name was invalid.
Solution: Use a valid column name.

GS-00619: The number of columns specified in view creation was inconsistent with
that of columns covered in query
Description: The number of specified columns was incorrect.
Solution: Modify the SQL syntax according to the error information.

GS-00620: Can't set NULL value for column '%s'


Description: The column contained value NULL.
Solution: Change the column value according to the error information.

2.9.3 GS-00621 -- GS-00630


GS-00621: Too many material result sets
Description: There were too many materialized result sets during SQL execution.
Solution: Check whether conditions can be added to the SQL syntax to filter out
useless table records. If they can, add the conditions to reduce materialized result
sets. If the fault persists after the above measure is taken, contact Huawei
technical support.
GS-00622: Virtual memory capacity error, details is '%s'

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: There was no free memory in the pool.


Solution: Check whether database parameters are set properly. For details, see
"Parameters" in GaussDB 100 V300R001C00 Database Reference. In addition,
check dynamic views to ensure no memory leak in service code.
If the fault persists after the above measure is taken, contact Huawei technical
support.

GS-00623: Sql execute error, detail is '%s'


Description: There was an error in SQL execution.
Solution: Proceed according to the error information.

GS-00624: The distinct column type [%d] is not supported


Description: The current SQL syntax does not support the column type.
Solution: Correct the SQL syntax according to the error information.

GS-00626: Set %s is not supported


Description: The parameters are not supported in the current version.
Solution: Use only parameters supported in the current version.

GS-00629: Virtual memory error, detail is '%s'


Description: There was an error in the memory of the temporary tablespace.
Solution: Proceed according to the message in %s.
● If the message is "fail to open vm page, the pages are already full", the
temporary tablespace has insufficient memory. In this case, increase the value
of TEMP_BUFFER_SIZE.
● If the message is "fail to create temp_btree_create_segment in
knl_open_temp_cursor", the temporary table cursor runs abnormally. In this
case, contact Huawei technical support.

2.9.4 GS-00631 -- GS-00640


GS-00633: Cannot create index on column with datatype lob
Description: An index was created on the column with the data type LOB.
Solution: Do not create indexes on a column with the data type LOB.

GS-00634: The total length (%d) of columns within an index exceeded the
maximum.
Description: The length of the index key exceeded the allowed maximum.
Solution: Correctly create an index.

GS-00635: %s
Description: The value was invalid.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Provide a valid value according to the error information.

GS-00636: Invalid number: %s


Description: There was an invalid value in the number-type column.
Solution: Provide a valid value for the number-type column according to the error
information.

GS-00637: The divisor was zero.


Description: The divisor was 0.
Solution: Do not use 0 as the divisor.

GS-00638: Login using %s is not allowed


Description: The user login was rejected.
Solution: Proceed according to the error information.

GS-00639: The row ID was invalid.


Description: There was an invalid row ID.
● This error is reported when an SQL statement contains WHERE ROWID=X but
the value of ROWID is invalid, for example, SELECT * FROM TABLE1 WHERE
ROWID= 12345;.
● The ROWID column cannot be used for joining two tables. If it is used, this
error will be reported. For example, SELECT * FROM T1 LEFT JOIN T2 ON
T1.ROWID=T2.ROWID;.
Solution: Ensure that the value of ROWID is a string of 18 numbers and is
enclosed in single quotation marks. You are advised to run SELECT ROWID FROM
Table name; to query for the value of ROWID before entering it.

GS-00640: The table had more than one primary key.


Description: There was more than one primary key.
Solution: Do not create the primary key repeatedly.

2.9.5 GS-00641 -- GS-00650


GS-00641: No insert/update/delete on table with some constraints disabled and
validated
Description: The operation violated existing constraints.
Solution: Proceed according to the error information.

GS-00642: The unique index or primary key was referenced by a foreign key.
Description: The table information was referenced by a foreign key.
Solution: Proceed according to the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00643: Table %s.%s is not empty, hint: use force option to flashback truncate
Description: The table was not empty.
Solution: Proceed according to the error information.

GS-00644: Too few arguments for %s


Description: The number of parameters was too small.
Solution: Proceed according to the error information.

GS-00645: Invalid flashback type %d


Description: The flashback operation type was invalid.
Solution: Select a proper flashback command according to the error information.

GS-00646: Invalid purge type %u


Description: Internal error. There was an invalid purge type.
Solution: Contact Huawei technical support.

GS-00647: The purge operation was invalid:%s


Description: Internal error. There was an invalid purge operation.
Solution: Contact Huawei technical support.

GS-00648: Invalid scan mode %d


Description: Internal error. There was an invalid table scan type.
Solution: Contact Huawei technical support.

GS-00650: The column referenced by a foreign key was not the unique index or
primary key of the referenced table
Description: Constraint conditions were not met.
Solution: Proceed according to the error information.

2.9.6 GS-00651 -- GS-00660


GS-00651: The index cannot be deleted because it is referenced by a primary key
or unique index
Description: The index cannot be deleted by DROP INDEX because it is referenced
by a primary key or unique key constraint.
Solution: Use the ALTER TABLE DROP CONSTRAINT syntax to delete the
constraint.

GS-00652: Multiple default values specified for column \"%s\"


Description: Multiple default values were specified for a column.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Specify one default value for one column.

GS-00654: The size of one row is %u, must be less than %u


Description: The total size of a row exceeded the allowed maximum, which is
64,000 bytes, including the row header (about 20 bytes).
Solution: Ensure that the total size of a row does not go beyond the allowed
maximum. Use the CLOB or BLOB type to replace the long string type.

GS-00655: Invalid page id


Description: Internal error. There was an invalid page ID.
Solution: Contact Huawei technical support.

GS-00656: Dictionary cache is corrupted


Description: Internal error. Table metadata was corrupted.
Solution: Contact Huawei technical support.

GS-00657: Password is too simple, password should contain at least three of the
following character types:
A. at least one lowercase letter
B. at least one uppercase letter
C. at least one digit
D. at least one special character: `~!@#$%%^&*()-_=+\\|[{}];:\'\",<.>/? and space
Description: The configured password was too simple.
Solution: Change the password based on the password complexity requirements.

GS-00658: The password was invalid: %s


Description: The password format was incorrect.
Solution: Change the password based on the password format requirements.

GS-00659: %s out of range


Description: Invalid data type value. The value was out of range.
Solution: Contact Huawei technical support.

GS-00660: There was an infinite loop in CONNECT BY execution


Description: The CONNECT BY loop syntax was incorrect.
Solution: Correct the SQL syntax according to the error information.

2.9.7 GS-00661 -- GS-00670


GS-00661: Finish scn can not little than prepare scn %llu

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The value of finish scn was invalid.


Solution: Change the value of finish scn to a valid one according to the error
information.

GS-00662: Invalid backupset


Description: Internal error. The backup was incomplete.
Solution: Ensure that the specified backup set is complete.

GS-00663: Synonym object %s.%s is not table or view type


Description: The type of the synonym object was invalid.
Solution: Use a valid synonym object.

GS-00664: Connect by level can not exceed %u


Description: The value of level in CONNECT BY exceeded the allowed maximum.
Solution: Correct the SQL syntax according to the error information.

GS-00665: Value size(%u) from cast operand is larger than cast target size(%u)
Description: Failed to convert the value type.
Solution: Proceed according to the error information.

GS-00666: Lob value too large in expression (actual: %u, maximum: %u)
Description: There was an error in reading LOB.
Solution: Proceed according to the error information.

GS-00669: Backup tag :%s already exists


Description: The tag specified by the backup command conflicted with an existing
one.
Solution: Specify a new tag.

GS-00670: Failed to save backupset info


Description: There was an error in recording backup set information in the system
catalog after the backup was complete. It is internal error code.
Solution: Contact Huawei technical support.

2.9.8 GS-00671 -- GS-00680


GS-00671: Backupset of tag :%s not prepare
Description: During distributed log backup, the corresponding data backup was
not in the prepare state.
Solution: Query the system catalog to check whether there is a specified tag.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00672: No valid base backupset, can not execute incremental backup


Description: No valid baseline was found for incremental backup.
Solution: Perform baseline incremental backup.

GS-00673: Invalid interval text %s


Description: The INTERVAL text format was incorrect.
Solution: Correct the format by referring to the text formats supported by
INTERVAL.

GS-00674: %s field exceeds the specified precision (%u)


Description: The domain of the INTERVAL type (such as year, month, day, hour,
minute, or second) went beyond the specified range.
Solution: Correct the domain of the INTERVAL type to a valid one.

GS-00675: Values in resource limit settings were invalid


Description: The value of resource limit was invalid. It did not exceed 0. For
example, the values '3'||'w' and -4 are both invalid. If they are used in an SQL
statement to create or modify an archive, an error will be reported.
Solution: Ensure that the value of resource limit entered for each SQL statement
is greater than 0.

GS-00676: Shutdown current session (sid %d) is prohibited


Description: The shutdown process was prohibited. For example, if multiple clients
execute the shutdown process at the same time and only one client succeeds first,
this error will be reported on other clients.
Solution: Wait for a while and check whether the rest clients are disconnected. If
they are not, trigger the process execution again.

GS-00677: Column ancestor level mismatch


Description: The column does not match the parent-child association of the cursor.
Solution: Contact Huawei technical support.

GS-00678: Invalid or lack character after escape


Description: There was no character following the escape character.
Solution: Add a character after the escape character.

GS-00679: The index cannot be used as a constraint


Description: When a primary key or unique key constraint was added to a table,
the USING INDEX clause forcibly specified an existing index. However, the indexed
column does not match the constraint column, and the index cannot be used as a
constraint.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Rebuild the index or modify the constraint adding statement to ensure
that the constraint column and indexed column match. Alternatively, remove the
USING INDEX clause, and use the database-created default index.

GS-00680: Specified length of column %s too long(> %u) for its datatype in
partition key

Description: The maximum length of the data type of the partition key for
creating a partitioned table exceeded the allowed maximum.

Solution: Use a correct data type for the partition key.

2.9.9 GS-00681 -- GS-00690


GS-00681: Regular expression compiling error, errloc=%d, errmsg=[%s]

Description: There was an error in compiling the regular expression.

Solution: Use a correct regular expression.

GS-00683: The session ID was missing or invalid

Description: The session ID was invalid. For example, the entered session ID is
smaller than the number of reserved sessions or the session ID does not match
serial. When ALTER SYSTEM KILL SESSION is executed, this error is reported.

Solution: Use the SELECT * FROM DV_SESSIONS; statement to query for the ID of
the session to be ended.

GS-00684: The current session cannot be killed

Description: Failed to kill the current session. When ALTER SYSTEM KILL SESSION
is executed, this error is reported.

Solution: Use the SELECT * FROM DV_SESSIONS; statement to query for the ID of
the session to be ended.

GS-00685: The referenced table had no primary key

Description: If no column is specified during foreign key creation, the primary key
of the parent table will be used by default. This error is reported when the parent
table has no primary key in this situation.

Solution: Set the primary key for the parent table.

GS-00687: Inserted values were too many

Description:

● When the INSERT INTO statement is executed and there is a SELECT


subquery condition, the number of columns (to be inserted) in the subquery
result is greater than the number of columns in the target table for insertion.
● When the SELECT statement is executed and there is an IN/NOT IN condition
clause, the number of columns in the IN/NOT IN subquery result is greater
than that in the condition clause.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Ensure that the numbers of columns in the left and right of the condition
are the same.

GS-00688: Sql has too many bind parameters, count = %d, max = %d
Description: The number of bind variables in the SQL statement exceeded the
allowed maximum.
Solution: Reduce the number of bind variables in the SQL statement.

GS-00689: Number of output parameter not match binding


Description: The number of output parameters does not match the number of
bind variables.
Solution: Change the number of bind variables.

GS-00690: Sequences were not supported.


Description: Sequences in the SQL statement are not supported.
Solution: Use the correct SQL syntax.

2.9.10 GS-00691 -- GS00699


GS-00691: Unknown lob type
Description: The internal LOB type was incorrect.
Solution: Check whether the communication content is valid according to the error
information.

GS-00692: Invalid interval text -- %s field out of range (<=%u)


Description: The INTERVAL string format was invalid.
Solution: Check the value of YEAR/MONTH/DAY/HOUR/MINUTE/SECOND
according to the error information, and ensure a valid value.

GS-00693: Invalid segment entry


Description: The segment entry was invalid.
Solution: Proceed according to the error information.

GS-00694: DATETIME out of range, it must be between %04d-01-01 00:00:00 and


%04d-12-31 23:59:59
Description: The value of DATETIME was out of range.
Solution: Change the value.

GS-00695: TIMESTAMP out of range, it must be between %04d-01-01


00:00:00.000000 and %04d-12-31 23:59:59.999999
Description: The value of TIMESTAMP was out of range.
Solution: Change the value.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00696: Minconn(%u) should less than maxconn(%u)


Description: The configured minimum number of connections exceeded the
maximum one.
Solution: Change the numbers of connections.

GS-00697: Unsupported page type


Description: The page type is not supported.
Solution: Change the page type.

GS-00698: The size(%u) of value can't larger than defined size(%u) of %s


Description: The size of the current value exceeded the allowed maximum.
Solution: Proceed according to the error information.

GS-00699: Argument %s is not found in procedure/function


Description: The specified parameter was not found in the current procedure or
function.
Solution: Proceed according to the error information.

2.10 GS-00700 -- GS-00799

2.10.1 GS-00700 -- GS-00710


GS-00701: The control file was damaged.
Description: Control files were damaged.
Solution: Ensure that the control files are undamaged and try again.

GS-00702: Failed to load ctrl file, %s


Description: No control file was available.
Solution: Ensure that there are available control files and try again.

GS-00704: Invalid charset for %s, %x


Description: The character set was invalid.
Solution: Use the UTF-8 or GBK character set.

GS-00705: Invalid database def because %s


Description: The definition was not supported by the database.
Solution: Use a definition supported by the database.

GS-00706: The number %u reached the upper limit of %s.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The number of data files reached the upper limit.


Solution: Delete unnecessary data files.

GS-00707: Invalid dictionary of table %s


Description: The data dictionary was invalid.
Solution: Try again when the data dictionary becomes valid.

GS-00708: The object %s %s does not exist.


Description: The object does not exist.
Solution: Find out the reason why the object does not exist, for example, the
object failed to be created due to insufficient tablespace or the object was deleted.
Then, rectify the fault accordingly.

GS-00710: Dictionary buffer is full


Description: The dictionary buffer was full.
Solution: Increase the value of SHARED_POOL_SIZE.

2.10.2 GS-00711 -- GS-00720


GS-00711: Log replay stopped at %u:%u, it did not reach the least recovery point
(LRP) %u:%u.
Description: Data was not recovered to the specified least recovery point (LRP)
recorded in the log. It may be because the log file did not exist or was damaged.
Solution: Find out the reason why the log file did not exist or was damaged and
rectify the fault accordingly.

GS-00712: Invalid batch %s


Description: The batch was invalid because the log file was damaged.
Solution: Find out the reason why the log file was damaged and rectify the fault
accordingly.

GS-00713: No free undo page


Description: The UNDO tablespace had insufficient space.
Solution: Expand the UNDO tablespace.

GS-00714: Log file size should be larger than log keep size %lld
Description: The size of the log file was too small.
Solution: Increase the specified log file size or decrease the value of
LOG_BUFFER_SIZE in the configuration file.

GS-00715: The snapshot was outdated.


Description: The snapshot was outdated.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Initiate a query again.

GS-00716: Found %s deadlock in session (%u)


Description: A deadlock occurred.
Solution: Find out the deadlock cause and rectify the fault accordingly.

GS-00717: Locking timed out while the operation was waiting.


Description: Timed out while waiting for lock for transaction log files.
Solution: Identify the lock and try again after the lock is released.

GS-00718: Current operation was canceled by the user.


Description: The operation was canceled by pressing Ctrl+C or because of an
exception.
Solution: Perform the operation again.

GS-00719: Session killed


Description: The session was killed.
Solution: Reconnect to the database.

GS-00720: Too many pending transaction


Description: The transaction space was insufficient because there were too many
pending transactions.
Solution: Reduce concurrency or clear the pending two-phase transactions.

2.10.3 GS-00721 -- GS-00730


GS-00722: Dictionary cache is invalidated
Description: The dictionary cache was unavailable.
Solution: Open the table again.

GS-00723: The resource to be locked was occupied, and the wait for the resource
timed out or the NOWAIT mode was used.
Description: The resource to be locked was occupied, and the waiting for the
resource timed out; or the NOWAIT mode was used.
Solution: Release the resource and try again.

GS-00724: Synonym %s.%s does not exist


Description: The synonym does not exist.
Solution: Create the synonym.

GS-00725: Too many indexes on table %s.%s

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The number of indexes in the table exceeded the allowed maximum.
Solution: Contact Huawei technical support.

GS-00726: The column has been indexed by %s.


Description: An index had been created on the column.
Solution: Create the index on other columns.

GS-00727: %s size %u exceeds the limitation %u


Description: The row to be operated was too long.
Solution: Shorten the row.

GS-00728: failed to find free space size: %u


Description: The disk space was insufficient.
Solution: Clear the disk or contact Huawei technical support.

GS-00729: Unique constraint violated%s.


Description: The UNIQUE index contained duplicate keys.
Solution: If a duplicate key error occurs due to INSERT, the index name and the
values in each column of the duplicate keys will be appended to the error
message, for example, "GS-00729, Unique constraint violated index IDX_T4_1,
duplicate key C-A." If the total length of an additional message exceeds 256 bytes,
only the values in the first several columns are displayed. The length of a single
column cannot exceed 128 bytes. The excess part will be truncated. You can
identify duplicate keys according to error messages or contact Huawei technical
support.

GS-00730: Database has not been created or is not open


Description: The database does not exist or was not open.
Solution: Do not use a nonexistent database or a database that is not open.

2.10.4 GS-00731 -- GS-00740


GS-00731: File hwm pages % u exceeds maximum of %u pages in space %s
Description: The number of pages in the file exceeded the allowed maximum.
Solution: Use a new file.

GS-00732: The table definition of %s.%s has been changed.


Description: The table definition was changed.
Solution: Restore the table by using Point-in-Time Recovery (PITR) or other
methods.

GS-00733: Error occurred when the transaction is in progress, %s

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: There were transactions in progress in the session.


Solution: Terminate the transactions and try again.

GS-00734: Invalid transaction isolation level %u


Description: The transaction isolation level was invalid.
Solution: Do not use transaction isolation levels other than READ COMMITTED
and SERIALIZABLE, and READ CURRENT COMMITTED.

GS-00735: Failed to set the transaction isolation level to Serializable.


Description: The transaction isolation level failed to be set to SERIALIZABLE.
Solution: Find out the reason and rectify the fault accordingly.

GS-00736: The savepoint '%s' does not exist.


Description: The savepoint does not exist.
Solution: Specify the savepoint and try again.

GS-00737: Session holds too many savepoints.


Description: There were too many savepoints in the session.
Solution: Delete unnecessary savepoints.

GS-00738: The database is already in the MOUNT state


Description: The database was in the MOUNT state while the operation was
performed. Actually, the NOMOUNT state is needed.
Solution: Restart the database to the NOMOUNT state.

GS-00739: The database has been opened.


Description: The database was open.
Solution: It is informational only. Ignore it.

GS-00740: No more free locks


Description: No more table locks can be allocated because there was no sufficient
space even after the memory was expanded.
Solution: Release unnecessary locks.

2.10.5 GS-00741 -- GS-00750


GS-00741: Too many pending result set
Description: There were too many rows in the result set.
Solution: Contact Huawei technical support.

GS-00742: Tablespace %s is not empty, %s

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The tablespace to be deleted was not empty.


Solution: Clear the tablespace.

GS-00743: %s %u already exists


Description: The object ID already exists.
Solution: Query views for the object that holds the ID.

GS-00744: Datafile %s has already been used, can not remove it in space %s
Description: The high-water mark (HWM) of the data file to be deleted was not 0,
indicating that the data file was in use and failed to be deleted.
Solution: Do not delete this data file.

GS-00746: The data file %s was renamed to an existing name.


Description: The data file was renamed to an existing name.
Solution: Rename the data file to another name.

GS-00748: %s name length is exceeded. name len = %d, max_len = %d


Description: The database name was too long.
Solution: Shorten the name and try again.

GS-00749: Drop tablespace %s failed, database must be in mount mode


Description: The tablespace to be deleted was not in the mount state.
Solution: Set the database status to mount.

GS-00750: Alter database is forbidden during backup


Description: The ALTER DATABASE statement was forbidden during backup.
Solution: Run the ALTER DATABASE statement after the backup is complete.

2.10.6 GS-00751 -- GS-00760


GS-00751: %s already running, can not start another process
Description: Concurrent backup and restoration are not allowed.
Solution: Serially back up and restore data.

GS-00752: Database is in recovery, please use 'shutdown abort' or try later


Description: The SHUTDOWN or SHUTDOWN IMMEDIATE statement is not
allowed when a database is being restored.
Solution: Run SHUTDOWN or SHUTDOWN IMMEDIATE after the restoration is
complete, or use SHUTDOWN ABORT instead.

GS-00753: The object %s %s already exists.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The object already exists.


Solution: Delete the existing object if necessary.

GS-00754: %s exceeded max number


Description: The number of columns used for creating constraints or indexes
exceeded the allowed maximum.
Solution: Reduce the number of columns used for creating indexes or constraints.

GS-00755: The column was referenced as a constraint.


Description: A constraint was created on the column.
Solution: Create the constraint on other columns.

GS-00757: Offline datafile %s failed, this file not exists in space %s


Description: The offline data file does not exist.
Solution: Enter the correct name of the offline data file.

GS-00758: The tablespace %s is offline, %s.


Description: The tablespace was offline.
Solution: Use another tablespace to create the table.

GS-00759: Participant of merge sort cannot be found due to invalid index: %d


Description: The index was invalid.
Solution: Contact Huawei technical support.

GS-00760: Datafile %s break down, %s


Description: The data file was damaged.
Solution: Take the data file offline.

2.10.7 GS-00761 -- GS-00770


GS-00761: Could not offline datafile in space %s
Description: Taking files in the SYSTEM tablespace offline was not allowed.
Solution: Do not take the files in the SYSTEM tablespace offline.

GS-00762: Drop offline tablespace %s must be in open mode


Description: The database was not in the open state when the offline tablespace
was deleted.
Solution: Set the database status to open.

GS-00763: The tablespace name already exists.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The tablespace name already exists.


Solution: Use another name.

GS-00764: %s must in OPEN status


Description: The database was not in the open state.
Solution: Set the database status to open.

GS-00766: Database is not created completely


Description: The database was created or restored incompletely.
Solution: Recreate or restore the database.

GS-00767: %s property for %s exceeds or smaller than size that system allowed
Description: The size parameters of the data file were invalid.
Solution: Set the parameters to valid values.

GS-00768: Operation can only be executed in mount status


Description: The database was not in the mount state.
Solution: If the database is in the nomount state, run the ALTER DATABASE
MOUNT statement to change it to mount. If the database is in the open state,
restart the database to enable the mount state.

GS-00769: Tablespace %s has a larger scn, origin tablespace replaced by


tablespace %s
Description: The original tablespace of the object was deleted.
Solution: Delete the object.

GS-00770: Not all transactions were committed when the database was shut
down.
Description: Not all transactions were committed when the database was shut
down.
Solution: Commit or roll back the transactions not committed and shut down the
database again.

2.10.8 GS-00771 -- GS-00780


GS-00771: %s file %s does not exist
Description: The file does not exist.
Solution: Ensure that the file exists and try again.

GS-00772: Switchover cannot be issued when raft is enabled


Description: Switchover was performed when Raft was enabled.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Do not perform a switchover when Raft is enabled.

GS-00773: %s can not be done when database is %s


Description: The operation failed to be performed when the standby database was
active.
Solution: Do not perform this operation when the standby database is active.

GS-00774: Failover in progress, can not be connected


Description: The primary database initiated a log sending thread to connect to a
standby database when the standby database was performing a failover.
Solution: Stop the primary database and set it to standby after the standby is
promoted to primary.

GS-00775: Invalid switch request, %s


Description: Switchovers or failovers are not allowed in the current database
status. Alternatively, there were concurrent switchovers or failovers.
Solution: Modify the database status according to the error information.
Alternatively, wait for other command execution to complete and then send the
failover or switchover command again.

GS-00776: No more free lob items


Description: There was no space for more LOB items even if the memory was
expanded.
Solution: Expand the space or clear unnecessary resources.

GS-00777: Too many primary, %s


Description: Multiple primary databases connected to the standby database.
Solution: Do not connect multiple databases to the same standby database.

GS-00778: Database not in archive mode, can not execute backup prepare
Description: The database was not in the archiving mode.
Solution: Enable the archiving mode for the database.

GS-00779: Error happened when sort %s parallel


Description: Failed to create indexes in parallel.
Solution: Try again.

GS-00780: The tablespace %s does not exist.


Description: The tablespace does not exist.
Solution: Ensure that the tablespace name you have entered exists.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2.10.9 GS-00781 -- GS-00790


GS-00781: The user %s does not exist.
Description: The user does not exist.
Solution: Create the user.

GS-00782: MAXIMIZE PROTECTION mode need at least 1 sync standby


Description: There was no synchronous standby in MAXIMUM PROTECTION
mode.
Solution: Ensure that there is at least one synchronous standby database, and then
try to switch to the MAXIMUM PROTECTION mode.

GS-00783: The role %s does not exist.


Description: The role does not exist.
Solution: Create the role.

GS-00784: Rfs thread not ready


Description: The primary-standby link was not ready.
Solution: Ensure that the primary-standby link parameters are correctly
configured, the network between the primary and standby databases is normal,
and the firewall is correctly configured.

GS-00785: Profile %s does not exist


Description: The profile does not exist.
Solution: Create the profile.

GS-00786: Could not find datafile to extend extent in tablespace %s


Description: The disk space was insufficient. As a result, the tablespace cannot be
extended.
Solution: Clear the disk or contact Huawei technical support.

GS-00787: Shutdown was canceled


Description: The SHUTDOWN statement was canceled.
Solution: If you are sure to shut down the database, run the SHUTDOWN
statement again.

GS-00788: Tablespace %s already exists


Description: The tablespace name already exists.
Solution: Use another tablespace name.

GS-00789: The foreign key constraint already exists.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The foreign key constraint already exists.


Solution: Do not create the constraint repeatedly.

GS-00790: Failed to drop tablespace %s, because %s


Description: Failed to delete the tablespace online because there were objects in
the tablespace.
Solution: Clean up these objects and delete the tablespace again.

2.10.10 GS-00791 -- GS-00799


GS-00791: Local is cascaded standby, and another database has connected
Description: The primary database connected to the cascaded standby database
instead of the standby database.
Solution: No action is required because the primary database will automatically
disconnect from the cascaded standby database.

GS-00792: Cannot specify %s tablespace as user default tablespace


Description: The tablespace of the specified type cannot be used as the default
tablespace (USER tablespace).
Solution: Specify a correct type.

GS-00793: Invalid archive file %s


Description: The archiving log was found incomplete during verification for the log
registration at the end of database restoration.
Solution: Delete the archiving log or overwrite it with a complete one.

GS-00794: %s id %d does not exists


Description: The object ID does not exist.
Solution: Identify the type of the object whose ID does not exist according to the
error information.

GS-00795: The tablespace specified for the user to be created was not a temporary
tablespace.
Description: The tablespace specified for the user to be created was not a
temporary tablespace.
Solution: Specify a temporary tablespace for the user.

GS-00796: Datafile number %u not exists


Description: Internal error.
Solution: Contact Huawei technical support.

GS-00798: %s thread is closed

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The working thread was shut down. This error occurs when shutdown
is concurrently performed.
Solution: After the shutdown is complete, restart the database.

GS-00799: Recyclebin object does not match, %s


Description: The table specified in the statement does not match the table in the
recycle bin.
Solution: Ensure that the object name in the statement is correct.

2.11 GS-00800 -- GS-00899

2.11.1 GS-00800 -- GS-00810


GS-00800: A %s partition %s does not exist.
Description: A partition does not exist.
Solution: Enter the correct partition name.

GS-00801: Distribute rule %s does not exist


Description: The distribution rule does not exist.
Solution: Create the distribution rule.

GS-00803: Profile id %u does not exist


Description: The profile ID does not exist.
Solution: Create the profile with this ID.

GS-00804: Invalid sequence because %s


Description: The sequence definition was invalid.
Solution: Correctly define the sequence.

GS-00805: Column %s is not empty in table %s


Description: The column failed to be modified or deleted because there was data
in it.
Solution: Delete the data and modify or delete the column again.

GS-00806: Scn too old and %s


Description: The table failed to be flashed back to the specified SCN because the
table definition was modified during the flashback.
Solution: Enter the correct SCN based on the table information in the system
catalog.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00807: The user %s has logged in, can not be dropped now
Description: The user failed to be deleted because it had logged in to the
database.
Solution: Log out the user and try again.

GS-00809: Transaction error because %s


Description: The 2PC transactions were prepared repeatedly or they were in
rollback and cannot be terminated.
Solution: Roll back or commit the prepared 2PC transactions. Terminate the
transactions after the rollback is complete.

GS-00810: Can not start database concurrently


Description: Databases were concurrently started.
Solution: Serially start the databases.

2.11.2 GS-00811 -- GS-00820


GS-00811: The constraint %s does not exist.
Description: The constraint does not exist.
Solution: Create the constraint.

GS-00812: Log file is not enough, requiring at least %u log files but only has %u
files
Description: The number of log files was less than 2 (system requirement).
Solution: Increase the number of log files.

GS-00813: RAFT: block size of logfiles should be the same


Description: The sizes of log files were different.
Solution: Change the sizes of log files to the same value.

GS-00814: row has been updated by current statement


Description: The row has been updated.
Solution: Send the update request again.

GS-00815: User %s is %s, can not drop


Description: The user to be deleted was in use.
Solution: Delete the user when it is not in use.

GS-00816: Table partition key should be subsets of local primary or unique index
Description: The partition key was not a subset of the local unique index columns.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Modify the statement for creating the partitioned index.

GS-00817: In the FOREIGN KEY constraint, the column type does not match the
type of the referenced column.
Description: In the FOREIGN KEY constraint, the column type does not match the
type of the referenced column.
Solution: Insert data or update the data with the matched type.

GS-00818: Profile has been assigned to user, can not been dropped without
cascade option.
Description: The profile had been allocated to a user and failed to be deleted
without CASCADE.
Solution: Add CASCADE to the DROP statement.

GS-00819: RAFT: failed to %s


Description: The GS-Paxos module cannot be loaded or run properly.
Solution: Proceed according to the error information in run logs.

GS-00820: btree level has exceeded limit %d.


Description: The B-tree level reached the limit and indexes increasing the level
failed to be inserted.
Solution: Combine or rebuild the indexes.

2.11.3 GS-00821 -- GS-00830


GS-00821: Can not recover to history time
Description: Failed to restore data to the specified time point because it was
earlier than the initial database time.
Solution: Specify a time point later than the initial database time.

GS-00822: When the password of an existing database user was changed, the
original password was incorrectly entered.
Description: Incorrect old password was entered to modify a database user
password.
Solution: Enter the correct old password. If you forgot the password, log in as a
database administrator to reset the password.

GS-00823: After TRUNCATE or DROP was executed on a partition of the


partitioned table having a unique index %s or constraint, the error occurred when
DML was executed on this table.
Description: After TRUNCATE or DROP was executed on one of the partitions of a
partitioned table having a unique index or constraint, the error occurred when
DML was executed on this table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Rebuild the index.

GS-00824: login using sysdba is unsupported


Description: User sysdba was not allowed to log in.
Solution: Set ENABLE_SYSDBA_LOGIN=true.

GS-00825: Invalid backup packet, len:%d


Description: The backup set was invalid.
Solution: Ensure that the backup set is valid.

GS-00826: Expected packet %d, but receive %d


Description: There was a packet error in the standby database building process.
This error is usually raised upon different versions between primary and standby
databases.
Solution: Ensure that the primary and standby databases use the same version
and run the build command on the standby database again.

GS-00827: Invalid operation when database isn't available


Description: The database was unavailable.
Solution: Run the following command to check whether the database status is
OPEN. If it is not, the database does not support this operation. If it is, try again
later.
SELECT STATUS FROM DV_DATABASE;

If this command cannot be executed, the database status is not OPEN.

GS-00828: %s %s.%s does not exist


Description: The object does not exist under the user.
Solution: Create the object.

GS-00829: Recyclebin object %s does not exist


Description: The object does not exist in the recycle bin.
Solution: Ensure that the object is in the recycle bin.

GS-00830: Index %s does not exist


Description: The index does not exist.
Solution: Create the index.

2.11.4 GS-00831 -- GS-00840


GS-00831: Can't get spin lock stat area
Description: The statistical view of the spinlock does not exist.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Contact Huawei technical support.

GS-00832: Xa transaction can't change temp table


Description: Two-phase transactions were not allowed to modify temporary tables.
Solution: Ensure there is no operation on temporary tables in two-phase
transactions.

GS-00834: The log file does not exist.


Description: The log file does not exist.
Solution: Enter the correct log file name or log file ID.

GS-00836: Parameter %s value %u does not match with database value %u


Description: Parameter values in the configuration file do not match those
specified during database installation.
Solution: Modify the configuration file to match the parameter values.

GS-00837: No file name was entered.


Description: No file name was entered.
Solution: Ensure that the statement is correct.

GS-00838: ARCHIVE_DEST_%d destination is the same as ARCHIVE_DEST_%d


destination
Description: Multiple archiving parameters were set to the same path.
Solution: Set them to different paths.

GS-00839: Flush redo file:%s, offset:%u, size:%lu failed


Description: Failed to write data into the redo log. A possible cause is that the file
system or disk was faulty.
Solution: Ensure that the OS and disk are running properly.

GS-00840: The directory %s does not exist.


Description: The directory does not exist.
Solution: Create the directory.

2.11.5 GS-00841 -- GS-00850


GS-00841: Log file is in use, can not be dropped
Description: The log file was in use and failed to be dropped or cleared.
Solution: Query the DV_LOG_FILES view. If the status of the log file is CURRENT,
run the ALTER DATABASE SWITCH LOGFILE statement to manually switch the

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

log file. If the status is ACTIVE, keep querying the view until the status changes to
INACTIVE. Then, run the corresponding statement to drop or clear the file.

GS-00842: Invalid parameter(%s)


Description: The ARCHIVE_FORMAT parameter did not contain any of %s, %S, %r,
or %R; contained repeated %s (%S), %r (%R), or %t (%T) symbols; or contained
% symbols except %s, %S, %r, %R, %t, and %T.
Solution: Change the value of ARCHIVE_FORMAT to a valid file format.

GS-00843: The table or view %s.%s does not exist.


Description: The table or view does not exist.
Solution: Create the table or view.

GS-00844: The column %s.%s does not exist.


Description: The column does not exist.
Solution: Add the column.

GS-00845: Function %s does not exist


Description: The function does not exist.
Solution: Create the function.

GS-00846: Table or view id %u.%u does not exist


Description: The table or view ID does not exist.
Solution: Create the table or view with this ID.

GS-00847: Cannot drop constraint of primary key, which is used by supplemental


log
Description: The primary key of the table with logical replication enabled failed to
be deleted.
Solution: Disable the logical replication and try again.

GS-00848: The sequence %s.%s does not exist.


Description: The sequence does not exist.
Solution: Create the sequence.

GS-00849: %s has been dropped or truncate


Description: The object has been deleted or truncated.
Solution: Rebuild the object.

GS-00850: Session holds too many table locks or lob columns

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The two-phase transaction held too many tables or LOB columns.
Solution: Reduce tables or LOB columns in the two-phase transaction.

2.11.6 GS-00851 -- GS-00860


GS-00851: Could not alloc temp extent
Description: The temporary tablespace had insufficient space.
Solution: Enable autoextend for the temporary tablespace or increase the value of
maxsize.

GS-00852: Recyclebin object %s.%s partition %s does not exist


Description: The partitioned table does not exist in the recycle bin.
Solution: Ensure that the entered name is correct.

GS-00853: Attempt to create permanent object in a temporary tablespace


Description: Non-temporary objects were created in a temporary tablespace.
Solution: Create non-temporary objects in a common tablespace.

GS_00855: Backup or restore or build failed


Description: Backup or restoration failed to be executed.
Solution: View the error cause in run logs, rectify the fault, and try again.

GS-00856: The current constraint forbids the column data type from being
modified.
Description: The data type of the current column cannot be modified because the
column has the CHECK constraint.
Solution: Delete the column constraint and try again.

GS_00857: ARCHIVE_DEST is in use, please disable it firstly


Description: When the ARCHIVE_DEST_n parameter (n=2..10) is dynamically
modified, this error will be reported if the corresponding link is still in use.
Solution: Run commands to set ARCHIVE_DEST_STATE_n to defer, and then
modify ARCHIVE_DEST_n.

GS_00858: High availability configured, database must run in archive mode


Description: There was an attempt to disable archiving in HA deployment mode.
Solution: Do not disable archiving in HA deployment mode (unlike standalone
deployment).

GS_00859: Recovery point %llu less than least recovery point %llu, open resetlogs
failed

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: Failed to open the reset log. A possible cause is that the database was
not completely stopped, the database status was abnormal, or the log file was
damaged.
Solution:
● Start the database in open mode and run the shutdown command. After
data synchronization between memory and disks is disabled, try again.
● If the log file was damaged and RECOVER DATABASE UNTIL CANCEL had
been executed, the database cannot be restored to the consistent point. In
this case, run the ALTER DATABASE OPEN IGNORE LOGS command to
forcibly start the database. However, this operation will damage data
consistency.

2.11.7 GS-00861 -- GS-00870

GS_00863: Cannot rename function index column %s


Description: The column on which a function-based index was created cannot be
renamed.
Solution: Drop the function-based index and try again.

GS_00864: The index cannot be converted to a constraint.


Description: The index cannot be converted to a constraint.
Solution: Do not use the index as a constraint.

GS_00865: the length of backup path exceed max path length


Description: The length of the specified backup path for backup or restoration
exceeded the allowed maximum.
Solution: Change the backup file path.

GS-00866: The table has no auto increment column


Description: The table had no auto-increment column, but there was a query for
the current cache value of an auto-increment column of the table (by using the
serial_lastval function).
Solution: Ensure that the target table has auto-increment columns.

GS-00867: Invalid operation when database is rolling back


Description: The operation was not allowed during database rollback.
Solution: Perform the operation after the database rollback is complete.

GS-00868: Tables and views of user %s exceeded the limit %d


Description: The numbers of tables and views created by the current user
exceeded the allowed maximum.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Delete the tables and views that are no longer used.

GS-00869: Checksum failed when read data from file %s


Description: CRC check failed due to damaged file data in the backup or
restoration process.
Solution:
● Clear the generated backup files.
● Use intact files and perform the backup or restoration operation again.

GS-00870: %s tablespace must be created first for nologging table


Description: A tablespace must be created first.
Solution: Create a tablespace as required.

2.11.8 GS-00871 -- GS-00880


GS-00871: %s tablespace cannot be used to create user object
Description: The tablespace cannot be used to create objects specified by users.
Solution: Ensure that a correct tablespace is specified.

GS-00872: The count of partition table list exceeded 500


Description: The number of lists in a single partition of a partitioned table
exceeded the upper limit 500.
Solution: Modify the table creation statement to ensure that the number of lists in
a single partition is less than or equal to 500.

GS-00873: User id %u does not exist


Description: The user corresponding to the ID does not exist.
Solution: Check whether the user has been initialized and whether there are
concurrent DROP USER operations.

GS-00874: Exceed max incremental backup number


Description: The number of consecutive level-1 differential incremental backups
exceeded the upper limit.
Solution: Perform a level-0 incremental backup and then a level-1 incremental
backup.

GS-00875: Cannot alter database timezone when database has TIMESTAMP WITH
LOCAL TIME ZONE columns
Description: Faied to modify db_timezone because the current database has
columns of the TIMESTAMP WITH LOCAL TIME ZONE type.
Solution: Delete the columns of the TIMESTAMP WITH LOCAL TIME ZONE type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00876: Space contains used data beyond requested value

Description: Valid data occupied more space than the set value during tablespace
shrinking.

Solution: Increase the value.

GS-00877: Cannot open database after %s, please %s

Description: The database cannot enter the open state after some commands are
executed in the mount state.

Solution: Proceed according to the error information.

GS-00878: Send backup record to primary failed

Description: The standby database failed to send backup set information to the
primary database.

Solution: Restore the primary/standby connection and perform backup again.

GS-00879: Wait primary record backup set failed

Description: The primary/standby connection was abnormal while the standby


database was waiting for the primary database to record the backup set result.

Solution: Restore the primary/standby connection and perform backup again.

GS-00880: Page %u-%u corrupted

Description: The data page was damaged, which led to an error in statement
execution.

Solution: Repair the page online or offline, and then access the page again.

2.11.9 GS-00881 -- GS-00890


GS-00881: File size specified is smaller than minimum required

Description: The data file size was smaller than the minimum value required by
the system.

Solution: Run the RESIZE command with parameter values increased to change
the data file size.

GS-00882: Can not exclude space %s

Description: The tablespace excluded during physical backup is related to the


system, and therefore cannot be excluded.

Solution: Modify the backup statement and try again.

GS-00883: Index %s has been dropped or truncate

Description: The index has been deleted. This error may also be reported during
the rebuilding process.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Check whether the index is actually deleted. If it is, recreate the index
and try again. If it is not, try again.

GS-00884: File size %ld bytes exceeds maximum of %ld bytes


Description: The file size specified in the RESIZE command exceeded the allowed
maximum.
Solution: Run the RESIZE command with parameter values reduced to change the
data file size.

2.12 GS-00900 -- GS-00999

2.12.1 GS-00900 -- GS-00910


GS-00900: The user-defined function did not return any value
Description: The user-defined function did not return any value.
Solution: Add a valid return value to the user-defined function.

GS-00901: The referenced composite type (only RECORD supported) was not
initialized
Description: The referenced composite type (only RECORD supported) was not
initialized.
Solution: Initialize the composite type before referencing it.

GS-00902: The declaration of CASE was not found when the CASE statement was
executed
Description: The declaration of CASE was not found when the CASE statement
was executed.
Solution: Ensure that the CASE statement is correctly declared.

GS-00904: Cursor is already opened


Description: The cursor was opened.
Solution: Do not open a cursor that has been opened, or execute the FOR LOOP
statement for an open cursor.

GS-00905: The cursor was invalid


Description: The cursor was invalid.
Solution: Ensure that the cursor has been opened and is not closed.

GS-00906: In PL/SQL, running SELECT INTO or EXECUTE IMMEDIATE INTO to


grant values to variables had no data found
Description: In PL/SQL, the SELECT INTO or EXECUTE IMMEDIATE INTO
statement was invoked to assign values to variables. No value data was found.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Ensure that the invoked SQL statements can return values.

GS-00907: The user did not log in


Description: The user was not logged in.
Solution: Log in before running the SQL statements.

GS-00908: PL/SQL internal program error(%s)


Description: PL/SQL internal error.
Solution: Proceed according to the error information.

GS-00909: Cannot COMMIT in a trigger


Description: COMMIT or a function containing COMMIT cannot be executed in
the trigger.
Solution: Modify the trigger code.

2.12.2 GS-00911 -- GS-00920


GS-00915: More than one return value of SELECT INTO, EXECUTE IMMEDIATE, or
a cursor was assigned to a common variable.
Description: More than one return value of SELECT INTO, EXECUTE IMMEDIATE,
or a cursor was assigned to a common variable.
Solution: Ensure that only one record is returned.

GS-00916: PL/SQL:syntax error (%s)


Description: PL/SQL syntax error.
Solution: Proceed according to the error information.

GS-00920: Undefined symbol


Description: The symbol was not defined.
Solution: Define the symbol.

2.12.3 GS-00921 -- GS-00930


GS-00921: The PL/SQL values (%s) were incorrect.
Description: PL/SQL numeric or value error.
Solution: Proceed according to the error information.

GS-00922: PL/SQL: illegal line


Description: The definition of the logical line was invalid.
Solution: Proceed according to the error information.

GS-00923: Inserted values were insufficient.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The number of parameters following VALUES in the INSERT


statement was greater than that of columns, the number of column values
returned by SELECT INTO of a stored procedure was greater than that of variables
for value assignment, or the number of variables used by EXECUTE IMMEDIATE
was greater than that of variables input by USING.
Solution: Ensure that the number of results is the same as the number of
variables.

GS-00924: Cursor not open


Description: The cursor was not opened when the return_result interface was
invoked.
Solution: Open the cursor before invoking result_return.

GS-00926: PL/SQL: Return types of Result Set variables or query do not match
Description: The returned result set was inconsistent with the variable set specified
by INTO.
Solution: Ensure that the number of columns in the FETCH result set is equal to
that in the variable set specified by INTO.

GS-00927: The trigger or user-defined function used by a SQL statement which is


adjusting a table %s.%s did not find the table.
Description: The trigger or user-defined function used by the SQL statement which
was adjusting a table did not find the table.
Solution: Create a trigger or adjust a user-defined function based on the adjusted
table.

GS-00928: DDL or DCL is not allowed in a trigger


Description: DDL and DCL were used in triggers.
Solution: Do not use DDL or DCL in triggers.

GS-00929: Trigger desc error


Description: The description of trigger creation was invalid. Usually, this error is
raised in the compilation phase.
Solution: Proceed according to the error information. A possible cause is that the
table was invalid.

GS-00930: The number of sys_refcursor can be returned extend the max size:%d
Description: The number of cursors returned by the return_result interface
exceeded the system-defined upper limit (2000).
Solution: Reduce the number of cursors returned by return_result.

2.12.4 GS-00931 -- GS-00940


GS-00931: There were user-defined PL/SQL exceptions not handled.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: There were user-defined PL/SQL exceptions not handled.


Solution: Add handling methods for the user-defined PL/SQL exceptions.

GS-00932: PL/SQL(GS_PLSQL.ANONYMOUS BLOCK)terminated with execute


errors
Description: There was an error in PL/SQL execution.
Solution: Proceed according to the error information.

GS-00933: Table %s.%s shrink in progress


Description: The table shrinking operation was in process.
Solution: Shrink the table repeatedly.

GS-00934: Keyword(eg.select,update,delete,if,etc) expected but encounter bracket


Description: The expected keywords (such as SELECT, UPDATE, DELETE, and IF)
encountered redundant parentheses.
Solution: Identify and delete redundant parentheses.

GS-00935: Triggers in a table cannot exceed %u


Description: The number of triggers in the table exceeded the upper limit (8).
Solution: Reduce the number of triggers.

GS-00936: Source code length %u exceed limit %u


Description: The length of PL/SQL source code exceeded the limit (1 MB).
Solution: Reduce the length of the PL/SQL source code.

GS-00937: The trigger %s.%s already exists on another table.


Description: The trigger already exists on another table.
Solution: Rename the trigger.

GS-00938: Don't support PL or trigger when _DISABLE_SOFT_PARSE is true


Description: PL stored procedures or triggers were not supported when
_DISABLE_SOFT_PARSE was set to true.
Solution: Change the value of _DISABLE_SOFT_PARSE to false.

GS-00939: Database under standby mode


Description: The PL/SQL object cannot be loaded to the standby database.
Solution: Do not use the PL/SQL object on the standby database.

GS-00940: Return_result be allowed in procedure or anonymous block, and can


not be used in dynamic sql

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: return_result can only be used in stored procedures or anonymous


blocks, instead of dynamic SQL statements.
Solution: Verify the usage scope of return_result.

2.12.5 GS-00941 -- GS-00950


GS-00941: '%s.%s'.TYPE was not a variable, column, or attribute.
Description: The object referenced by %TYPE was not a variable, column, field, or
parameter.
Solution: Reference only a variable, column, field, or parameter for %TYPE.

GS-00942: With ROWTYPE attribute, '%s' must name a table, cursor or cursor-
variable
Description: The object referenced by %ROWTYPE was not a table, cursor, or
pointer variable.
Solution: Reference only a table, cursor, or pointer variable for %ROWTYPE.

GS-00943: PL/SQL: block too complex, depth exceed the limitation %d


Description: The PL/SQL block was too complex and the block depth exceeded
128.
Solution: Simplify the PL/SQL statement blocks.

GS-00944: PL/SQL(%s.%s) terminated with compiling errors\n%s


Description: PL/SQL compiling error.
Solution: Proceed according to the error information.

GS-00945: Param only allowed in dml or anonymous block or call


Description: Bind parameters can be used only in DML statements, anonymous
blocks, and function/stored procedure calling.
Solution: Verify the usage scope of bind parameters.

GS-00946: Unknown replay type %u


Description: There was an unknown type during logical log replay.
Solution: Contact Huawei technical support. This error is seldom reported.

GS-00947: Duplicate object name %s


Description: There were duplicate object names in the statement block.
Solution: Do not declare duplicate objects in a statement block.

GS-00948: Duplicate argument %s in %s


Description: There were duplicate parameter names.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Do not use duplicate parameters in a function or stored procedure.

GS-00949: The %uth argument of %s %s


Description: There was an error in the Nth parameter of the stored procedure or
function.
Solution: Proceed according to the error information.

GS-00950: The expression %s was used as the assignment target (left operand of
the assignment statement).
Description: The expression was used as the assignment target (left operand of
the assignment statement).
Solution: Do not use an expression as an assignment target.

2.12.6 GS-00951 -- GS-00960


GS-00951: The expression %s was used as the assignment target of INTO.
Description: The expression was used as the assignment target of INTO.
Solution: Do not use an expression as the assignment target of INTO.

GS-00952: No prepare context


Description: There was no executable context.
Solution: Contact Huawei technical support.

GS-00953: %s sql-context type expected but %u found


Description: The SQL statement type was not as expected (INSERT or MERGE).
Solution: Modify the SQL statement to ensure that it meets the expectation.

GS-00954: %s expected but %s found


Description: The symbol was not as expected.
Solution: Check the statement in the row corresponding to the error, and correct
the symbol as expected.

GS-00955: Unexpected %s found


Description: There was an unexpected symbol found.
Solution: Check the statement in the row corresponding to the error, and correct
the symbol.

GS-00956: Invalid exception name %s


Description: There was an invalid exception name.
Solution: Use a valid exception name.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00957: The declaration of the variable %s was incomplete.


Description: The declaration of the variable was incomplete.
Solution: Ensure that the declaration of the variable is complete.

GS-00958: Unsupported feature


Description: The feature was not supported.
Solution: N/A

GS-00959: Exceed label max %u in one block


Description: The number of labels in the statement block exceeded the allowed
maximum 128.
Solution: Ensure that the number of labels in the statement block is no greater
than 128.

GS-00960: The OUT and IN OUT parameters were not allowed to contain a
default expression.
Description: The OUT and IN OUT parameters were not allowed to contain a
default expression.
Solution: Do not use a default expression in the OUT and IN OUT parameters.

2.12.7 GS-00961 -- GS-00970


GS-00961: The keyword PRIOR of a function or pseudo-column can be used only
in SQL statements.
Description: The keyword PRIOR of a function or pseudo-column can be used only
in SQL statements.
Solution: Use the keyword PRIOR of a function or pseudo-column only in SQL
statements.

GS-00962: Invalid plattr %s


Description: The PL/SQL attribute was invalid.
Solution: Use only the ISOPEN, FOUND, NOTFOUND, and ROWCOUNT PL/SQL
attributes.

GS-00963: could not lock pl object '%s'


Description: The PL/SQL stored procedure was being used by another session.
Solution: Wait for the session to release the stored procedure.

GS-00964: pl dictionary cache is invalidated


Description: The PL/SQL object was invalid.
Solution: Contact R&D engineers.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-00965: Expression is of wrong type

Description: The PL/SQL expression type was incorrect.

Solution: Check whether the expression in the line is correct, whether the
expression meets the constraint conditions, and whether the reference cursor with
a parameter is used to assign a value.

2.12.8 GS-00971 -- GS-00980


GS-00971: The content datatype of 'execute immediate' must be string

Description: The data type of the dynamic SQL statements executed by EXECUTE
IMMEDIATE was not string.

Solution: Change data type of the dynamic SQL statements executed by EXECUTE
IMMEDIATE to string.

GS-00972: The into clause and select need to appear together in 'execute
immediate'

Description: INTO was not used together with SELECT.

Solution: Use INTO together with SELECT.

GS-00973: There was a statement that affects transaction commission or rollback


in the user-defined function invoked by the DML operation.

Description: There was a statement that affects transaction commission or rollback


in the user-defined function invoked by the DML operation.

Solution: Do not use statements that affect transaction commission or rollback in


the user-defined function invoked by the DML operation.

GS-00974: Unexpected pl variant

Description: Variables exist in SQL statements of non-anonymous blocks, user-


defined functions, stored procedures, or triggers.

Solution: Do not use variables in such SQL statements.

GS-00975: Label type is invalid

Description: The label type was invalid.

Solution: Use a label name that is a variable type or the one enclosed with double
quotation marks.

GS-00976: The using of loop index %s is invalid

Description: The FOR loop variable was invalid.

Solution: Do not use the FOR loop variable in the range for traversing or as a
parameter for traversing cursors.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

2.13 GS-01000 -- GS-01099

2.13.1 GS-01000 -- GS-01010


GS-01000: Sys user only can login with local host
Description: The user does not have the login permission.
Solution: Grant the login permission to the user.

GS-01001: Permissions were insufficient


Description: The user was not authorized to perform the current operation.
Solution: Grant the corresponding permission to the user according to the error
information.

GS-01002: Privileges %s has not granted to %s


Description: The permission was not granted.
Solution: Proceed according to the error information.

GS-01003: Grant role in a circle


Description: The permission was granted cyclically.
Solution: Proceed according to the error information.

GS-01004: Can not revoke privilege from user %s


Description: The permission cannot be revoked from the user.
Solution: Proceed according to the error information.

GS-01005: Users cannot grant permissions to or revoke permissions from


themselves
Description: Users cannot grant permissions to or revoke permissions from
themselves.
Solution: Database administrators are recommended.

GS-01006: The user lacks create session privilege


Description: The user does not have the permission to create a session.
Solution: Grant the permission to create a session to the user.

GS-01007: Role %s has not granted to %s


Description: The role was not granted to the user.
Solution: Grant the role to the user.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 70


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-01008: The number of %s exceeds the maximum %u


Description: The number of users or roles in one authorization (GRANT or
REVOKE) operation exceeded the upper limit (63).
Solution: Reduce the number to be less than or equal to the upper limit. If the
total number exceeds this limit, you are advised to perform multiple authorization
operations.

GS-01009: The number of granted objects exceeds the maximum %u


Description: The number of objects granted to the user exceeded the upper limit
(2048 in the 64-bit system).
Solution: Reduce the number to be less than or equal to the upper limit, with the
objects inherited by roles covered.

2.14 GS-01100 -- GS-01199

2.14.1 GS-01100 -- GS-01110


GS-01100: The partition name violated the naming conventions.
Description: The partition name did not meet requirements.
Solution: Change the name according to the requirements.

GS-01101: The number of index partitions was different from that of table
partitions.
Description: The number of index partitions was different from that of table
partitions.
Solution: Locate the cause for the inconsistency.

GS-01102: Invalid partition %s type %s


Description: The partition type did not meet requirements.
Solution: Ensure that the type of the new partition is consistent with that of the
partition key.

GS-01103: Invalid partition key, %s


Description: The partition key was invalid.
Solution: Use a valid partition key.

GS-01104: The LOB column was used as the partition key.


Description: The LOB column was used as the partition key.
Solution: Do not use the LOB column as a partition key.

GS-01105: The column used as the partition key was modified.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 71


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The column used as the partition key was modified.


Solution: Do not modify the column used as the partition key.

GS-01106: can not drop partitioning column


Description: The column used as the partition key was deleted.
Solution: Do not delete the column used as the partition key.

GS-01107: There were duplicate partition names.


Description: The partition name already exists.
Solution: Use a unique name.

GS-01108: The number of partitions exceeds the maximum %lu


Description: The number of partitions exceeded the allowed maximum.
Solution: Locate the cause for the number out of range.

GS-01109: Cannot drop the only partition of a partitioned table


Description: The only partition of the partitioned table was deleted.
Solution: Do not delete the only partition of a partitioned table.

GS-01110: The operation %s was not allowed.


Description: There was an adding operation in the interval partition.
Solution: Do not perform the operation.

2.14.2 GS-01111 -- GS-01120


GS_01111: The local index of the partitioned table was treated as a common
index.
Description: The local index of a partitioned table was processed as a common
index.
Solution: Use the MODIFY PARTITION Partition name statement.

GS_01112: The common index was treated as a partitioned index.


Description: The common index was processed as a partitioned index.
Solution: Do not use the MODIFY PARTITION Partition name statement.

GS_01113: Updating the partition key would cause changes to partitions, while
cross-partition update was not supported.
Description: Updating the partition key would cause changes to partitions, while
cross-partition update was not supported.
Solution: Note the update on upper boundary values of the partition key. Do not
perform cross-partition update.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 72


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS_01114: The %u%s partition key already exists in partition %s


Description: The partition key already exists.
Solution: Delete the original partition key or create another column as the
partition key.

2.15 GS-01200 -- GS-01299

2.15.1 GS-01200 -- GS-01210


GS-01200: Error for modifying XA transaction state
Description: Failed to commit the XA (two-phase) transaction.
Solution: Contact Huawei technical support.

GS-01201: Xa need timestamp to synchronize datanode logic clock


Description: Failed to implement distributed SQL execution.
Solution: Check whether the node status is normal. If it is not, try again after it
becomes normal.

GS-01202: Node count error


Description: The number of required DN nodes was incorrect during SQL
execution.
Solution: Check the configuration of the current node.

GS-01203: Invalid node id %s


Description: The required DN node cannot be found during SQL execution.
Solution: Check whether the routing rule, DN node status, and network
configuration are normal. If they are not, try again after they become normal.

GS-01204: This node(LSNR_ADDR=%s,LSNR_PORT=%d) is not configured in


DATA_NODES$
Description: The required DN node was not configured during SQL execution.
Solution: Check the configuration of the current node.

GS-01210: Wrong connect: %s


Description: Failed to establish a connection between nodes.
Solution: Contact Huawei technical support.

2.15.2 GS-01211 -- GS-01220


GS-01211: Wrong connect cause %s reaches upper limit: current num is %u, max
num is %u, node id is %u

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 73


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The number of statements or connections reached the upper limit,


and new connections cannot be established between nodes.
Solution:
● When the number of statements reached the upper limit, contact Huawei
technical support.
● When the number of connections reached the upper limit, increase the
maximum number of connections specified by
MAX_CONNECTION_POOL_SIZE.

GS-01212: Failed to get timestamp from gts (node id=%u), error number = %05d
Description: Failed to obtain the timestamp when establishing a connection
between nodes.
Solution: Contact Huawei technical support.

GS-01213: Node id = %u, error number = GS-%05d, error message = '%s'


Description: Failed to establish a connection between nodes.
Solution: Contact Huawei technical support.

GS-01214: Some slot not released


Description: The connection between nodes was not closed.
Solution: Contact Huawei technical support.

GS-01215: There is no valid local timestamp


Description: Failed to obtain the timestamp.
Solution: Contact Huawei technical support.

GS-01220: Username can't be %s.


Description: The entered username cannot be configured in the CREATE NODE/
ALTER NODE syntax.
Solution: Enter a valid username.

2.15.3 GS-01221 -- GS-01230


GS-01221: The instance is starting, and this operation is not allowed
Description: There was an attempt to create, delete, or modify a node when the
database was being started.
Solution: Perform the operations after the database is started.

GS-01222: Check constraint violated


Description: The operation violated the constraint condition.
Solution: Proceed according to the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 74


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-01223: Integrity constraint violated - parent key (child record) not found
Description: The operation violated the integrity constraint condition.
Solution: Proceed according to the error information.

GS-01224: Failed to drop supplement log


Description: Failed to delete the supplemental log.
Solution: Contact Huawei technical support.

GS-01225: Flashback table partition to timestamp(scn or before drop) not


supported
Description: There was an attempt to flash back the partitioned table to a specific
timestamp or before DROP.
Solution: Contact Huawei technical support.

2.16 GS-01300 -- GS-01399

2.16.1 GS-01300 -- GS-01310


GS-01300: There can be only one auto column and it must be defined as a key
Description: Only one auto-increment column can be defined, and the column
must have the primary key or unique constraint.
Solution:
● Check the number of defined auto-increment columns.
● Check whether the column has the primary key or unique constraint.

GS-01301: %s.%s is already exists


Description: There were duplicate table definitions.
Solution: Check whether the table already exists.

GS-01302: Unknown lob type when %s


Description: There was an unknown LOB type. Currently, only the following three
values are supported:
● 0 (LOB_FROM_KERNEL)
● 1 (LOB_FROM_VMPOOL)
● 2 (LOB_FROM_NORMAL)
Solution: Check the input LOB type.

GS-01303: Convert %s type to %s type failed


Description: Failed to convert the type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 75


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Proceed according to the error information.

GS-01304: Data type '%s' is not supported


Description: The data type was not supported.
Solution: Proceed according to the error information.

GS-01305: Unknown plan type when %s


Description: There was an unknown execution plan type.
Solution: Proceed according to the error information.

GS-01306: Invalid datafile number %d (min=%d, max=%d)


Description: The number of data files was invalid.
Solution: Proceed according to the error information.

GS-01307: %s is stored procedure %s


Description: Failed to execute user-defined stored procedures.
Solution: Proceed according to the error information.

GS-01308: %lu node_id expected to be filled but only %u filled


Description: The number of columns was too small.
Solution: Proceed according to the error information.

GS-01309: Datatype %s is not allowed for distribute column


Description: The data type was not supported for the distribution column.
Solution: Check the data type of the distribution column.

GS-01310: Comment object %s.%s is not table or view type


Description: The comment object was not a table or view.
Solution: Check the comment object.

2.16.2 GS-01311 -- GS-01320


GS-01311: %s must be %s
Description: The data must be of a fixed data type.
Solution: Proceed according to the error information.

GS-01312: %s expected
Description: The syntax was incorrect, with the keyword missing.
Solution: Proceed according to the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 76


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-01313: Invalid attribute name %s


Description: The attribute name was invalid.
Solution: Proceed according to the error information.

GS-01315: Compare type is error


Description: There was an error in the comparison type.
Solution: Proceed according to the error information.

GS-01316: Unexpected %s
Description: The syntax was incorrect, with an incorrect keyword.
Solution: Proceed according to the error information.

GS-01317: Unexpected aggregation '%s'


Description: The syntax was incorrect, invoking the aggregation function by
mistake.
Solution: Proceed according to the error information.

GS-01318: Unknown datatype %d


Description: The data type was unknown.
Solution: Proceed according to the error information.

GS-01319: Decimal/number overflow


Description: The value was out of range.
Solution: Proceed according to the error information.

GS-01320: Undefined operator: %s %s %s


Description: There was an unknown operation.
Solution: Proceed according to the error information.

2.16.3 GS-01321 -- GS-01330


GS-01321: Unknown aggr operation
Description: Unknown aggregation function operation.
Solution: Proceed according to the error information.

GS-01322: Calculate %s failed


Description: Failed to calculate the expression.
Solution: Proceed according to the error information.

GS-01323: %s not supported %s

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 77


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Description: The function was not supported.


Solution: Proceed according to the error information.

GS-01324: %s failed
Description: Failed to invoke the function.
Solution: Proceed according to the error information.

GS-01325: Data type %s mismatched with column '%s'


Description: The data type did not match the column definition.
Solution: Check the data type and ensure that the data type matches the column
definition.

GS-01326: %s cast to column '%s' failed


Description: Failed to convert the default value of the column to the column value.
Solution: Proceed according to the error information.

GS-01327: Unsupported %s type=%d


Description: The operation type was not supported.
Solution: Proceed according to the error information.

GS-01328: Too many aggregation


Description: There were too many parameters.
Solution: Proceed according to the error information.

GS-01329: The function ID %d was invalid


Description: The function was invalid.
Solution: Proceed according to the error information.

GS-01330: argument value is out of range


Description: The parameter value was out of range.
Solution: Proceed according to the error information.

2.16.4 GS-01331 -- GS-01340


GS-01331: The package ID %d was invalid
Description: The package was invalid.
Solution: Proceed according to the error information.

GS-01332: Cannot create a user with the name same as sys user
Description: A user with the same name as the system user cannot be created.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 78


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Change the name of the user to be created.

GS-01333: The SQL syntax %s was incorrect with no operation specified


Description: The SQL syntax was incorrect, with no operation specified.
Solution: Check the SQL statement.

GS-01334: Only accept commit prepared or rollback prepared


Description: Currently, only COMMIT PREPARED and ROLLBACK PREPARED are
supported.
Solution: Proceed according to the error information.

GS-01335: Has no more lob data to read


Description: There was no LOB data for reading.
Solution: Proceed according to the error information.

GS-01336: Node 'node_name = %s' already exists


Description: The DN already exists.
Solution: Proceed according to the error information.

GS-01337: Node 'node_name = %s' does not exist


Description: The DN does not exist.
Solution: Proceed according to the error information.

GS-01338: coordinator node don't allow %s


Description: The operation was not allowed on CNs.
Solution: Proceed according to the error information.

GS-01339: Cannot %s distribute column \"%s\" %s


Description: The operation was not allowed on distribution columns.
Solution: Proceed according to the error information.

GS-01340: Select .. for update syntax error: %s


Description: The syntax was incorrect.
Solution: Proceed according to the error information.

2.16.5 GS-01341 -- GS-01350


GS-01341: No sort items in remote scan plan
Description: There was no sort item at the remote end.
Solution: Proceed according to the error information.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 79


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

GS-01342: Winsort funcs in column list can't exceed %u


Description: The number of columns in the window function exceeded the allowed
maximum.
Solution: Adjust the number of columns in the window function.

GS-01343: Invalid protocol invoke, %s


Description: The protocol was invalid.
Solution: Proceed according to the error information.

GS-01344: Statement id is invalid: %u


Description: The statement ID was invalid.
Solution: Proceed according to the error information.

GS-01345: DML statements were not allowed in query statements


Description: DML operations cannot be executed in query statements.
Solution: Generally, this error is raised in user-defined functions. Adjust the user-
defined functions according to the error information.

GS-01346: The column \"%s\" length exceeded the maximum,(actual: %u,


maximum: %u)
Description: The column length exceeded the allowed maximum.
Solution: Proceed according to the error information.

GS-01347: Function %s is not indexable


Description: Indexing was not supported by the current function.
Solution: Select the function that supports indexing to create an index.

GS-01348: The number of reserved sql cursors can not decrease


Description: The value of _RESERVED_SQL_CURSORS can only be increased,
instead of decreased.
Solution: Set this parameter to a value greater than the current value.

GS-01349: Querying views containing DISTINCT, GROUP BY, or ROWNUM for


ROWID was not allowed
Description: Querying views containing DISTINCT, GROUP BY, or ROWNUM for
ROWID was not allowed.
Solution: Modify the SQL statement according to the error information.

GS-01350: The input was not of the NUMBER type


Description: The input was not of the NUMBER type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 80


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Input data of the NUMBER type.

2.16.6 GS-01351 -- GS-01360


GS-01352: SQL mapping only supports DML and DQL statements
Description: SQL mapping is supported only between DML statements.
Solution: Ensure that both the source and target SQL statements for mapping are
DML statements.

GS-01353: SQL mapping does not exist


Description: The SQL mapping to be deleted does not exist.
Solution: Ensure that the SQL mapping to be deleted exists.

GS-01354: Table function multi-table associations are not supported


Description: The table function does not support multi-table joins.
Solution: Ensure that the table function does not contain multi-table joins.

GS-01356: The number of statements exceeds the maximum: %u


Description: The number of cursors opened in the current session exceeded the
allowed maximum.
Solution: Close unused cursors to ensure that the number of opened cursors does
not exceed the allowed maximum.

2.16.7 GS-01361 -- GS-01370


GS-01367: %s, errno %d
Description: Code conversion failed. errno is the error code of the Linux system
conversion failure.
Solution: Check whether the error information in the run log contains the "Set
locale failed" string.
● If it does, the language coding of the current system environment is not
supported. You can change the current language coding to en_US.UTF-8 or
zh_CN.UTF-8, and then restart the database.
● If it does not, check whether the code stream entered on the client is correct
according to the error information.

2.17 GS-01400 -- GS-01499

2.17.1 GS-01400 -- GS-01410


GS-01400: The interval of jobs was not a future time
Description: The interval of jobs was not a future time.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 81


GaussDB 100
Error Code Reference (Standalone) 2 Error Code Reference

Solution: Adjust the interval expression for jobs.

GS-01401: "Job unsupport %s"


Description: The job does not support this feature.
Solution: Adjust the job usage.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 82


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

3 Interface Mapping (GaussDB 100 Native


Interface Names vs. Mainstream Database
Interface Names)

3.1 Data Dictionary Tables


Table 3-1 Name mapping of data dictionary tables (GaussDB 100 native interface
names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 83


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 84


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

3.2 DBA Views


Table 3-2 Name mapping of DBA views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 85


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 86


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 87


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

3.3 User Views


Table 3-3 Name mapping of user views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_ARGUMENTS ALL_ARGUMENTS

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 88


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 89


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

3.4 Dynamic Performance Views


Table 3-4 Name mapping of dynamic performance views (GaussDB 100 native
interface names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 90


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 91


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 92


GaussDB 100 3 Interface Mapping (GaussDB 100 Native Interface
Error Code Reference (Standalone) Names vs. Mainstream Database Interface Names)

3.5 Configuration Parameters


Table 3-5 Name mapping of configuration parameters (GaussDB 100 native
interface names vs. mainstream database interface names)
GaussDB 100 Native Interface Name Mainstream Database Interface
Name

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 93


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

4 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are


a set of features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a


thread database. The thread is used to archive database logs to a
specified path.

atomicity One of the ACID features of database transactions. Atomicity


means that a transaction is composed of an indivisible unit of
work. All operations performed in a transaction must either be
committed or uncommitted. If an error occurs during transaction
execution, the transaction will be rolled back to the state when it
was not committed.

backup A backup, or the process of backing up, refers to the copying and
archiving of computer data. Backup data can be used for
restoration in case of data loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false
logical condition. A bit is physically represented by an element
such as high or low voltage at one point in a circuit, or a small
spot on a disk that is magnetized in one way or the other. A single
bit conveys little information a human would consider meaningful.
A group of eight bits, however, makes up a byte, which can be
used to represent many types of information, such as a letter of
the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at


a certain time. GaussDB 100 periodically stores the data of
committed transactions and data of uncommitted transactions to
disks. The data and redo logs can be used for database restoration
if a database restarts or breaks down.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 94


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands
are entered through keyboards or similar devices and are compiled
and executed by applications. The results are displayed in text or
graphic forms on the terminal interface.

coding Coding is representing data and information using code so that it


can be processed and analyzed by a computer. Characters, digits,
and other objects can be converted into digital code, or
information and data can be converted into the required electrical
pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or


more columns.

compressio Data compression, source coding, or bit-rate reduction involves


n encoding information that uses fewer bits than the original
representation. Compression can be either lossy or lossless.
Lossless compression reduces bits by identifying and eliminating
statistical redundancy. No information is lost in lossless
compression. Lossy compression reduces bits by identifying and
removing unnecessary or less important information. The process
of reducing the size of a data file is commonly referred as data
compression, although its formal name is source coding (coding
done at the source of data, before it is stored or transmitted).

concurrenc A DBMS service that ensures data integrity when multiple


y control transactions are concurrently executed in a multi-user
environment. In a multi-threaded GaussDB 100 environment,
concurrency control ensures that database operations are safe and
all database transactions remain consistent at any given time.

consistency One of the ACID features of database transactions. Consistency is


a database state. In such a state, integrity constraints on tables
are not damaged.

convergenc Downlink to uplink bandwidth ratio of a switch. A high


e ratio convergence ratio indicates a highly converged traffic environment
and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or
system dump records the state of working memory of the
program at that point in time. The states of key programs are
often dumped at the same time. For example, information about
processor registers, including program metrics, stack pointers,
memory management, other processors, and OS flags are often
dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 95


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

core file A file that is created when memory overwriting, assertion failures,
or access to invalid memory occurs in a process, causing it to fail.
This file is then used for further analysis.
A core file stores memory dump data, and supports binary mode
and specified ports. The name of a core file consists of the word
"core" and the OS process ID.
The core file is available regardless of the type of platform.

crash A crash (or system crash) is when a computer or program, such as


a software application or an operating system, stops functioning
properly. Often the program will exit after encountering this type
of error. The program experiencing the crash can hang or freeze
until a crash reporting service reports the crash and any details
relating to it. If the program is a critical part of the operating
system and crashes, the entire system may be paralyzed, often
resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes
constants, variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored
procedure information, user rights, user statistics, database
process information, database increase statistics, and database
performance statistics.

data flow An operator that exchanges data among query fragments. By their
operator input/output relationships, data flows can be categorized into
Gather flows, Broadcast flows, and Redistribution flows. Gather
combines multiple query fragments of data into one. Broadcast
forwards the data of one query fragment to multiple query
fragments. Redistribution reorganizes the data of multiple query
fragments and then redistributes the reorganized data to multiple
query fragments.

data A division of a logical database or its constituent elements into


partitionin multiple parts (partitions) whose data does not overlap based on
g ranges or lists. The target storage location is mapped based on the
range of the values in the column that is specified in the tuple.

database A collection of data that is stored together and can be accessed,


managed, and updated. Data in a view in a database can be
classified into the following types: numeral, full text, digit, and
image.

database A binary file that stores user data and the internal data of a
file database system.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 96


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

database GaussDB 100 provides a highly reliable HA solution. Every logical


HA node in GaussDB 100 is identified as a primary or standby node.
At the same time, only one GaussDB 100 node is identified as the
primary server. In GaussDB 100, standby nodes first perform full
synchronization from the primary node and later incremental
synchronization. When the HA system is running, the primary
node can receive data read and write requests in GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database
instances to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database


maintenance operations.

DBLINK An object of the path from one database to another. A remote


database object can be queried with DBLINK.

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a
database. It is a collection of programs that allows users to access,
manage, and query data in a database. A DBMS can be classified
as memory DBMS or disk DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent
device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data
during an event response, whereas a trace file contains
continuously generated diagnostic data.

durability One of the ACID features of database transactions. Transactions


that have been committed will permanently survive and not be
rolled back.

encryption A function hiding information content during data transmission to


prevent unauthorized use of the information.

environme An environment variable defines a part of the environment in


nt variable which a process runs. For example, it can define a main directory,
command search path, terminal that is in use, or the current time
zone.

error A technique that automatically detects and corrects errors in


correction software and data streams to improve system stability and
reliability.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 97


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

F–J

failover Automatic switchover from a faulty node to its standby node.


Reversely, automatic switchback from the standby node to the
primary node is called failback.

failover Automatic substitution of a functionally equivalent system


component for a failed one. The system component can be a
processor, server, network, or database.

free space A mechanism for managing free space in a table. This mechanism
manageme enables a database system to record free space in each table and
nt establish an easy-to-find data structure, accelerating operations
(such as INSERT) performed on the free space.

freeze An operation automatically performed by the AutoVacuum


Worker process when transaction IDs are exhausted. GaussDB 100
records transaction IDs in the row heading. When a transaction
reads a row, the transaction ID in the row heading and the actual
transaction ID are compared to determine whether this row is
explicit. Transaction IDs are integers containing no symbols. If
exhausted, transaction IDs are re-calculated outside of the integer
range, causing the explicit rows to become implicit. To prevent
such a problem, the freeze operation marks a transaction ID as a
special ID. Rows marked with these special transaction IDs are
explicit to all transactions.

full A data synchronization mechanism specified in the GaussDB 100


synchroniz HA solution. Used to synchronize all data from the primary server
ation to a standby server.

GNU The GNU Project was publicly announced on September 27, 1983
by Richard Stallman, aiming at building an OS composed wholly
of free software. GNU is a recursive acronym for "GNU's Not
Unix!". Stallman announced that GNU should be pronounced as
Guh-NOO. Technically, GNU is similar to Unix in design, a widely
used commercial OS. However, GNU is free software and contains
no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for
each node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration


of service interruptions caused by routine maintenance (planned)
or sudden system breakdowns (unplanned), improving system and
application usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on


behalf of all or some of the system users.

incrementa Incremental backup stores all file changes since the last valid
l backup backup.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 98


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

index An ordered data structure in a DBMS. An index accelerates data


query and update in database tables.

isolation One of the ACID features of database transactions. Isolation


means that the operations inside a transaction and data used are
isolated from other concurrent transactions. Concurrent
transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java


APIs of SQL statements. It provides unified access to multiple
relational databases, consisting of a set of classes and interfaces
written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements.
When deleting a tuple, GaussDB 100 only marks the tuples that
are to be cleared. The VACUUM thread will then periodically clear
these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

metadata Data that provides information about other data. Metadata


describes the source, size, format, or other characteristics of data.
In database columns, metadata explains the content of a data
warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that


allows a tuple to have multiple versions, on which different query
operations can be performed. One basic advantage is that read
and write operations do not conflict.

network Network backup provides a comprehensive, flexible data


backup protection solution for Microsoft Windows, UNIX, and Linux
platforms. Network backup can back up, archive, and restore files,
folders, directories, volumes, and partitions on a computer.

OS An operating system (OS) manages applications or application


programs on a computer.

P–T

page Smallest memory unit for row storage in the relational object
structure in GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature


of GaussDB 100. Data can be restored to a specified point in time
if backup data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB
server 100 HA system and works with all standby servers. At any time,
only one node in the HA system is identified as the primary server.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 99


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

process An instance of a computer program that is being executed. A


process may be made up of one or more threads. A process
cannot use a thread occupied by another process.

QPS Query Per Second (QPS) means the number of queries that a
server can respond to per second.

query Each query job can be split into one or more query fragments.
fragment Each query fragment consists of one or more query operators and
can independently run on a node. Query fragments exchange data
through data flow operators.

query An iterator or a query tree node, which is a basic unit for the
operator execution of a query. Execution of a query can be split into one or
more query operators. Common query operators include scan, join,
and aggregation.

record In a relational database, a record corresponds to data in each row


of a table.

redo log A log that contains information required for performing an


operation again in a database. If a database is faulty, redo logs
can be used to restore the database to its original state.

relational A database created using the relational model. It processes data


database using methods of set algebra.

resource A collection of resources that can be accessed to obtain


library information.

RPO Recovery point objective (RPO) refers to the latest status that a
database system and the data can be restored to after a disaster,
and it is usually represented by time.

RTO Recovery time objective (RTO) refers to the duration between the
database system failure caused by a disaster and its restoration to
proper running.

schema A database object set that includes the logical structure, such as
tables, views, sequences, stored procedures, synonyms, clusters,
and database links.

segment A segment in a database indicates a part containing one or more


extents. An extent is the smallest range of a database and consists
of data blocks. One or more segments comprise a tablespace.

session A job created by a database system for connection purposes when


an application attempts to connect to the database. Sessions are
managed by the session manager. They execute initial jobs to
perform all user operations.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 100


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

SGA System global area (SGA). It is the cache management framework


of GaussDB 100. It contains most cache management components
of the storage engine and SQL engine, including PlanCache,
DataBuffer, DcCache, RedoBuffer, CkptBuffer, LockBuffer,
TransactionBuffer, and ReplicationBuffer.

shared A shared pool is created for repeatedly executed SQL statements


pool to save memory. It contains the explain trees and execution plans
of given SQL statements.

SQL Structured Query Language (SQL) is a standard database query


language. It consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used
by Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides
three basic security services, all of which use the public key
technology. SSL ensures the security of service communication
through a network by establishing a secure connection between a
client and a server and then sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup


server of the primary server. If the primary server is behaving abnormally,
the standby server is promoted to primary, ensuring uninterrupted
data services.

statistics Information that is automatically collected by databases, including


table-level information (number of tuples and number of pages)
and column-level information (column value range distribution
histograms). Statistics in databases are used to estimate the costs
of query plans to find the plan with the lowest cost.

stop word In computing, stop words are words which are filtered out before
or after processing of natural language data (text), saving storage
space and improving search efficiency.

stored A group of SQL statements compiled into a single execution plan


procedure and stored in a large database system. Users can specify a name
and parameters (if any) for a stored procedure to execute the
procedure.

system A table storing meta information about a database. The meta


catalog information includes user tables, indexes, columns, functions, and
data types in a database.

table A set of columns and rows. Each column is referred to as a field.


Values in each field represent a data type. For example, if a table
contains three fields of person names, cities, and states, it has
three columns: Name, City, and State. In every row in the table,
the Name column contains a name, the City column contains a
city, and the State column contains a state.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 101


GaussDB 100
Error Code Reference (Standalone) 4 Glossary

Term Description

tablespace A tablespace is a logical storage structure that contains tables,


indexes, and objects. A tablespace provides an abstract layer
between physical data and logical data, and provides storage
space for all database objects. When you create an object, you can
specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and


are used for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a


database. A transaction consists of a limited database operation
sequence, and must have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information


library. A WSR is generated by comparing statistics collected by
two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively


enter queries, issue them to GaussDB 100, and view the query
results. Queries can also be entered from files. zsql supports many
meta commands and shell-like commands, allowing you to
conveniently compile scripts and automate jobs.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 102


GaussDB 100
V300R001C00

Feature Description (Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Feature Description (Standalone) Contents

Contents

1 About This Document.................................................................................................................. 1


2 Architecture.................................................................................................................................... 2
2.1 x86 Servers..................................................................................................................................................................... 2
2.2 ARM Servers.................................................................................................................................................................. 2

3 Supported Operating Systems.................................................................................................... 4


3.1 Linux Servers..................................................................................................................................................................4

4 Functions Oriented to Application Development.................................................................. 5


4.1 Standard Development Interfaces...................................................................................................................................5
4.2 Transactions.................................................................................................................................................................... 5
4.3 Tables..............................................................................................................................................................................7
4.4 Temporary Tables........................................................................................................................................................... 7
4.5 Standard Data Types....................................................................................................................................................... 8
4.6 Indexes............................................................................................................................................................................9
4.7 Views............................................................................................................................................................................ 10
4.8 Synonyms..................................................................................................................................................................... 10
4.9 Sequences......................................................................................................................................................................11
4.10 Standard SQL............................................................................................................................................................. 12
4.11 Bind Variables.............................................................................................................................................................12
4.12 Stored Procedures....................................................................................................................................................... 13
4.13 Functions.................................................................................................................................................................... 13
4.14 Triggers.......................................................................................................................................................................14
4.15 Advanced Packages.................................................................................................................................................... 14

5 Basic Data Functions................................................................................................................... 16


5.1 Wait Events................................................................................................................................................................... 16
5.2 Metadata Views............................................................................................................................................................ 16
5.3 Dynamic Performance Views....................................................................................................................................... 18
5.4 Tablespace Management...............................................................................................................................................19
5.5 Performance Analysis Report....................................................................................................................................... 20
5.6 IPv6...............................................................................................................................................................................21
5.7 Text Data Import and Export........................................................................................................................................ 21
5.8 Logical Import and Export........................................................................................................................................... 22

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Feature Description (Standalone) Contents

6 Performance.................................................................................................................................. 23
6.1 Execution Plans............................................................................................................................................................ 23
6.2 Execution Plan Cache................................................................................................................................................... 23
6.3 Partitions....................................................................................................................................................................... 24
6.4 Hints..............................................................................................................................................................................25
6.5 CBO.............................................................................................................................................................................. 26

7 High Availability.........................................................................................................................28
7.1 Physical Standby Databases......................................................................................................................................... 28
7.2 Flashback...................................................................................................................................................................... 29
7.3 Backup and Restoration................................................................................................................................................30
7.4 Logical Replication.......................................................................................................................................................31

8 Database Security........................................................................................................................ 32
8.1 Permission Management...............................................................................................................................................32
8.2 Database Audit............................................................................................................................................................. 33
8.3 Network Communication Security............................................................................................................................... 34
8.4 User Profiles................................................................................................................................................................. 35

9 Glossary......................................................................................................................................... 36

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Feature Description (Standalone) 1 About This Document

1 About This Document

Overview
This document describes features of GaussDB 100 V300R001C00 developed by Huawei
Technologies Co., Ltd.

Intended Audience
This document is intended for:
l Pre-sales engineers
l System architecture engineers

Change History
Version Change Description Date

03 This issue is the third official release. 2019-06-06

02 This issue is the second official release. 2019-04-05

01 This issue is the first official release. 2018-10-30

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Feature Description (Standalone) 2 Architecture

2 Architecture

2.1 x86 Servers


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports x86 servers, effectively reducing hardware costs. The system fully
utilizes resources on each node to provide large capacity, high performance, and high
scalability.

Description
GaussDB 100 can be deployed on x86 servers, enabling powerful scale-out for databases. Log
synchronization is used to ensure data consistency between primary and standby nodes. One
primary node can have multiple standby nodes, and each standby node can work in either
synchronous or asynchronous mode. Service applications can access the standby nodes for
read-only operations, enhancing system read performance.

2.2 ARM Servers


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports ARM servers, effectively reducing hardware costs. The system fully
utilizes resources on each node to provide large capacity, high performance, and high
scalability.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Feature Description (Standalone) 2 Architecture

Description
GaussDB 100 can be deployed on ARM servers. The databases can fully utilize the multi-core
capability of ARM servers, achieving high performance, high scalability, and large capacity in
the ARM ecosystem.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Feature Description (Standalone) 3 Supported Operating Systems

3 Supported Operating Systems

3.1 Linux Servers


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports Linux operating systems.

Description
GaussDB 100 supports the following Linux operating systems and versions:
The x86 architecture supports the following operating systems:
l Red Hat Enterprise Linux Server release 7.4 x86_64
l SUSE Linux Enterprise Server 11.3 (SUSE 11 for short), x86_64
l SUSE Linux Enterprise Server 12.4 (SUSE 12 for short), x86_64
l EulerOS Server V2.0SP3 x86_64
l EulerOS Server V2.0SP5 x86_64
The ARM architecture supports the following operating systems:
EulerOS Server V2.0SP8 ARM_64

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

4 Functions Oriented to Application


Development

4.1 Standard Development Interfaces


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports standard development interfaces, achieving quick interconnection with
development and application software.

Description
GaussDB 100 supports the following development interfaces:
1. C API
2. JDBC 4.0
3. Python 2.7
4. ODBC 3.0
5. GO
GaussDB 100 also supports CLI-based connection to clients.

4.2 Transactions
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports transactions, ensuring integrity and consistency in data processing.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

Description
A transaction is a logical unit of work that contains one or more SQL statements, which are
either all committed or all not committed. Transaction processing ensures that data is not
permanently modified until all operations in a transactional unit are completed successfully.
By combining a set of related operations into a unit that succeeds completely or fails
completely, the system can ensure correct service logic with no loss. All transactions must
have the basic ACID properties. ACID is an acronym for the following:
l Atomicity

Operations contained in a transaction are considered as a logical unit, and they either succeed
completely or fail completely.

l Consistency

When a transaction is complete, data must be consistent and the data integrity constraint must
not be damaged. If there is an error during transaction execution, the transaction will be rolled
back to the state before execution, as if it has never been executed.

l Isolation

A transaction allows multiple users to concurrently access the same data without damaging
the correctness and integrity of the data. In addition, changes in parallel transactions must be
independent.

l Durability

Changes made by committed transactions are permanently stored in databases and will not be
rolled back.

GaussDB 100 also supports the following transaction isolation levels:

l READ COMMITTED (default): At this level, a transaction can access only committed
data.
Generally, the SELECT statement accesses a database snapshot taken when the query
begins. It can also access the data updates in its session, regardless of whether they have
been committed. In this case, different database snapshots may be available to two
consecutive SELECT statements in the same transaction because other transactions may
be committed while the first SELECT statement is executed.
At the READ COMMITTED level, the execution of each statement begins with a new
snapshot, which contains all the transactions that have been committed by the execution
time. Therefore, during a transaction, a statement can access the results of other
committed transactions. Pay attention to whether a single statement always accesses
absolutely consistent snapshots in a database.
Transaction isolation at this level meets the requirements of many applications, and is
fast and easy to use. However, applications performing complicated queries and updates
may require a view that is more consistent than this level can provide.
l SERIALIZABLE: At this level, a transaction can see only changes committed at the
beginning of the transaction (not a query) and changes made by the transaction itself. A
serializable transaction operates in an environment that makes it appear as if no other
users were modifying data in the database. Serializable isolation is suitable for
environments where there are short transactions that update only a few rows, the chance
that two concurrent transactions will modify the same row is relatively low, or relatively
long-running transactions are primarily read only.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

In serializable isolation, any row read by a transaction is assured to be consistent during


repeated reads, and any query is guaranteed to return the same results in the transaction
duration. Changes made by other transactions are not visible to the transaction query
regardless of how long the transaction has been running. Serializable transactions do not
experience dirty reads, fuzzy reads, or phantom reads.
l CURRENT COMMITTED
Data read by an SQL statement is the latest committed data at the read time. All read
data is no longer of the same snapshot.

In GaussDB 100 transaction management, you can start, commit, and roll back transactions,
prepare for two-phase commit, set a transaction isolation level, and create a savepoint for a
transaction.

For details about how to use transaction control, see GaussDB 100 V300R001C00 R&D
Documentation (Standalone).

4.3 Tables
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports typical heap tables for data storage and query. Data will be
automatically persisted after being committed.

Description
l A heap table is a default data table storage structure. In a heap table, data rows are
managed based on random access. Space from a segment header block to the high water
mark (HWM) is extensively managed in a random manner. By default, when a data row
needs to be inserted into a table, the system checks for idle space below the HWM to
accommodate the new row. If there is a vacant position, the row will be placed. Note that
this position should be as small as possible and it may be an overwrite position where a
data row has been deleted. If no proper position is found below the HWM of a heap table
segment, the system will raise the heap table HWM. In heap tables, row storage has no
order. This characteristic is called random access. For details about how to use ordinary
database heap tables, see GaussDB 100 V300R001C00 R&D Documentation.
l GaussDB 100 supports table partitioning. A partitioned table is a logical table that is
divided into several physical partitions for storage based on a specific plan. Data is
stored on these physical partitions, instead of the logical partitioned table. Currently,
GaussDB 100 supports range partitioning, hash partitioning, list partitioning, and interval
partitioning.

4.4 Temporary Tables


Version
Introduced in GaussDB 100 V300R001C00

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

Introduction
GaussDB 100 allows users to customize temporary tables.

Description
A temporary table is like an ordinary table, allowing users to add, delete, modify, and query
data. It can be used to store and process intermediate results and will be automatically deleted
after use.

GaussDB 100 supports both local temporary tables and global temporary tables.

l A local temporary table (or its table structure) exists for the duration of a specific
session, and will be cleared and deleted when the session ends.
l A global temporary table (or its table structure) is globally visible and persistent. It will
be automatically cleared but not deleted when the session ends. A global temporary table
can be a transaction- or session-level temporary table.
– ON COMMIT PRESERVE ROWS: Defines a session-level temporary table.
When a session ends, the temporary table data is deleted but the table structure
remains.
– ON COMMIT DELETE ROWS: Defines a transaction-level temporary table.
When a transaction ends, the temporary table data is deleted but the table structure
remains.

4.5 Standard Data Types


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports standard data types.

Description
Currently, GaussDB 100 supports the following data types:

Numeric: BINARY_INTEGER, INTEGER, BINARY_BIGINT, BIGINT,


BINARY_DOUBLE, DOUBLE, FLOAT, REAL, and DECIMAL/NUMBER, and integer
unsigned

Character: CHAR, NCHAR, CLOB, VARCHAR, VARCHAR2, NVARCHAR, and


NVARCHAR2

Binary: BINARY, VARBINARY, IMAGE, RAW, and BLOB

Date: DATETIME/DATE, TIMESTAMP, TIMESTAMP(n) WITH TIME ZONE, and


TIMESTAMP(n) WITH LOCAL TIME ZONE

Boolean: BOOLEAN

Time interval: INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

4.6 Indexes
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows indexes to be created on tables. Users can quickly search for data based
on indexes, improving performance.

Description
An index is a structure that sorts the values of one or more columns in a database table. Use
select * from table where col=1000000 as an example. If there is no index, the entire table
will be traversed until the row whose col is 1000000 is found. After an index is created (on
the col column), the index will be queried. Indexes have been optimized by algorithms,
greatly reducing the number of searches.
From the perspective of data search implementation, indexes are another type of data objects.
Indexes contain various records that can point to related data records. Specifically, each index
includes the data of all indexed columns for a specified data row, and is stored at the physical
location corresponding to the data row. In this way, an index is equivalent to a collection of all
data directory items, and users can quickly locate a data row that meets the condition
specified by the data in an indexed column.
l An index can be created on multiple columns.
GaussDB 100 allows indexes to be created on one or more columns. Users can combine
multiple column values to narrow the search scope. A composite index contains a
maximum of 16 columns.
l Unique indexes can be created.
GaussDB 100 allows for unique indexes. In this case, the system checks whether new
values are unique in the indexed column. Attempts to insert or update data which would
result in duplicate values in the indexed column will generate an error. Currently, only B-
tree indexes can be created as unique indexes.
l Partitioned indexes can be created.
GaussDB 100 allows local partitioned indexes to be created on partitioned tables. Such
an index is equipartitioned with the table and the index partitioning is automatically
maintained when partitions are dropped or truncated. This ensures that the index always
remains equipartitioned with the table. The number of local index partitions must be the
same as that of partitions in a table.
l Function-based indexes can be created.
GaussDB 100 allows for function-based indexes, which are created based on the
calculation results of columns in a table. Such indexes improve query performance
without modifying the logic of applications. If there is no function-based index, any
query that executes a function on a column cannot use the index of this column. A
database uses a function-based index only when the function is included in a query. In
GaussDB 100, you can create function-based indexes for the UPPER and TO_CHAR
functions. The function parameter must be one column, and the index cannot be
converted to a constraint.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

l Indexes can be created online.


GaussDB 100 supports online index creation. Generally, exclusive locks are added to a
table for index creation (DDL) on this table, preventing concurrent UPDATE,
DELETE, and INSERT operations and decreasing the throughput of system catalog
transactions. Therefore, when online index creation and rebuilding are used, share locks
are added to the table (exclusive locks are temporarily used only at the beginning and
end of the creation or rebuilding) to allow for concurrent UPDATE, DELETE, and
INSERT operations without affecting the proper running of online services.
For details about the syntax for index creation, maintenance, and deletion, see GaussDB
100 V300R001C00 R&D Documentation (Standalone).

4.7 Views
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows views to be created and deleted.

Description
A view is a logical representation of one or more tables. In essence, a view is defined by a
query. Like an actual table, a view also contains a series of columns with names and rows.
However, views are not stored as data value sets in databases. A view derives its row and
column data from the table referenced by the query of the view, and the data is dynamically
generated when the view is referenced.
GaussDB 100 supports the following two types of views:
l User-defined views: Users can create and delete views as needed.
l Preset system views: The system can initialize and preset views, and the owner is user
SYS. Such views include metadata and dynamic performance views, which can be used
to query the metadata and dynamic performance data of the system.

4.8 Synonyms
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to customize synonyms.

Description
A synonym is an alias of a data object, indicating a mapping relationship with the data object.
It is often used to simplify object access and improve the security of object access. A

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

synonym requires no storage other than its definition in the data dictionary. Therefore, using
synonyms saves a large amount of data space and enables users to seamlessly interact with
each other across databases.

GaussDB 100 supports the following two types of synonyms:

l Private synonyms: If the keyword public is not added during synonym creation, the
synonym will be a private one. Other users can access the private synonym only after
being authorized. A private synonym can have the same name as another public
synonym.
l Public synonyms: If the keyword public is added during synonym creation, the synonym
will be a public one. Public synonyms are created by user public. Other users can access
the synonyms without authorization. However, while accessing the objects to which the
synonyms point, the users still need to pass permission verification.

4.9 Sequences
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports sequences, allowing users to generate unique integers.

Description
GaussDB 100 supports sequences. Users can run the CREATE SEQUENCE statement to
create a sequence, also a database object, from which multiple users can generate unique
integers. Sequences can also be used to generate primary keys automatically.

When sequence numbers are generated, the sequence increments automatically, which is
irrelevant to transaction commission or rollback. When two users increment the same
sequence at the same time, the sequence numbers obtained by a user may have a gap with
those obtained by the other because the two users generate different numbers. A user can
never obtain the sequence numbers generated by another user. After a user generates a
sequence number, the user can continue to access the corresponding value regardless of
whether the sequence is incremented by another user.

Sequence numbers are independent of tables, and therefore the same sequence can be used for
one or more tables. A single sequence number may be skipped because it is generated and
used in the transaction when the final rollback was performed. In addition, a single user may
not realize that other users are obtaining values from the same sequence.

After a sequence is created, it can be referenced in SQL statements with the NEXTVAL and
CURRVAL pseudocolumns. Each new sequence number is generated when the pseudocolumn
NEXTVAL is used, while the current sequence number can be repeatedly returned when the
pseudocolumn CURRVAL is used.

For details about how to use sequences, see GaussDB 100 V300R001C00 R&D
Documentation (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

4.10 Standard SQL


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports the SQL:2003 standard, enabling quick application migration and
rollout.

Description
SQL standards are international and updated periodically. SQL standards have defined core
features and optional features. Most databases cannot completely conform to the SQL
standards. SQL features are built by database vendors to maintain customers and push up
application migration costs. New SQL features are increasingly different among vendors.
Currently, there is no authoritative SQL standard test.

GaussDB 100 supports standard SQL statements. Specifically, it supports most of the core
features in SQL:2003, as well as some optional features, implementing basic SQL syntax in
application development.

In addition, GaussDB 100 offers compatibility with most mainstream SQL syntax to quickly
migrate existing applications and reduce the workload of application modification.

For details about the SQL syntax list, see the SQL syntax part in GaussDB 100 V300R001C00
R&D Documentation (Standalone).

4.11 Bind Variables


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to bind variables to SQL statements, simplifying the parse process
and increasing the execution efficiency.

Description
Variable binding refers to the use of variables instead of constants in the conditions of SQL
statements. Assume there are two SQL statements in the SQL pool.
select * from table where col=1;
select * from table where col=2;

For GaussDB 100, the two statements are completely different. Specifically, GaussDB 100
matches each character in the texts of the two SQL statements. Although there is only one
character different, the SQL statements in the SQL pool cannot be matched. Therefore, the

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

database considers them to be two completely different statements. Any SQL statements that
cannot be completely matched need to be hard parsed.
Change the above SQL statements to select * from table where col=:var1, and assign a
value to the variable var1 for query. The first statement will be hard parsed, and the second
statement will match the first one and only need to be soft parsed. In this case, the existing
information in the SQL pool is reused. If a statement has been repeatedly executed for many
times, using bind variables will bring great benefits. If an application does not use or not fully
use bind variables, there will be a high probability of serious performance problems.
Bind variables help reduce hard parses, which in turn reduces parse-caused CPU contention
and resource overhead as well as the memory usage of SQL pools. However, histograms
cannot be used in this situation and SQL optimization becomes difficult.

4.12 Stored Procedures


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to customize stored procedures.

Description
A stored procedure is a set of SQL statements that are used to complete specific functions in a
large database system. It is stored inside a database. A stored procedure is compiled only for
the first time, and does not need to be compiled in later invoking. Users can execute a stored
procedure by specifying its name and providing parameters (if any). A stored procedure is an
important object in a database.
Stored procedures provide benefits by:
l Allowing customers to modularize program design and encapsulate SQL statement sets,
easy to invoke.
l Caching the compilation results of stored procedures, accelerating SQL statement set
execution.
l Allowing system administrators to restrict the permission for executing a specific stored
procedure, controlling access to the corresponding type of data. This prevents access
from unauthorized users and ensures data security.

4.13 Functions
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to customize functions and provides a large number of preset
functions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

Description
A function is a set of SQL statements that are used to complete specific functions in a large
database system. It is stored inside a database. A function is compiled only for the first time,
and does not need to be compiled in later invoking. Users can execute a function by
specifying its name and providing parameters (if any). Functions have return values. Users
can use functions to achieve specific targets and obtain required data.
GaussDB 100 allows users to customize functions. Users can use SQL syntax to create and
delete functions.
GaussDB 100 also provides a large number of preset functions, including numeric calculation,
character processing, time and date, interval, type conversion, and aggregation functions.
For details about the syntax for function creation, deletion, and usage as well as the preset
functions, see GaussDB 100 V300R001C00 R&D Documentation (Standalone).

4.14 Triggers
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to customize triggers.

Description
A database trigger is a compiled storage unit, written in PL/SQL or Java. It is automatically
invoked by a database.
GaussDB 100 can monitor the SELECT, INSERT, UPDATE, DELETE, and MERGE
operations on data tables. It executes corresponding trigger actions when these operations are
performed. GaussDB 100 can fire a trigger at the table or row level before or after table data
access/change. For details about trigger usage and restrictions, see GaussDB 100
V300R001C00 R&D Documentation (Standalone).

4.15 Advanced Packages


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 provides preset system packages.

Description
A package is a schema object that groups logically related PL/SQL types, variables, constants,
subprograms, cursors, and exceptions. A package is compiled and stored inside a database

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Feature Description (Standalone) 4 Functions Oriented to Application Development

where many applications can share its content. A package always has a specification, which
declares the public items that can be referenced from outside the package. If the public items
include cursors or subprograms, then the package must also have a body. The body must
define queries for public cursors and code for public subprograms. The body can also declare
and define private items that cannot be referenced from outside the package but are necessary
for the internal work of the package. Finally, the body can have an initialization part whose
statements initialize variables and do other one-time setup steps, and an exception-handling
part. You can change the body without changing the specification or the references to the
public items.
GaussDB 100 also provides preset system packages. For details about the content and usage
of system packages, see GaussDB 100 V300R001C00 R&D Documentation (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

5 Basic Data Functions

5.1 Wait Events


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to collect statistics on wait events to determine system running
status.

Description
A wait event occurs when a session waits for system behavior. It may be caused by many
factors, such as slow read/write on disks, architecture-caused locks, and various system
resource contentions. A wait event can be at the system or session level. A session-level wait
event affects the activity of a single user in a database. A system-level wait event affects the
entire database system. Users can locate system performance problems by analyzing wait
events.

GaussDB 100 provides seven classes of wait events (25 events in total): Idle, Concurrency,
Other, Commit, Application, User I/O, and Configuration.

You can query the DV_SESSION_EVENTS and DV_SESSION_WAITS views for statistics
on session-level wait events, and the DV_SYS_EVENTS view for statistics on system-level
wait events.

5.2 Metadata Views


Version
Introduced in GaussDB 100 V300R001C00

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

Introduction
GaussDB 100 provides preset metadata views, from which users can query system metadata.

Description
An important part of GaussDB 100 is its metadata, which is a set of views providing
management metadata about the database. Metadata includes the following information:

l Definition of each schema object in a database, including default values and integrity
constraints of columns
l Amount of space allocated for and used by a schema object
l Name of a database user, permissions and roles granted to the user, as well as audit
information related to the user

Metadata is the core part of GaussDB 100 management. Assume that a database performs the
following operations:

l Accessing the data dictionary to find information about users, schema objects, and
storage structures
l Modifying the data dictionary each time DDL statements are issued

Since GaussDB 100 stores metadata in the system and opens metadata views to users, the
users can run SQL statements to query the views. For example, users can run SELECT to
determine their permissions, which tables exist in their schemas, which columns are in these
tables, and whether indexes are built on these columns.

Metadata consists of base tables and views.

l Base table

A base table stores metadata information about a database. The database system writes and
reads such tables, and users should not access the tables directly because the tables have been
standardized and most data is stored in hidden format.

l View

A view uses JOIN and WHERE clauses to decode base table data into useful information,
such as user names or table names, which simplifies information. A view contains the names
and descriptions of all objects in the data dictionary. Some views can be accessed by all
database users, while some others are only for administrators.

Generally, data dictionary views are grouped. In many cases, there are three views containing
similar information and distinguished by their prefixes.

Table 5-1 Data dictionary views


Prefix Access Permission Content Remarks

ADM_ Database All objects Such a view


administrators contains additional
columns with some
useful information
for the
administrators.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

Prefix Access Permission Content Remarks

DB_ All users All objects Such a view


accessible to the contains information
users about all objects that
users can access.

MY_ All users All objects Such a view


accessible to a user contains information
about all objects that
the current user can
access. By default,
the syntax for
creating such a view
incorporates owner
verification to
automatically match
the user who
executes the SQL
statement.

For details about metadata views, see GaussDB 100 V300R001C00 R&D Documentation
(Standalone).

5.3 Dynamic Performance Views


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 provides dynamic performance views, from which users can query statistics
about a current database. The views are continuously updated while a database is open and in
use, providing system status in real time.

Dynamic performance views usually start with DV, and also can be called DV views.

Description
Dynamic performance data is owned by user SYS and stored in dynamic performance tables,
allowing users to query views for performance data. Dynamic performance views provide the
status information of databases and are updated in real time.

A dynamic performance view provides the following information:

l Memory status information


l Log and archive information
l Data storage information

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

l View and lock information


l Database configuration and parameter information
l SQL running statistics
l Session information
l Wait event statistics

For details about dynamic performance views, see GaussDB 100 V300R001C00 R&D
Documentation (Standalone).

5.4 Tablespace Management


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports data management based on tablespaces. Users can create and delete
tablespaces to flexibly allocate and use storage resources.

Description
A GaussDB 100 database tablespace consists of one or more data files. Database objects are
logically stored in tablespaces and physically stored in data files.

When a GaussDB 100 database is created, the following tablespaces are automatically
created: SYSTEM, TEMP, UNDO, USERS, TEMP2, and TEMP2_UNDO.

l SYSTEM tablespace
It stores GaussDB 100 metadata. To ensure stable database running, you are advised not
to store user data in the SYSTEM tablespace. By default, the SYSTEM tablespace is not
automatically extended. If it is full, manually add data files or extend the tablespace.
l TEMP tablespace
It is automatically maintained by GaussDB 100. When SQL statements apply for disk
space, the GaussDB 100 database allocates temporary segments from the TEMP
tablespace. The TEMP tablespace is also used for index creation, data sorting that
cannot be executed in the memory, intermediate result sets of SQL statements, and
temporary tables.
l UNDO tablespace
It stores undo data. When a DML operation (INSERT, UPDATE, or DELETE) is
performed, old data before the operation is written into the UNDO tablespace. Such a
tablespace is mainly used for transaction rollback, database instance restoration, read
consistency, and flashback query.
l USERS tablespace
It is the default tablespace. When a user is created with no tablespace specified, all
information about the user is stored in the USER tablespace.
l TEMP2
It stores NOLOGGING table data, and is automatically maintained by GaussDB 100.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

l TEMP2_UNDO
It stores the undo data of NOLOGGING tables.
Users can create and specify tablespaces to store user data, including tables, table partitions,
and indexes.
Database administrators can use tablespaces to control the layout of disks where a database is
installed. This has the following advantages:
l Separate user data from system data, reducing I/O contention.
l Separate the data of an application from that of another application, preventing multiple
applications from being affected when a tablespace is offline.
l Store data files of different tablespaces on different disk drives, reducing I/O contention.
l Make a single tablespace offline while retaining other tablespaces online. Tablespace
usage can be improved by reserving a tablespace for a specific type of database use, such
as frequent update activities, read-only activities, or temporary segment storage.
Some operating systems limit the number of files that can be opened at the same time. This
limit may affect the number of tablespaces that can be online concurrently. Plan tablespaces
effectively to avoid breaking this limit. Only create enough tablespaces to meet your
requirements, and create them using as few files as possible. If you have to increase the size
of a tablespace, add one or two big data files, or create a data file with autoextend enabled,
instead of creating many small data files.
For details about how to use tablespaces, see GaussDB 100 V300R001C00 User Guide
(Standalone).

5.5 Performance Analysis Report


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports Workload Statistics Report (WSR), which can be used to generate
performance analysis reports.

Description
A snapshot is a collection of system statistics at a specified time point. Users can use wsr
$create_snapshot to collect complete statistics of the entire database system at a specified
time point.
WSR is a built-in system tool of GaussDB 100. It generates a report by comparing the
statistics collected in two snapshots. The report data is used to analyze database performance
in a specified period to further analyze system performance problems.
WSR can generate a report only when there are two or more snapshots. The IDs of start and
end snapshots must be specified, and there must be no system restart between the two
snapshots. Specifically, the system compares statistics collected in two snapshots to obtain the
changes within the time period. Then, a report is generated.
A WSR report contains the following:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

l Load profile: CPU, I/O, and redo resource usage information, and the total numbers of
SQL and transaction executions
l SQL statistics: SQL status, and top 10 SQL statements sorted by execution time, CPU
time, user I/O wait, physical read, logical read, execution times, and parse times

5.6 IPv6
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports service access addresses in IPv6 format and allows logs to be
transmitted between primary and standby databases on an IPv6 network.

Description
GaussDB 100 supports service access addresses in IPv6 format. Users can set an IPv6 address
of a server as the listening address. They can also access a database from an IPv6 address of a
server.
GaussDB 100 allows primary and standby databases to communicate from IPv6 addresses and
transmit logs on an IPv6 network.
GaussDB 100 allows a service network and a primary/standby replication network to have
different network segments. IPv4 and IPv6 can be selected as needed.

5.7 Text Data Import and Export


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows data to be imported and exported. Users can export data from a database
to the text format and import text data to the database.

Description
To facilitate data transfer, GaussDB 100 supports text data import and export. This feature is
commonly used in data migration, data backup, and service text data import scenarios. Users
can run DUMP on zsql to export data to the text format and LOAD to import text data.
In GaussDB 100, data export can be performed on both servers and clients. Specifically, SQL
statements are assembled on a client before being sent to the server, which then receives
specific DDL and DML statements. GaussDB 100 allows users to export a single table, that
is, all data in the table is exported as text data. Users can also customize statements for export,
for example, add SELECT to DUMP. GaussDB 100 allows users to set the specifications for
exporting data to text files, including the size of a target text file (splitting supported, creating

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Feature Description (Standalone) 5 Basic Data Functions

another file when the size is exceeded), symbols contained in columns, delimiters of columns,
and the number of rows for a record.
GaussDB 100 also supports plain-text data import. Specifically, SQL statements are
assembled on a client before being sent to the server, which then receives specific DDL and
DML statements. A target file for text data to be imported to must match the source file in the
number of columns and the data types of columns. For data import, users can also set the data
format of text files, including symbols contained in columns, delimiters of columns, and the
number of rows for a record.
For details about how to import and export data, see GaussDB 100 V300R001C00 User Guide
(Standalone).

5.8 Logical Import and Export


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports logical data import and export. Users can logically export data from
and import data to a database. Source and target files for import and export are all of the SQL
type.

Description
To facilitate data transfer, GaussDB 100 supports logical data import and export. This feature
is commonly used in data migration, data backup, and service text data import scenarios. The
format of files for logical import and export is SQL text. Users can run EXP on zsql to
logically export data and IMP to logically import data.
In GaussDB 100, logical data export can be performed on both servers and clients.
Specifically, SQL statements are assembled on a client before being sent to the server, which
then receives specific DDL and DML statements.
In GaussDB 100, you can logically export a single table or a user-specified table, and also
multiple tables of multiple users at a time. If EXP is used to export data, users can set
parameters such as parallel, insert_batch, and commit_batch to accelerate export.
GaussDB 100 allows users to import the files that they logically export data to. Users can also
choose full import or incremental import. By specifying the REMAP_SCHEMA and
REMAP_TABLESPACE parameters to determine data mappings for logical import, users
can prevent import conflicts due to duplicate objects.
For details about how to logically import and export data, see GaussDB 100 V300R001C00
User Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Feature Description (Standalone) 6 Performance

6 Performance

6.1 Execution Plans


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows SQL statement execution plans to be viewed to analyze the performance
of SQL statements.

Description
An SQL statement execution plan is a combination of steps used by a database to execute an
SQL statement. It is the core of SQL performance analysis and optimization. An execution
plan includes the following information:

l Sequence of tables referenced by the SQL statement


l Method of accessing each table in the SQL statement
l Methods of joining and operating tables in the SQL statement
l Operations, such as condition filtering (WHERE), sorting (ORDER), and aggregating
(COUNT)

Users can run EXPLAIN PLAN to determine whether an optimizer has chosen a specific
execution plan, such as a nested loop join. The users can also examine the decision of the
optimizer, for example, the reason why the optimizer chose a nested loop join rather than a
hash join.

6.2 Execution Plan Cache


Version
Introduced in GaussDB 100 V300R001C00

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Feature Description (Standalone) 6 Performance

Introduction
GaussDB 100 allows SQL execution plans to be cached in a shared pool. In this case, SQL
statements do not need to be repeatedly parsed each time they are executed, increasing SQL
execution efficiency.

Description
In GaussDB 100, when an SQL statement is executed for the first time, the SQL syntax is
hard parsed and the generated execution plan is cached in an independent shared pool. When
the statement is executed later, the system automatically matches the SQL texts and directly
invokes the execution plan cached in the SQL pool, skipping the hard parse operation and
reducing the SQL execution time.
GaussDB 100 determines that historical execution information and an execution plan in an
SQL pool can be reused only when all the characters in two SQL texts are the same. Even if
the SQL texts have a little bit difference, GaussDB 100 will determine the two as different
statements. Then, it will separately hard parse the SQL statement and store the generated
execution plan in the shared pool. If two SQL texts differ from each other only in the values
in the WHERE clause, bind variables are recommended. For details about how to use bind
variables, see GaussDB 100 V300R001C00 R&D Documentation.
The size of memory occupied by an SQL pool is affected by the memory parameter
SHARED_POOL_SIZE. The size can be dynamically adjusted. You can query the
DV_GMA view for the SGA structure and shared pool size, query the DV_SQLS view for
cached SQL statements, and query the DV_OBJECT_CACHE view for the data dictionary
cache.
For details about shared pools, see GaussDB 100 V300R001C00 User Guide (Standalone).

6.3 Partitions
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports the syntax for creating partitioned tables and data partitions as well as
for optimizing execution plans.

Description
A continuous increase in the amount of data in a table slows down the data query speed and
deteriorates the application performance. In this case, you need to partition the table. After a
table is partitioned, it is still a complete table logically, but its data is physically stored in
multiple tablespaces (physical files). In this case, the system does not need to scan the entire
table in each data query.
GaussDB 100 table partitioning provides many benefits for applications, such as improving
manageability, performance, and availability. Partitioning can greatly improve the
performance of some query and maintenance operations. In addition, partitioning can greatly
simplify common management jobs. It is a key feature for systems with an ultra-large amount
of data and ultra-high availability.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Feature Description (Standalone) 6 Performance

Partitioning enables a tables or index to be divided into smaller pieces, which called
partitions. Each partition has its own name and storage characteristics. From the perspective
of a database administrator, a partitioned object has multiple pieces that can be managed
either collectively or individually, allowing for great flexibility for the administrator to
manage partitioned objects. However, from the perspective of an application, a partitioned
table is identical to the non-partitioned table; and no modifications are needed when a
partitioned table is accessed using DML statements.

GaussDB 100 supports range partitioning, list partitioning, hash partitioning, and interval
partitioning. A partition key supports integer, character, and time data types. With partition
pruning, querying a partitioned table is over 10 times faster than querying a non-partitioned
table.

l In range partitioning, a table is partitioned based on ranges defined by values in one or


more columns, with no overlap between the ranges of values assigned to different
partitions. Each range has a dedicated partition for data storage.
l In list partitioning, a table is partitioned based on a specific value in a specified column.
l In hash partitioning, a table is partitioned based on partition key values. If a hashed
record can be mapped to a partition, it will be inserted into the partition; if it cannot, an
error message will be reported. Hash partitioning is the most commonly used partitioning
policy.
l Interval partitioning is an extension of range partitioning. In interval partitioning, a table
is partitioned based on data intervals. If a record can be mapped to a partition, it will be
inserted into the partition; if it cannot, a partition will be automatically created and the
record will be inserted to the new partition.

For details about how to use partitions in GaussDB 100, see GaussDB 100 V300R001C00
R&D Documentation (Standalone).

6.4 Hints
Version
Introduced in GaussDB 100 V300R001C00

Introduction
In standalone deployment, GaussDB 100 allows hints to be set at the SQL statement level.

Description
Hints are special SQL syntax. They can be used to manually intervene SQL execution plan
selection. Adding a hint to an SQL statement instructs the SQL optimizer to select a specific
execution plan. Hints are usually used when users know the optimal SQL execution plan, or
used to stabilize the SQL execution plan and optimize performance.

In GaussDB 100, you can optimize execution plans at both the hint and SQL levels.

GaussDB 100 supports the following three types of hints:

l access_method_hint
Hint for type selection during data access.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Feature Description (Standalone) 6 Performance

There are seven hints, which are FULL, INDEX, NO_INDEX, INDEX_ASC,
INDEX_DESC, INDEX_FFS, and NO_INDEX_FFS.
l join_order_hint
Hint for join order selection.
There are two hints, which are ORDERED and LEADING.
l join_method_hint
Hint for join method selection.
There are three hints, which are USE_NL, USE_MERGE, and USE_HASH.

For details about hints and the usage, see GaussDB 100 V300R001C00 R&D Documentation
(Standalone) and GaussDB 100 V300R001C00 Performance Tuning Guide.

6.5 CBO
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports the cost-based optimizer (CBO).

Description
Query optimization is a process of choosing the most efficient method for executing an SQL
statement.

SQL is a non-procedural language. Therefore, an optimizer can freely merge, reorganize, and
progress in any order. In addition, a database can optimize each SQL statement based on the
statistics collected on accessed data. Then, the optimizer can examine multiple access
methods (such as full table scan or index scan), different join methods (such as nested loop
join and hash join), different join orders, and possible conversions to determine the optimal
execution plan for an SQL statement.

Given a specific query and an environment, an optimizer will assign a relative numerical cost
to each step of an execution plan, and calculate the values together to generate an overall cost
estimation result for the plan. After calculating the costs of alternative execution plans, the
optimizer will select an execution plan with the minimal cost estimate. For this reason, an
optimizer is sometimes referred to as the CBO, which is often compared with the rule-based
optimizer (RBO).

GaussDB 100-supported CBO selects an optimal execution plan based on the costs of SQL
statements. It has three key components:

l Query converter
For some statements, the query converter rewrites an original SQL statement into an
equivalent SQL statement with a lower cost and determines whether the conversion is a
worthy operation.
l Cost estimator
It is used to determine the overall cost of a given execution plan.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Feature Description (Standalone) 6 Performance

l Execution plan generator


It explores various SQL execution plans by trying different access paths, join methods,
and join orders.
The CBO estimates execution plan costs based on the following statistics:
l Table statistics, including the total number of rows, total number of data blocks, and
average row length
l Column statistics, including the histogram, number of distinct values, number of null
values, and column density
l Index statistics, including the indexed columns, index size, and index level

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Feature Description (Standalone) 7 High Availability

7 High Availability

7.1 Physical Standby Databases


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows a primary database to send redo logs to a standby database so that the
standby database can apply the logs to implement quick data synchronization and DR between
the two databases.

Description
In traditional database DR, redo logs are transferred between primary and standby databases
for data synchronization. The logs are generated when data is modified on a primary database,
and they can be sent to a standby database in either synchronous or asynchronous mode. After
the standby database receives and applies the redo logs, its data becomes consistent with that
in the primary database.
GaussDB 100 supports the following three modes for standby databases:
l Maximum protection: It ensures no data loss.
In this mode, transaction logs are not only written into local log files, but also into the
log files of standby databases. Transactions are committed in a primary database only
when data is available in at least one standby database. If standby databases are
unavailable due to a fault (for example, network disconnection), services on the primary
database will be blocked to prevent data loss. Only LGWR SYNC is supported for
replication from a primary database to standby databases.
l Maximum availability: It provides the highest-level data protection without
compromising the availability of a primary database.
Maximum availability is similar to maximum protection. It also requires that local
transaction logs be written into the log files of at least one standby database before
commission. There is also a difference between the two. In maximum availability mode,
if standby databases are unavailable due to a fault, services in the primary database will

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Feature Description (Standalone) 7 High Availability

not be blocked and the database will automatically switch to the maximum performance
mode. After the standby databases recover, the primary database will automatically
switch back to the maximum availability mode. Although data loss is avoided, data
consistency cannot be completely ensured. Only LGWR SYNC is supported for
replication from a primary database to standby databases.
l Maximum performance: It provides the highest-level data protection without
compromising the performance of a primary database. It is the default mode.
This mode allows transactions to be committed at any time. The transaction logs of a
primary database must be written into at least one secondary database, and this write can
be asynchronous. In ideal network conditions, this mode provides data protection similar
to the maximum availability mode and has slight impact on primary database
performance. Both LGWR SYNC and ASYNC are supported for replication from a
primary database to standby databases.

GaussDB 100 supports a maximum of nine standby databases. Users can determine the
quantity and protection mode of standby databases based on their HA requirements.

For details about how to create, maintain, and rebuild a standby database, see GaussDB 100
V300R001C00 User Guide (Standalone).

7.2 Flashback
Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 allows users to flash back data after misoperations, without stopping databases.

Description
Flashback is a fast data recovery solution. You can selectively query or cancel misoperations.
FLASHBACK TABLE restores a table to an earlier state in the event of human or
application errors. The time in the past to which the table can be flashed back is dependent on
the amount of undo data in the system. In addition, GaussDB 100 cannot restore a table to an
earlier state across any DDL operations that change the structure of the table.

In GaussDB 100, flashback can be implemented by:

l Restoring table data to a specified time point or SCN point. This mode is suitable when
users have incorrectly adjusted the data.
l Restoring tables that have been deleted by mistake from recycle bins. This mode is
suitable when users have incorrectly executed DROP TABLE.

For details about the FLASHBACK syntax and usage, see GaussDB 100 V300R001C00
R&D Documentation (Standalone).

For details about the scenarios and steps of FLASHBACK, see GaussDB 100 V300R001C00
User Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Feature Description (Standalone) 7 High Availability

7.3 Backup and Restoration


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports full data backup and restoration. In the case of extreme data loss, data
can be restored, improving system reliability.

Description
l Physical backup
GaussDB 100 supports physical database backup. Before backing up a database, ensure that
the database is in archiving mode. The backup operation can be performed only on primary
databases in the OPEN state.
l Full backup
To improve service reliability, the system supports full backup of database data (excluding
alarm data) in either automatic or manual mode. Full backup is performed at a specified time
point, covering the full data of a database at that point. When a database is abnormal, users
can restore it by using the full backup file. GaussDB 100 supports full backup of an entire
database, and allows users to run the BACKUP DATABASE statement on zsql to fully back
up a database.
l Incremental backup
To accelerate data backup, the system supports incremental backup of database data
(excluding alarm data) in either automatic or manual mode. Incremental backup covers
differential data between a specified time point and the last full/incremental backup time
point, reducing the amount of data to be backed up. When a database is abnormal, users can
restore it by using the full backup and incremental backup files. GaussDB 100 supports
incremental backup of an entire database, and allows users to run the BACKUP DATABASE
INCREMENTAL statement on zsql to incrementally back up a database. Level 0 indicates
the baseline backup. Level 0 backup must be performed before level 1 backup is performed
for the first time. Level 1 backup is based on the previous level 1 or level 0 backup.
l Backup compression
To reduce the space occupied by backup data, GaussDB 100 provides the backup compression
function. Database data can be compressed in stream data mode, generating compressed
backup files. Users can run the COMPRESSED BACKUPSET command to compress data
during backup.
l Database restoration
GaussDB 100 supports database restoration. Before restoring a database, ensure that there is
an available database backup file, the server has sufficient disk space, the database is in the
NOMOUNT state, and data files in the data directory have been deleted. A path specified
during restoration must be the same as that specified during backup.
GaussDB 100 supports database restoration in either synchronous or asynchronous mode. In
synchronous mode, the system returns execution results to the client only after restoration is

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Feature Description (Standalone) 7 High Availability

complete. In asynchronous mode, the database instance returns execution results to the client
after receiving the RESTORE DATABASE statement. To check whether the restoration is
successful, observe the STATUS column in the DV_BACKUP_PROCESSES view.
GaussDB 100 also supports Point-In-Time Recovery (PITR). Users can run the UNTIL
TIME statement to restore a database to a specified time point.
For details about how to restore a database, see GaussDB 100 V300R001C00 User Guide
(Standalone).

7.4 Logical Replication


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports data synchronization based on logical logs.

Description
GaussDB 100 logical replication parses table column changes recorded in redo logs to
reversely generate and replay SQL statements, and then executes the SQL statements on a
target database, replicating GaussDB 100 data changes to the target database in real time.
Logical replication is more flexible than physical replication, which has strong dependency on
the physical formats of logs. Logical replication can implement GaussDB 100 cross-version
replication and GaussDB 100 replication to other heterogeneous databases (such as Oracle
databases). It also provides customization support when the structures of source and target
database tables are inconsistent. Logical replication can be used for incremental data backup
between primary and standby databases, data synchronization between different service
systems, and online data migration during system upgrade.
GaussDB 100 can logically replicate data to Oracle and GaussDB 100 databases. For primary/
standby replication, you need to install, configure, and start the logical backup service on both
the primary and standby hosts. In this case, only the primary host has logical replication in
working mode.
For details about how to create and maintain logical replication, see GaussDB 100
V300R001C00 User Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Feature Description (Standalone) 8 Database Security

8 Database Security

8.1 Permission Management


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 provides two levels of user permissions. It allows for object access permission
settings by user type, achieving refined access control.

Description
Database users are used to connect databases, access database objects, and run SQL
statements. Only an existing database user can be used to connect databases. Therefore,
database administrators need to plan a database user for anyone who wants to connect a
database. GaussDB 100 supports user permission management. You can configure the
operation and access permissions for database objects and the use permissions for database
functions for different users.
GaussDB 100 provides two levels of user permissions.
l System permissions
System permissions are about system operations, for example, changing system
parameters. By default, only system administrators have the system permissions. After a
database is installed, the system administrator can grant system permissions to other
users. For security purposes, grant system permissions only to reliable users.
l Object permissions
Object permissions are about database object operations, such as INSERT, DELETE,
UPDATE, and SELECT permissions. The management of object permissions is
flexible. The system administrator can either grant all permissions or partial permissions
(such as SELECT and UPDATE) for certain database objects to users.
A database may be accessed by multiple users. To facilitate management, you can group
permissions and grant them to roles. Each permission group corresponds to a role. A role can

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Feature Description (Standalone) 8 Database Security

be granted to a user based on the user permission level. In this way, the user has all the
permissions of this role, that is, the required permissions are granted in batches to the user.
GaussDB 100 supports role-based permission management. Users can define roles. A role is a
set of multiple user permissions. If a role is granted to a user, the user will have all
permissions of this role.
Users can query system-provided views for information about system permissions, permission
allocation, and role permissions.
For details about permission management and precautions, see GaussDB 100 V300R001C00
Security Maintenance Guide (Standalone).

8.2 Database Audit


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports database audit.

Description
Database audit, referred to as audit, can record database-related operations in real time,
manage the compliance of fine-grained audit on database operations, generate alarms for risks
that a database faces, and block attack behavior. Specifically, it records, analyzes, and reports
user access to a database to help users generate compliance reports for incident backtracking.
In addition, it enhances the management of internal and external database operation records,
improving data security.
GaussDB 100 supports audit on certain user operations. The DDL and DCL audit switches are
enabled by default. Audit logging is controlled by the AUDIT_LEVEL parameter.
GaussDB 100 supports the following audit operations:
l DDL audit: When AUDIT_LEVEL is set to 1, only DDL operations such as CREATE,
DROP, and ALTER of database objects or users are audited. DDL is used to define or
modify database objects, such as tables, indexes, views, synonyms, databases, sequences,
users, roles, tablespaces, and profiles.
l DCL audit: When AUDIT_LEVEL is set to 2, only DCL operations of database objects
are audited. DCL is used to set or change the permissions for database sessions and
objects. DCL operations include ALTER SESSION, COMMIT, ROLLBACK,
GRANT, REVOKE, SHUTDOWN, ALTER SYSTEM KILL SESSION, and LOCK
TABLE.
l DML audit: When AUDIT_LEVEL is set to 4, DML operations such as INSERT,
UPDATE, DELETE, and MERGE are audited, and SELECT and EXPLAIN PLAN
are also audited. DML is used to manage table data.
l PL audit: When AUDIT_LEVEL is set to 8, stored procedures of databases are audited.
l DDL audit + DCL audit: When AUDIT_LEVEL is set to 3, both DDL audit and DCL
audit are performed.
l DDL audit + DML audit: When AUDIT_LEVEL is set to 5, both DDL audit and DML
audit are performed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Feature Description (Standalone) 8 Database Security

l DCL audit + DML audit: When AUDIT_LEVEL is set to 6, both DCL audit and DML
audit are performed.
l All types of audit: When AUDIT_LEVEL is set to 15, DDL audit, DCL audit, DML
audit, and PL audit are all performed.
GaussDB 100 audit allows for a customized log path and limits the maximum number and
size of audit logs.
For details about how to use the audit function, see GaussDB 100 V300R001C00 Security
Hardening Guide (Standalone).

8.3 Network Communication Security


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports SSL connection encryption and authentication between a server and a
client. When an application is connected through a JDBC interface, you can enable the SSL
connection. In addition, GaussDB 100 allows database whitelists and blacklists to be
configured, limiting client addresses for accessing databases.

Description
SSL, a security protocol, is used to ensure data security and data integrity for Internet
communication. Configuring SSL to encrypt client/server communication enhances security.
To start a server in SSL mode, you must configure a device certificate and a private key file
on the server. SSL_CERT and SSL_KEY parameters can be used in this situation. In a Unix
operating system, any world or group access to the private key file must be forbidden. You
can run the chmod 0600 server-key.crt command to set access permissions. If the private key
file needs password protection, set the SSL_KEY_PASSWORD parameter. GaussDB 100
uses SSL connection encryption and authentication to ensure user data security and integrity.
Configure client access authentication to allow remote host access. You can configure the user
whitelist (zhba.conf), IP address whitelist (TCP_INVITED_NODES), and IP address
blacklist (TCP_EXCLUDED_NODES) to control remote connections to GaussDB 100. By
default, only local access is allowed.
l User whitelist: Only users listed in zhba.conf can access the database and they must
access the database through specified IP addresses.
l IP address whitelist: Only the specified IP addresses can be used to access the database.
l IP address blacklist: The specified IP addresses cannot be used to access the database.
For details about how to configure the SSL connection encryption, user whitelist, IP address
whitelist, and IP address blacklist, see GaussDB 100 V300R001C00 Security Hardening
Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Feature Description (Standalone) 8 Database Security

8.4 User Profiles


Version
Introduced in GaussDB 100 V300R001C00

Introduction
GaussDB 100 supports user profiles to restrict user resources and behavior, ensuring database
security.

Description
A profile is a means of restricting resources for database users. For example, a profile can
limit CPU resources for sessions or SQL statements, and it also can determine user password
management policies. After a database is created, there is a default profile named DEFAULT
in the system. By default, the profile will be used for creating users unless otherwise
specified.

In GaussDB 100, each database user can be configured with a profile, the DEFAULT profile
by default.

GaussDB 100 can control the following resources and behavior:

l Number of days in which a password cannot be reused. PASSWORD_REUSE_TIME


specifies the number of days in which a password cannot be used repeatedly.
l Password validity period. PASSWORD_LIFE_TIME specifies the number of days in
which a password can be used. The default value is 180 (unit: day).
l Number of login attempt failures. FAILED_LOGIN_ATTEMPTS specifies the
maximum number of login attempts allowed before an account is locked. The default
value is 10.
l Account lock duration upon a login failure. PASSWORD_LOCK_TIME specifies the
account lock duration after the number of login attempts reaches the maximum. The
default value is 1 (unit: day).
l Number of days for alerting a password change. PASSWORD_GRACE_TIME
specifies a grace period, that is, the number of days from the time when a database sends
a warning to the time when the login expires. If a database password is not changed
within the grace period, the password becomes invalid after the grace period expires. The
default value is 7 (unit: day).
l Number of available connections for each user. SESSIONS_PER_USER specifies the
number of connections allowed for each user. The value must be less than the maximum
number of connections in a connection pool. This parameter takes effect only when
RESOURCE_LIMIT is enabled. To enable RESOURCE_LIMIT, run ALTER
SYSTEM SET RESOURCE_LIMIT = TRUE;.

For details about how to use user profiles, see GaussDB 100 V300R001C00 User Guide
(Standalone) and GaussDB 100 V300R001C00 R&D Documentation (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Feature Description (Standalone) 9 Glossary

9 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are a set of
features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a database. The
thread thread is used to archive database logs to a specified path.

atomicity One of the ACID features of database transactions. Atomicity means that a
transaction is composed of an indivisible unit of work. All operations
performed in a transaction must either be committed or uncommitted. If an
error occurs during transaction execution, the transaction will be rolled
back to the state when it was not committed.

backup A backup, or the process of backing up, refers to the copying and archiving
of computer data. Backup data can be used for restoration in case of data
loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false logical
condition. A bit is physically represented by an element such as high or low
voltage at one point in a circuit, or a small spot on a disk that is magnetized
in one way or the other. A single bit conveys little information a human
would consider meaningful. A group of eight bits, however, makes up a
byte, which can be used to represent many types of information, such as a
letter of the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at a certain
time. GaussDB 100 periodically stores the data of committed transactions
and data of uncommitted transactions to disks. The data and redo logs can
be used for database restoration if a database restarts or breaks down.

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands are entered
through keyboards or similar devices and are compiled and executed by
applications. The results are displayed in text or graphic forms on the
terminal interface.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

coding Coding is representing data and information using code so that it can be
processed and analyzed by a computer. Characters, digits, and other objects
can be converted into digital code, or information and data can be converted
into the required electrical pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or more


columns.

compression Data compression, source coding, or bit-rate reduction involves encoding


information that uses fewer bits than the original representation.
Compression can be either lossy or lossless. Lossless compression reduces
bits by identifying and eliminating statistical redundancy. No information is
lost in lossless compression. Lossy compression reduces bits by identifying
and removing unnecessary or less important information. The process of
reducing the size of a data file is commonly referred as data compression,
although its formal name is source coding (coding done at the source of
data, before it is stored or transmitted).

concurrency A DBMS service that ensures data integrity when multiple transactions are
control concurrently executed in a multi-user environment. In a multi-threaded
GaussDB 100 environment, concurrency control ensures that database
operations are safe and all database transactions remain consistent at any
given time.

consistency One of the ACID features of database transactions. Consistency is a


database state. In such a state, integrity constraints on tables are not
damaged.

convergence Downlink to uplink bandwidth ratio of a switch. A high convergence ratio


ratio indicates a highly converged traffic environment and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or system
dump records the state of working memory of the program at that point in
time. The states of key programs are often dumped at the same time. For
example, information about processor registers, including program metrics,
stack pointers, memory management, other processors, and OS flags are
often dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

core file A file that is created when memory overwriting, assertion failures, or access
to invalid memory occurs in a process, causing it to fail. This file is then
used for further analysis.
A core file stores memory dump data, and supports binary mode and
specified ports. The name of a core file consists of the word "core" and the
OS process ID.
The core file is available regardless of the type of platform.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

crash A crash (or system crash) is when a computer or program, such as a


software application or an operating system, stops functioning properly.
Often the program will exit after encountering this type of error. The
program experiencing the crash can hang or freeze until a crash reporting
service reports the crash and any details relating to it. If the program is a
critical part of the operating system and crashes, the entire system may be
paralyzed, often resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes constants,
variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored procedure
information, user rights, user statistics, database process information,
database increase statistics, and database performance statistics.

data flow An operator that exchanges data among query fragments. By their input/
operator output relationships, data flows can be categorized into Gather flows,
Broadcast flows, and Redistribution flows. Gather combines multiple query
fragments of data into one. Broadcast forwards the data of one query
fragment to multiple query fragments. Redistribution reorganizes the data
of multiple query fragments and then redistributes the reorganized data to
multiple query fragments.

data A division of a logical database or its constituent elements into multiple


partitioning parts (partitions) whose data does not overlap based on ranges or lists. The
target storage location is mapped based on the range of the values in the
column that is specified in the tuple.

database A collection of data that is stored together and can be accessed, managed,
and updated. Data in a view in a database can be classified into the
following types: numeral, full text, digit, and image.

database file A binary file that stores user data and the internal data of a database system.

database HA GaussDB 100 provides a highly reliable HA solution. Every logical node in
GaussDB 100 is identified as a primary or standby node. At the same time,
only one GaussDB 100 node is identified as the primary server. In
GaussDB 100, standby nodes first perform full synchronization from the
primary node and later incremental synchronization. When the HA system
is running, the primary node can receive data read and write requests in
GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database instances
to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database maintenance


operations.

DBLINK An object of the path from one database to another. A remote database
object can be queried with DBLINK.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a database.
It is a collection of programs that allows users to access, manage, and query
data in a database. A DBMS can be classified as memory DBMS or disk
DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data during an
event response, whereas a trace file contains continuously generated
diagnostic data.

durability One of the ACID features of database transactions. Transactions that have
been committed will permanently survive and not be rolled back.

encryption A function hiding information content during data transmission to prevent


unauthorized use of the information.

environment An environment variable defines a part of the environment in which a


variable process runs. For example, it can define a main directory, command search
path, terminal that is in use, or the current time zone.

error A technique that automatically detects and corrects errors in software and
correction data streams to improve system stability and reliability.

F–J

failover Automatic switchover from a faulty node to its standby node. Reversely,
automatic switchback from the standby node to the primary node is called
failback.

failover Automatic substitution of a functionally equivalent system component for a


failed one. The system component can be a processor, server, network, or
database.

free space A mechanism for managing free space in a table. This mechanism enables a
management database system to record free space in each table and establish an easy-to-
find data structure, accelerating operations (such as INSERT) performed on
the free space.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

freeze An operation automatically performed by the AutoVacuum Worker process


when transaction IDs are exhausted. GaussDB 100 records transaction IDs
in the row heading. When a transaction reads a row, the transaction ID in
the row heading and the actual transaction ID are compared to determine
whether this row is explicit. Transaction IDs are integers containing no
symbols. If exhausted, transaction IDs are re-calculated outside of the
integer range, causing the explicit rows to become implicit. To prevent such
a problem, the freeze operation marks a transaction ID as a special ID.
Rows marked with these special transaction IDs are explicit to all
transactions.

full A data synchronization mechanism specified in the GaussDB 100 HA


synchronizat solution. Used to synchronize all data from the primary server to a standby
ion server.

GNU The GNU Project was publicly announced on September 27, 1983 by
Richard Stallman, aiming at building an OS composed wholly of free
software. GNU is a recursive acronym for "GNU's Not Unix!". Stallman
announced that GNU should be pronounced as Guh-NOO. Technically,
GNU is similar to Unix in design, a widely used commercial OS. However,
GNU is free software and contains no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for each
node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration of


service interruptions caused by routine maintenance (planned) or sudden
system breakdowns (unplanned), improving system and application
usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on behalf of


all or some of the system users.

incremental Incremental backup stores all file changes since the last valid backup.
backup

index An ordered data structure in a DBMS. An index accelerates data query and
update in database tables.

isolation One of the ACID features of database transactions. Isolation means that the
operations inside a transaction and data used are isolated from other
concurrent transactions. Concurrent transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java APIs of
SQL statements. It provides unified access to multiple relational databases,
consisting of a set of classes and interfaces written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements. When
deleting a tuple, GaussDB 100 only marks the tuples that are to be cleared.
The VACUUM thread will then periodically clear these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

metadata Data that provides information about other data. Metadata describes the
source, size, format, or other characteristics of data. In database columns,
metadata explains the content of a data warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that allows a


tuple to have multiple versions, on which different query operations can be
performed. One basic advantage is that read and write operations do not
conflict.

network Network backup provides a comprehensive, flexible data protection


backup solution for Microsoft Windows, UNIX, and Linux platforms. Network
backup can back up, archive, and restore files, folders, directories, volumes,
and partitions on a computer.

OS An operating system (OS) manages applications or application programs on


a computer.

P–T

page Smallest memory unit for row storage in the relational object structure in
GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature of


GaussDB 100. Data can be restored to a specified point in time if backup
data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB 100 HA
server system and works with all standby servers. At any time, only one node in
the HA system is identified as the primary server.

process An instance of a computer program that is being executed. A process may


be made up of one or more threads. A process cannot use a thread occupied
by another process.

QPS Query Per Second (QPS) means the number of queries that a server can
respond to per second.

query Each query job can be split into one or more query fragments. Each query
fragment fragment consists of one or more query operators and can independently
run on a node. Query fragments exchange data through data flow operators.

query An iterator or a query tree node, which is a basic unit for the execution of a
operator query. Execution of a query can be split into one or more query operators.
Common query operators include scan, join, and aggregation.

record In a relational database, a record corresponds to data in each row of a table.

redo log A log that contains information required for performing an operation again
in a database. If a database is faulty, redo logs can be used to restore the
database to its original state.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

relational A database created using the relational model. It processes data using
database methods of set algebra.

resource A collection of resources that can be accessed to obtain information.


library

RPO Recovery point objective (RPO) refers to the latest status that a database
system and the data can be restored to after a disaster, and it is usually
represented by time.

RTO Recovery time objective (RTO) refers to the duration between the database
system failure caused by a disaster and its restoration to proper running.

schema A database object set that includes the logical structure, such as tables,
views, sequences, stored procedures, synonyms, clusters, and database
links.

segment A segment in a database indicates a part containing one or more extents. An


extent is the smallest range of a database and consists of data blocks. One
or more segments comprise a tablespace.

session A job created by a database system for connection purposes when an


application attempts to connect to the database. Sessions are managed by
the session manager. They execute initial jobs to perform all user
operations.

SGA System global area (SGA). It is the cache management framework of


GaussDB 100. It contains most cache management components of the
storage engine and SQL engine, including PlanCache, DataBuffer,
DcCache, RedoBuffer, CkptBuffer, LockBuffer, TransactionBuffer, and
ReplicationBuffer.

shared pool A shared pool is created for repeatedly executed SQL statements to save
memory. It contains the explain trees and execution plans of given SQL
statements.

SQL Structured Query Language (SQL) is a standard database query language. It


consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used by
Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides three
basic security services, all of which use the public key technology. SSL
ensures the security of service communication through a network by
establishing a secure connection between a client and a server and then
sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup of the


server primary server. If the primary server is behaving abnormally, the standby
server is promoted to primary, ensuring uninterrupted data services.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
Feature Description (Standalone) 9 Glossary

Term Description

statistics Information that is automatically collected by databases, including table-


level information (number of tuples and number of pages) and column-level
information (column value range distribution histograms). Statistics in
databases are used to estimate the costs of query plans to find the plan with
the lowest cost.

stop word In computing, stop words are words which are filtered out before or after
processing of natural language data (text), saving storage space and
improving search efficiency.

stored A group of SQL statements compiled into a single execution plan and
procedure stored in a large database system. Users can specify a name and parameters
(if any) for a stored procedure to execute the procedure.

system A table storing meta information about a database. The meta information
catalog includes user tables, indexes, columns, functions, and data types in a
database.

table A set of columns and rows. Each column is referred to as a field. Values in
each field represent a data type. For example, if a table contains three fields
of person names, cities, and states, it has three columns: Name, City, and
State. In every row in the table, the Name column contains a name, the City
column contains a city, and the State column contains a state.

tablespace A tablespace is a logical storage structure that contains tables, indexes, and
objects. A tablespace provides an abstract layer between physical data and
logical data, and provides storage space for all database objects. When you
create an object, you can specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and are used
for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a database. A


transaction consists of a limited database operation sequence, and must
have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information library. A


WSR is generated by comparing statistics collected by two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively enter
queries, issue them to GaussDB 100, and view the query results. Queries
can also be entered from files. zsql supports many meta commands and
shell-like commands, allowing you to conveniently compile scripts and
automate jobs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
V300R001C00

Operation Guide to Tools


(Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Operation Guide to Tools (Standalone) Contents

Contents

1 About This Document.................................................................................................................. 1


2 Client Tools.....................................................................................................................................4
2.1 Data Studio..................................................................................................................................................................... 4
2.2 zsql..................................................................................................................................................................................4
2.2.1 Overview..................................................................................................................................................................... 4
2.2.2 Connecting to a Database............................................................................................................................................ 6
2.2.3 Running Commands.................................................................................................................................................... 8
2.2.3.1 Executing SQL Statements....................................................................................................................................... 8
2.2.3.2 Executing SQL Scripts............................................................................................................................................. 9
2.2.3.3 Binding Parameters to SQL Statements................................................................................................................. 10
2.2.3.4 Executing SQL Statements in Silent Mode............................................................................................................ 12
2.2.4 Viewing Information Using DESC............................................................................................................................12
2.2.5 Printing Information Using PROMPT.......................................................................................................................13
2.2.6 Saving Execution Results Using SPOOL.................................................................................................................. 13
2.2.7 Setting Parameters..................................................................................................................................................... 14
2.2.8 Querying for Parameters............................................................................................................................................18
2.2.9 Exporting Data...........................................................................................................................................................21
2.2.10 Importing Data.........................................................................................................................................................25
2.2.11 Logically Exporting Data.........................................................................................................................................28
2.2.12 Logically Importing Data........................................................................................................................................ 33
2.2.13 Generating an Analysis Report................................................................................................................................36
2.2.14 Other Functions....................................................................................................................................................... 39
2.2.15 Exiting zsql.............................................................................................................................................................. 42

3 Database Management Tools.................................................................................................... 44


3.1 Tool Support................................................................................................................................................................. 44
3.2 install.py....................................................................................................................................................................... 45
3.3 uninstall.py................................................................................................................................................................... 46
3.4 upgrade.py.................................................................................................................................................................... 47
3.5 zctl.py........................................................................................................................................................................... 51
3.6 zencrypt........................................................................................................................................................................ 54
3.7 ztrst............................................................................................................................................................................... 56

4 Tools Used in the System...........................................................................................................58

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Operation Guide to Tools (Standalone) Contents

4.1 sql_process.py...............................................................................................................................................................58
4.2 zengine..........................................................................................................................................................................59
4.3 shutdowndb.sh.............................................................................................................................................................. 60

5 Interface Mapping (Basic Packages vs. Compatible Packages).......................................... 61


5.1 Data Dictionary Tables................................................................................................................................................. 61
5.2 DBA Views...................................................................................................................................................................63
5.3 User Views....................................................................................................................................................................65
5.4 Dynamic Performance Views....................................................................................................................................... 68

6 Glossary......................................................................................................................................... 71

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Operation Guide to Tools (Standalone) 1 About This Document

1 About This Document

Overview
GaussDB 100 is a high-performance and high-reliability distributed relational database
developed by Huawei Technologies Co., Ltd.. It supports automatic horizontal sharding and
breaks the storage and performance bottlenecks of a single server, applying to massive data
storage and processing. This document describes how to use the tools provided by the
GaussDB 100.
GaussDB 100 software packages are classified into basic and compatible packages. They
differ in the names of various interfaces. The compatible package is used to offer
compatibility with the usage habits of mainstream databases in the industry. The interfaces
mentioned in this document use names from the basic package. If you have installed the
compatible package, you can use either the interface names of the basic package or those of
the compatible package by referring to Interface Mapping (Basic Packages vs. Compatible
Packages). For details about how to install the basic and compatible packages, see
"Installation and Deployment" in GaussDB 100 V300R001C00 V300R001C00 User Guide
(Standalone).

Intended Audience
Database administrators

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not avoided, will


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in minor or moderate injury.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Operation Guide to Tools (Standalone) 1 About This Document

Symbol Description

Indicates a potentially hazardous situation which, if not avoided, could


result in equipment damage, data loss, performance deterioration, or
unanticipated results.
NOTICE is used to address practices not related to personal injury.

Calls attention to important information, best practices, and tips.


NOTE is used to address information not related to personal injury,
equipment damage, and environment deterioration.

Example Conventions
The following table describes some example information in this document. You can replace
the example information as needed.

Information Description

$GSDB_HOME Environment variable of the GaussDB 100 installation directory


that is automatically written when install.py is used for
installation. Assume that /opt/gaussdb/app is set as the
installation directory.

$GSDB_DATA Environment variable of the GaussDB 100 data directory that is


automatically written when install.py is used for installation.
Assume that /opt/gaussdb/data is set as the data directory.

gaussdba GaussDB 100 administrator manually created after the installation

database_123 Password of the database administrator gaussdba

192.168.0.1 IP address of the GaussDB 100 server

1888 Port number used by GaussDB 100 to listen to client connection


requests

Parameters of GaussDB 100 tools are parsed in sequence. If a parameter is specified for
multiple times, the last value takes effect.

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are in


italics.

[] Items (keywords and parameters) in brackets [ ] are optional.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Operation Guide to Tools (Standalone) 1 About This Document

Format Description

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more options or no
item is selected.

{ x | y | ... } Indicates that one item is selected from two or more options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with commas (,).

Change History
Version Update Changed On

03 Added: 2019-06-06
l ztrst
Modified:
l Parameter description in GaussRoach.py

02 This issue is the second official release. 2019-04-05

01 This issue is the first official release. 2018-10-30

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

2 Client Tools

After the database is deployed, you need certain tools to conveniently connect to a database
for operations and commissioning. GaussDB 100 provides database connection tools for users
to conveniently perform operations on the database.

2.1 Data Studio


Data Studio is a graphical user interface (GUI) tool used to connect to the database, and to
debug and run SQL statements and stored procedures. It supports the basic features of
GaussDB 100 and provides GUI for database developers, greatly improving the efficiency of
developing applications and simplifying tasks of database and application development.

Function
Database Manager provides the following functions for database developers:
l Browsing database objects
l Creating database objects, such as the database, user, table, and index
l Executing SQL statements and SQL scripts
l Editing and executing PL/SQL statements
For details about how to use Data Studio, see Data Studio User Manual released with the tool.

2.2 zsql
zsql is a client tool provided by GaussDB 100. It provides basic database functions, such as
interaction and query. It also provides advanced features.

2.2.1 Overview
zsql provides a command line interface (CLI) to help users connect to and use GaussDB 100.
zsql has its own commands and environments.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Parameters

Table 2-1 zsql parameters


Parameter Function

-h Shows help information.

-v Shows version information.

CONN, Connects to a database.


CONNECT l / AS SYSDBA
Allows user SYS to use local password-free login.
l / AS clsmgr
Specifies a DBMS administrator, who can connect to the database
only on the cluster management node.

-c Runs an SQL statement. This parameter cannot be used together with -f


or -s and must be placed at the end of a command.

-f Executes an SQL script. This parameter cannot be used together with -c


or -s and must be placed at the end of a command.

-s Runs an SQL statement in silent mode. In this mode, command prompt


and output are hidden. This parameter cannot be used together with -c or -
f and must be placed at the end of a command.

-w Time to wait before the client connection to the database times out. The
default value is 10s. This parameter can be used together with -q.

-q Cancels the SSL login authentication. This parameter can be used


together with -w.

DESCRIBE, Shows a database object.


DESC

PROMPT Prints user information.

SPOOL Records an operation log.

SET Sets parameters.

SHOW Shows query parameters.

DUMP Exports data.

LOAD Imports data.

EXP Logically exports data.

IMP Logically imports data.

WSR Generates an analysis report.

CALL Deletes a specified snapshot.

EXIT, QUIT Exits the zsql tool.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

2.2.2 Connecting to a Database


You can log in to GaussDB 100 in either of the following ways:
l Remote password-authentication login: The password can be an encrypted password for
remote connection or a non-encrypted password for local connection.
l Local password-free login: You log in as a Linux system user that has passed the
authentication. Therefore, you can use zsql to log in to the database running on the local
host. You can reset the password of user SYS after logging in as this user.

If you have logged in to a database through zsql in non-interactive mode, there would be a
large number of plaintext passwords in the environment. Therefore, you are advised to log in
to GaussDB 100 in interactive mode.
If no IP address is specified during password-free login, the first IP address of LSNR_ADDR
in the local configuration file will be used.

Scenario
Use zsql to connect to a GaussDB 100 server. Then, you can run SQL statements and perform
database operations.

Prerequisites
l The zsql tool has been installed on the client.
l The user for connection must have permission to access the database.
l Before remotely accessing a database through APIs such as zsql or JDBC, set LSNR_IP
and LSNR_PORT in the zengine.ini file. A maximum of eight listening IP addresses
can be set at a time, and they must be separated by commas (,). For details, see
"Database Usage > Configuring Client Access Authentication" in GaussDB 100
V300R001C00 User Guide (Standalone).
l Before remotely accessing a database, configure access authentication on the local client.
For details about how to configure client access authentication, see "Database Usage >
Configuring Client Access Authentication" in GaussDB 100 V300R001C00 User Guide
(Standalone).

Precautions
If the password of a database user contains the special character $, use the escape character \
to connect to the database through zsql. Otherwise, the login will fail.

Procedure
l Log in as a database administrator. (Only database administrators can use password-free
login.)
zsql
{ CONNECT | CONN } / AS SYSDBA [ip:port] [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

[ip:port] is optional. If it is not specified, the local host will be connected by default.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

If a database administrator has started multiple database instances, you need to specify
the database directory (-D) when connecting to a specified database.
The -q parameter is used to cancel the SSL login authentication check. The -s parameter
is used to set the silent mode (no prompt) for SQL statement execution.
The -w parameter is used to set the timeout period for the client to wait for a connection
response from the database. Its values are -1, indicating that the client keeps waiting
without timeout restrictions; 0, indicating that the client does not wait and the server
directly returns a failure result; and n, indicating that the client waits for n seconds. The
default value is 10s. After this parameter is used, its value will be the response waiting
timeout period when the zsql process is started to connect to the database. After the
process startup, the timeout period will be used in waiting for a response for establishing
or reestablishing a new connection as well as that in queries. After the zsql process is
exited, the setting becomes invalid.
l Log in as a common database user.
GaussDB 100 supports the following login modes:
– Interactive login mode 1:
zsql user@ip:port [-D /home/gaussdba/data1] [-q] [-s "silent_file"] [-w
connect_timeout]

Enter the password as prompted.


Please enter password:

– Interactive login mode 2:


zsql
conn user/user_password@ip:port [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

– Non-interactive login mode:


zsql user/user_password@ip:port [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

In this command, user indicates the name of the database user and password indicates
the password of the user. ip:port indicates the IP address and port number of the host
where the database resides. The default port number is 1888.
If a database administrator has started multiple database instances, you need to specify
the database directory (-D) when connecting to a specified database.
The -q parameter is used to cancel the SSL login authentication check. The -s parameter
is used to set the silent mode (no prompt) for SQL statement execution.
The -w parameter is used to set the timeout period for the client to wait for a connection
response from the database. Its values are -1, indicating that the client keeps waiting
without timeout restrictions; 0, indicating that the client does not wait and the server
directly returns a failure result; and n, indicating that the client waits for n seconds. The
default value is 10s. After this parameter is used, its value will be the response waiting
timeout period when the zsql process is started to connect to the database. After the
process startup, the timeout period will be used in waiting for a response for establishing
or reestablishing a new connection as well as that in queries. After the zsql process is
exited, the setting becomes invalid.

Examples
l Locally log in to a database as user gaussdba.
gaussdba@plat1~> zsql
SQL> CONN gaussdba/database_123@127.0.0.1:1888

connected.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

l Start the zsql process and set a response waiting timeout period.
-- Start the zsql process and set the response waiting timeout period to 20s.
After the process is started, the timeout period for waiting for a connection
setup response will be 20s.
zsql gaussdba/database_123@127.0.0.1:1888 -w 20
connected.
-- Create a user jim and grant the CREATE SESSION permission to the user.
DROP USER IF EXISTS jim;
CREATE USER jim IDENTIFIED BY database_123;
GRANT CREATE SESSION TO jim;
-- Switch to the user. The timeout period for waiting for a reconnection
setup response will be also 20s.
CONN jim/database_123@127.0.0.1:1888
connected.
-- Exit the zsql process. The timeout period setting becomes invalid, and the
timeout period for waiting for a new connection setup response will be 10s
(default value).
EXIT

2.2.3 Running Commands


zsql supports the following types of command input:
l SQL statements: used to process data in databases and manage databases, such as
creating users, managing rights, configuring database parameters (requiring database
administrator rights), and detecting database systems
l zsql commands: used to format query results, set session parameters, execute client SQL
scripts, and store SQL execution results
l Data import and export commands: used for logical backup

2.2.3.1 Executing SQL Statements

Scenario
Run SQL statements on zsql to add, delete, update, and query data, objects, and permissions.

NOTE

The maximum length of an executable SQL statement is 1 MB.

SQL Execution
Take creating a table as an example
CREATE TABLE place
(
place_ID NUMBER(4) not null,
STREET_ADDRESS VARCHAR2(40),
POSTAL_CODE VARCHAR2(12),
CITY VARCHAR2(30),
STATE_PROVINCE VARCHAR2(25),
state_ID CHAR(2)
) ;

When entering a SQL statement in the zsql interface, use a semicolon (;) or a slash (/) at the
end of the statement, and then press Enter to run the command. If you use a slash (/), put it in
a new line and press Enter.
zsql also allows for multiple SQL statements in a single line. In this case, use a semicolon (;)
to separate them. zsql identifies each SQL statement by semicolon (;) and then executes them
in sequence. For example, run the following statements:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

SELECT 1 + 2 FROM sys_dummy;SELECT 'Hello Zenith' FROM sys_dummy;

The following information is displayed:


1 + 2
--------------------
3
1 rows fetched.
'HELLO ZENITH'
--------------
Hello Zenith
1 rows fetched.

SQL Execution Using -c


zsql allows a single SQL statement to be executed upon zsql start by using the -c parameter.
An example is as follows:
zsql user/password@ip:port -c "SQL_Statement"

l Following the -c parameter, you can enter multiple common SQL statements and
separate them using semicolons (;); or enter only one stored procedure and end it with a
slash (/).
l If an object name contains $, an escape character (\) is needed.

2.2.3.2 Executing SQL Scripts

Scenario
zsql can be used to execute SQL script files. A SQL script file is a .sql file that contains a set
of SQL statements. The syntax is as follows. The maximum length of a line is 64 KB and the
maximum length of an executable SQL statement is 1 MB.

SQL Script Execution Using @ or start


After logging in to a database using the zsql tool, you can use @, @@, or the start command
to execute the SQL script. Specify the absolute storage path of the script file.
-- The symbol @ is followed by the SQL script file.
@/opt/userscripts/sql_script_file
-- The symbol @@ is followed by the SQL script file.
@@/opt/userscripts/sql_script_file
-- start is followed by the SQL script file.
start /opt/userscripts/sql_script_file

Assume that the content of the SQL script file my_script.sql is as follows and the storage
path is /opt/userscripts/my_script.sql.
INSERT INTO COUNTRY
VALUES ('NGA','Nigeria','Africa','Western
Africa',923768.00,1960,111506000,51.6,65707.00,58623.00,'Nigeria','Federal
Republic','Olusegun
Obasanjo',2754,'NG');
SELECT Code, Name, Population
FROM COUNTRY
WHERE Population > 100000;

Run either of the following commands in the zsql command line to execute my_script.sql:
@/opt/userscripts/my_script.sql

Or

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

start /opt/userscripts/my_script.sql

SQL Script Execution Using -f


zsql allows a script file to be executed upon zsql start by using the -f parameter. Examples are
as follows:
zsql user/password@ip:port -f sql_script_file

Or
zsql user/password@ip:port -f "sql_script_file"

Comment Conventions
The SQL scripts of GaussDB 100 support two comment formats:
l Single-line comment
Format: -- Comment
l Multi-line comment
Format: /*Comment*/

2.2.3.3 Binding Parameters to SQL Statements

Scenario
zsql supports parameter binding, which means binding a variable to a name placeholder or
question mark placeholder in a prepared SQL statement. This effectively prevents SQL
injection. Parameter binding is widely used in applications. You can bind multiple parameters
to a SQL statement by entering their types and values in sequence.

Method
Placeholders are as follows:
l ? -- Single question mark
l :1 -- Colon and number
l :name -- Colon and variable name
The zsql supports the following data types for bind parameters: CHAR, VARCHAR,
STRING, INT, INTEGER, UINT32, UNSIGNED INTEGER, BIGINT, REAL, DOUBLE,
DATE, TIMESTAMP, BLOB, CLOB, DECIMAL, NUMBER, BOOLEAN, and BOOL. For
details about the mapping, see Table 2-2.

Table 2-2 Mapping between bind parameters and types


Bind Parameter Type Converted To

CHAR CHAR

VARCHAR VARCHAR

STRING STRING

INT INTEGER

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Bind Parameter Type Converted To

INTEGER INTEGER

UINT32 UINT32

UNSIGNED INTEGER UINT32

BIGINT BIGINT

REAL REAL

DOUBLE REAL

DATE DATE

TIMESTAMP TIMESTAMP

BLOB STRING

CLOB STRING

DECIMAL DECIMAL

NUMBER NUMBER

BOOLEAN BOOLEAN

BOOL BOOLEAN

Precautions
l Placeholders for parameter binding cannot appear in the SELECT list, that is,
placeholders are not allowed between SELECT and FROM.
l If an entered data type is not supported, an error will be reported.

Examples
Enter the following statement:
SELECT Code, Name, Population
FROM COUNTRY
WHERE Population > ?;

The following information is displayed:


+-------------------------------------------------+
| ZSQL Bind Param |
+-------------------------------------------------+
The 1th param:
Direction :

After you specify Direction, DataType, and BindValue for parameter binding, the following
information will be displayed:
Direction : in
DataType : int
BindValue: 1
Bind params successfully.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

2.2.3.4 Executing SQL Statements in Silent Mode

Scenario
Executing SQL statements in silent mode returns the execution results all to a specified file,
instead of a display screen.

Procedure
Step 1 Specify the silent mode when connecting to a database.
zsql gaussdba@192.168.0.1 -s silent.log
Please enter password:
************
connected.

For details about how to connect to a database, see Connecting to a Database.

Step 2 Run SQL statements.

Step 3 Print the specified output file to view the execution results.
cat silent.log

----End

Examples
-- Connect to a database as user hr in silent mode, and specify the output log
file as silent.log:
zsql hr@127.0.0.1:1171 -s silent.log
-- Create a training table:
CREATE TABLE training(staff_id INT NOT NULL,course_name
CHAR(50),course_start_date DATETIME, course_end_date DATETIME,exam_date
DATETIME,score INT);
INSERT INTO
training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20
12:00:00','2017-06-25 12:00:00',90);
-- Exit the database:
exit
-- View silent.log:
cat silent.log
Succeed.

2.2.4 Viewing Information Using DESC

Scenario
On the zsql client, you can run the DESCRIBE command or its abbreviation DESC to view
the definition information about database objects (such as tables or views) or view SQL
statements.

Syntax
l View the definition information about database objects.
DESCRIBE [-o | -O] object

Or
DESC [-o | -O] object

l View SQL statements.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

The description of a column when SELECT is used for query is displayed, including its
name, nullable attribute, type, and size (character or byte).
If DESC is used, the column size will be displayed as the maximum deduction value
obtained during SQL parsing, and the returned column data will not exceed this size.
DESC -q SELECT expression

Examples
Query the definition of the privilege table.
-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege(staff_id INT PRIMARY KEY, privilege_name VARCHAR(64) NOT
NULL, privilege_description VARCHAR(64), privilege_approver VARCHAR(10));
-- Query the definition of the privilege table.
DESC privilege;

Name Null? Type


----------------------------------- -------- ------------------------------------
STAFF_ID NOT NULL BINARY_INTEGER
PRIVILEGE_NAME NOT NULL VARCHAR(64 BYTE)
PRIVILEGE_DESCRIPTION VARCHAR(64 BYTE)
PRIVILEGE_APPROVER VARCHAR(10 BYTE)

2.2.5 Printing Information Using PROMPT

Scenario
Running the PROMPT command prints user-entered information. You can add this command
in a script to provide information for users.

NOTE

l Press Enter to end input. Semicolons (;) at the end of a line are not displayed.
l The maximum length an input string is 64 bytes.

Examples
Run the following statements to print user information:
PROMPT Please enter a username
PROMPT For example: jim
SELECT * FROM DV_DATABASE

2.2.6 Saving Execution Results Using SPOOL

Scenario
Running the SPOOL statement records operation logs for database management.

Procedure
zsql can output execution results to an OS file by using SPOOL. The syntax is as follows:
-- Specify an output file, which can be either a relative path or an absolute
path:
SPOOL file_path

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

-- Save the execution results and stop spooling:


SPOOL off

After the file for spooling is specified, zsql will directly output the execution results to the
file. The content of the file is similar to that displayed in the zsql command line. Spooling
will be stopped only after SPOOL off is specified.

If the file specified in the SPOOL statement does not exist, zsql will create a file. If the
specified file already exists, zsql will append the execution results to the file.

Examples
Run the following statements:
SPOOL ./spool.txt
SELECT Code, Name, Population
FROM COUNTRY
WHERE Population > 100000;
SELECT 'This SQL will be output into ./spool.txt' FROM SYS_DUMMY;
SPOOL OFF;
SELECT 'This SQL will not be output into ./spool.txt' FROM SYS_DUMMY;

After these statements are executed, a file ./spool.txt will be generated in the current
directory, and the file content is as follows:
SQL> SELECT Code, Name, Population
SQL> FROM COUNTRY
SQL> WHERE Population > 100000;
CODE NAME POPULATION
---- ---------------------------------------------------- ------------
MLT Malta 380200
MMR Myanmar 45611000
MNG Mongolia 2662000
MTQ Martinique 395000
4 rows fetched.
SQL>
SQL> SELECT 'This SQL will be output into ./spool.txt' FROM SYS_DUMMY;
'THIS SQL WILL BE OUTPUT INTO
----------------------------------------
This SQL will be output into ./spool.txt
1 rows fetched.
SQL>
SQL> SPOOL OFF;

2.2.7 Setting Parameters


On the zsql client, you can set some client parameters by running the SET statement.

Syntax
SET [attr_name] [value]

Parameters
l attr_name
Specifies the attribute name.
The following attributes are supported:
– AUTO[COMMIT]
Specifies whether to automatically commit statements.
Valid value:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

n ON: Commit.
n OFF: Do not commit.
Default value: OFF
– EXITC[OMMIT]
Specifies whether to commit data modified in a session when zsql is closed or
exited.
Valid value:
n ON: Commit.
n OFF: Do not commit.
Default value: ON
– CHARSET
Specifies the client character set.
Valid value:
n GBK
n UTF8
Default value: UTF8
– HEA[DING]
Specifies whether to display column headings.
Valid value:
n ON: Display.
n OFF: Do not display.
Default value: ON
– TRIMS[POOOL]
Specifies whether to remove trailing blanks at the end of each line.
Valid value:
n ON: Remove.
n OFF: Do not remove.
Default value: OFF
– SERVEROUT[PUT]
Specifies whether to display server output information generated by the
DBMS_OUTPUT.PUT_LINE package.
Valid value:
n ON: Display.
n OFF: Do not display.
Default value: 0, which means no limit.
– LINE[SIZE]
Specifies the maximum number of characters allowed in a line. If the output content
for a line exceeds this number, the content will be truncated.
Value range: [0, +∞)
Default value: 0, which means no limit.
– NUM[WIDTH]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Specifies the width for displaying numbers.


Value range: [6,52]
Default value: 40
– PAGES[IZE]
Specifies the number of lines on each page.
Value range: 0 or [4, +∞)
Default value: 0, which means no limit.
– TIM[ING]
Specifies whether to display the runtime of an SQL statement, accurate to 0.001s
(ms).
Valid value:
n ON: Display.
n OFF: Do not display.
Default value: OFF
– FEED[BACK]
Specifies whether to display feedback when an SQL statement returns n or more
than lines of records.
Valid value:
n ON: When you set the number of returned records to n, in the range [1, +∞),
and the actual number exceeds n, the feedback is displayed.
n OFF: n is 0, and no feedback is displayed.
Default value: ON
– ECHO
Specifies whether to display the SQL statements in a script executed by using the
symbol @.
Valid value:
n ON: Display.
n OFF: Do not display.
Default value: OFF
– VER[IFY]
Specifies whether to display the confirmation information old sql is and new sql is
when the variable replacement command SET DEFINE is used.
Valid value:
n ON: Display.
n OFF: Do not display.
Default value: ON
– TERM[OUT]
Specifies whether to display the execution information when SQL commands in a
script are executed by using the symbol @.
Valid value:
n ON: Display.
n OFF: Do not display.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Default value: ON
– NEWP[AGE]
Specifies the number of empty rows between pages.
Value range: 0 or [1, +∞)
Default value: 1
– COLSEP
Specifies the separator between columns.
Value range: 'text'|"text"|text
Default value: ' ', indicating that the separator between columns is a space
– LONG
It is used only for syntax adaptation.
– DEFINE
Specifies whether to enable variable substitution. The substitution variable
identifier is an ampersand (&) by default.
n ON: Enable. In this case, if an input string contains a substitution variable
identifier, the string following the identifier will be identified as the variable
name, you will be prompted to enter the value of the substitution variable. For
example, when you enter the string SQL&Plus, the system prompts you to
enter the value of the substitution variable Plus. After you enter ABC, the
string SQL&Plus will be converted to SQLABC.
n OFF: Do not enable. The substitution variable identifier is entered as a
common character. For example, when you enter the string SQL&Plus, the
final input is also SQL&Plus.
n one_char can be used to change the substitution variable identifier, and only
one character is supported. In this case, the substitution variable function is
automatically enabled. For example, use SET DEFINE @ to set the
substitution variable identifier to @.
Default value: OFF
– OPLOG
Specifies whether to enable the function of recording operation logs on the zsql
client.
Valid value:
n ON: Enable.
n OFF: Do not enable.
Default value: ON
– ZSQL_SSL[_MODE|_CA|_CERT|_CRL|_CIPHER|_KEY|_KEY_PASSWD]
Specifies SSL-related attributes and the file path.
Default value: NULL
– CONNECT[_TIMEOUT]
Sets the timeout period for the client to wait for a connection response from the
database. After this parameter is modified, the timeout period for waiting for a
response from the current long connection is still 10s. The modification will take
effect for a new connection established at the background or for a connection
reestablished using conn name/password@ip:port. The modification will be invalid
after the zsql process exits.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Valid value:
n -1: Wait for a response from the server and never time out.
n 0: Do not wait.
n n: Wait for n seconds.
Default value: 10s
l value
Specifies an attribute value.

Examples
l Set INTERACTIVE_TIMEOUT to 4200.
ALTER SYSTEM SET INTERACTIVE_TIMEOUT = 4200;

l Set AUTO to OFF to disable the automatic commit function.


SET AUTO OFF;

l Set the substitution variable identifier to an ampersand (&).


-- Set the substitution variable identifier to an at sign (@).
SET DEFINE @

ON
-- View the current value of the substitution variable identifier:
SHOW DEFINE

repalce fuction is ON and replace mark is @.

l Set CONNECT to 20s.


-- Start the zsql process.
zsql
-- Set CONNECT to 20s.
SQL> set CONNECT = 10
-- The timeout period for waiting for the response from a new connection is
20s.
SQL> CONN gaussdba/database_123@127.0.0.1:1888
SQL>
-- Exit the zsql process. The timeout period setting becomes invalid, and the
timeout period for waiting for a new connection setup response will be 10s
(default value).
EXIT

2.2.8 Querying for Parameters

Scenario
When you query for parameter information, fuzzy query is supported, which is case-
insensitive.

Syntax
SHOW [
PARAMETER[S]
| PARAMETER[S] parameter_name
| attr_name
]

Parameters
l PARAMETER[S]
Displays the names, types, and values of all configured parameters.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

l PARAMETER[S] parameter_name
Displays the value of a specified parameter in the database.
Fuzzy query of parameters is supported.
l attr_name
Specifies the attribute name.
The following attributes are supported:
– AUTO[COMMIT]
Specifies whether to automatically commit statements.
n ON: Commit.
n OFF: Do not commit.
– EXITC[OMMIT]
Specifies whether to commit data modified in a session when zsql is closed or
exited.
n ON: Commit.
n OFF: Do not commit.
– CHARSET
Specifies the client character set.
– HEA[DING]
Specifies whether to display column headings.
n ON: Display.
n OFF: Do not display.
– SERVEROUT[PU]T
Specifies whether to display procedural output generated by the
DBMS_OUTPUT.PUT_LINE package.
n ON: Display.
n OFF: Do not display.
– TRIMS[POOL]
Specifies whether to remove trailing blanks at the end of each line.
n ON: Remove.
n OFF: Do not remove.
– SPOO[L]
Specifies whether to export data to a specified file.
n ON: Export.
n OFF: Do not export.
– LIN[ESIZE]
Specifies the maximum number of characters allowed in a line. If the output content
for a line exceeds this number, the content will be truncated.
– NUM[WIDTH]
Specifies the width for displaying numbers.
– PAGES[IZE]
Specifies the number of lines displayed on a page.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

– TIM[ING]
Specifies whether to display SQL execution time.
n ON: Display.
n OFF: Do not display.
– FEED[BACK]
Specifies whether to display feedback when an SQL statement returns n or more
than lines of records.
n ON: When you set the number of returned records to n, in the range [1, +∞),
and the actual number exceeds n, the feedback is displayed.
n OFF: No feedback is displayed.
– ECHO
Specifies whether to display the SQL statements in a script executed by using the
symbol @.
n ON: Display.
n OFF: Do not display.
– VER[IFY]
Specifies whether to display the confirmation information old sql is and new sql is
when the variable replacement command SET DEFINE is used.
n ON: Display.
n OFF: Do not display.
– TERM[OUT]
Specifies whether to display the execution information when SQL commands in a
script are executed by using the symbol @.
n ON: Display.
n OFF: Do not display.
– NEWP[AGE]
Specifies the number of blank lines between pages. The default value is 1.
– COLSEP
Specifies the separator between columns. The default value is ' '.
– LONG
It is used only for syntax adaptation.
– PARAMETER[S]
Displays the names, types, and values of all configured parameters.
– DEFINE
Specifies whether to enable variable substitution.
n ON: Enable.
n OFF: Do not enable.
– OPLOG
Specifies whether to enable the operation log function on the zsql client.
n ON: Enable.
n OFF: Do not enable.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

– ZSQL_SSL[_MODE|_CA|_CERT|_KEY|_CRL|_KEY_PASSWD|_CIPHER]
Specifies SSL-related attributes.
– CONNECT[_TIMEOUT]
Queries the time to wait before a database connection times out.

Examples
l Query for parameters whose names contain the keyword interactive_timeout.
SQL> show parameter interactive_timeout;

NAME
DATATYPE VALUE
----------------------------------------------------------------
--------------------
----------------------------------------------------------------
INTERACTIVE_TIMEOUT
GS_TYPE_INTEGER 28800

l Query for parameters whose names contain the keyword timeout.


SQL> show parameter timeout;

NAME
DATATYPE VALUE
----------------------------------------------------------------
--------------------
----------------------------------------------------------------
CHECKPOINT_PERIOD
GS_TYPE_INTEGER 300
INTERACTIVE_TIMEOUT
GS_TYPE_INTEGER 28800
LOCK_WAIT_TIMEOUT
GS_TYPE_INTEGER 0
LONGSQL_TIMEOUT
GS_TYPE_INTEGER 10
REPL_WAIT_TIMEOUT
GS_TYPE_INTEGER 10

2.2.9 Exporting Data

Scenario
During database migration or data backup, you need to import and export data. zsql allows
you to use the DUMP statement to export data.

Precautions
l If DUMP uses the -h, -u, or help parameter and ends with a semicolon (;) or slash (/),
the help information of the command will be displayed.
l If DUMP uses the -o or option parameter and ends with a semicolon (;) or slash (/), the
latest configuration item will be displayed.
l When DUMP is used to export data, SQL statements are assembled on the client before
being sent to a server, which then receives complete, specific DDL and DML statements.
l The server audit log {GSDB_DATA}/log/audit records only the DDL and DML
statements, instead of DUMP.
l Do not set the name of a target export file to the system or configuration file name.
Otherwise, the file may be overwritten or deleted.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Syntax
DUMP { TABLE table_name | QUERY "select_query " }
INTO FILE 'file_name '
[ FILE SIZE 'uint64_file_size' ]
[ { FIELDS | COLUMNS } ENCLOSED BY 'ascii_char' [ OPTIONALLY ] ]
[ { FIELDS | COLUMNS } TERMINATED BY 'string ']
[ { LINES | ROWS } TERMINATED BY 'string ']
[ CHARSET 'string' ];

Parameter Description
l table_name
Specifies the name of a table whose data is to be exported.
l select_query
Specifies the records to be exported. select_query is a SELECT clause.
l file_name
Specifies the name of a file to store exported data.
l uint64_file_size
Specifies the size of each file storing exported data. If a file is full, a new file will be
created to store data. The default value is 0, indicating that no new file will be created.
l FIELDS
Specifies the format of each column.
l COLUMNS
Specifies the format of each column. It is equal to FIELDS.
l ENCLOSED BY
Encloses column values with a pair of characters.
l ascii_char
Specifies the characters used to enclose each column value. For example, in "ABC", the
value is ABC and the characters used to enclose the value are double quotation marks
(""). By default, the characters are not specified.
Value range: a single ASCII character or an empty string. The value single quotation
marks ('') indicate that no characters are specified.
– Decimal ASCII characters range from 0 to 127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-3.
l OPTIONALLY
Encloses only character and binary data. By default, OPTIONALLY is not used.
l TERMINATED BY
Separates columns with delimiters.
l string
Specifies a column delimiter. The default value is a comma (,).
Value range: a single-byte ASCII character
– Decimal ASCII characters range from 0 to 127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-3.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

l LINES
Separates rows with delimiters if a record contains multiple rows.
l ROWS
It is a synonym of LINES.
string
Specifies a row delimiter. The default value is \n.
Value range: a single-byte ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-3.
l CHARSET
Specifies the character set to be exported.
string
Currently, only the UTF8 (without BOM) character set (CHARSET = UTF8) and GBK
character set (CHARSET = GBK) are supported. The former is used by default.
l row_terminated_char
Specifies a row delimiter. The default value is \n.
Value range: a single-byte ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-3.

Table 2-3 Common escape characters

Escape Description ASCII ASCII


Character (Decimal) (Hexadecimal)

\a BELL (BEL) 007 \x07

\f Form feed (FF). Move to 012 \x0C


the beginning of the next
page.

\n Line feed (LF). Move to 010 \x0A


the beginning of the next
line.

\r Carriage return (CR). 013 \x0D


Move to the beginning of
the current line.

\t Horizontal table (HT). 009 \x09


Jump to the next tab.

\v Vertical tab (VT) 011 \x0B

\\ One backslash (\) 092 \x5C

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Escape Description ASCII ASCII


Character (Decimal) (Hexadecimal)

Two single One single quotation 039 \x27


quotation mark (')
marks ('')

\" One double quotation 034 \x22


mark (")

\? One question mark (?) 063 \x3F

\0 Null character (NULL) 000 \x00

\ooo One- to three-digit octal Three-digit octal -


character code

\xhh One- to two-digit Two-digit -


hexadecimal character hexadecimal
code

NOTE

The single quotation mark (') is an escape character of SQL. If you need to use it as a delimiter, use two
single quotation marks ('') to represent it. For example:
.... enclosed by ''''....
The outer two single quotation marks are used to enclose the inner ones ('') that represent a single
quotation mark (').
If the character specified by ascii_char is included in the column value, the character will be escaped
again when the column value is exported. For example, if the specified character is the double quotation
mark (") which is included in the column value 1"1, the value will be exported as "1""1".

Examples
l Export an existing table places from the database. Add a vertical bar (|) at the end of the
statement.
DUMP TABLE places INTO FILE '/gaussdb/backup/places_backup ' FIELDS ENCLOSED
BY '|';
23 rows dumped.

l Export the rows whose STATED_ID is US from the table places. Each row is enclosed
with single quotation marks (''), and is ended with vertical bars (|).
DUMP QUERY "SELECT STREET_ADDRESS,CITY FROM places WHERE STATED_ID = 'US'"
INTO FILE '/gaussdb/backup/places_backup '
COLUMNS ENCLOSED BY ''''
COLUMNS TERMINATED BY '|';
4 rows dumped.

The following is exported:


'2014 Jabberwocky Rd'|'Southlake'
'2011 Interiors Blvd'|'South San Francisco'
'2007 Zagora St'|'South Brunswick'
'2004 Charade Rd'|'Seattle'

l Display the method for using DUMP.


dump -h;
dump -u;
dump help;

l Display the current configuration item for DUMP.


dump -o;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

dump option;

2.2.10 Importing Data

Scenario
During database migration or data backup, you need to import and export data. zsql allows
you to use the LOAD statement to import data.

Precautions
l A target file for data to be imported to must match the source file in the number of
columns and the data types of columns.
l GaussDB 100 supports plain-text file import.
l If LOAD uses the -h, -u, or help parameter and ends with a semicolon (;) or slash (/), the
help information of the command will be displayed.
l If LOAD uses the -o or option parameter and ends with a semicolon (;) or slash (/), the
latest configuration item will be displayed.
l When LOAD is used to import data, SQL statements are assembled on the client before
being sent to a server, which then receives complete, specific DDL and DML statements.
l The server audit log {GSDB_DATA}/log/audit records only the DDL and DML
statements, instead of LOAD.

Syntax
LOAD DATA INFILE "file_name" INTO TABLE table_name
[{ FIELDS | COLUMNS } ENCLOSED BY 'ascii_char' [ OPTIONALLY ]]
[{ FIELDS | COLUMNS } TERMINATED BY 'string']
[{ LINES | ROWS } TERMINATED BY 'string']
[ TRAILING COLUMNS( COLUMN1[ , COLUMN2, ... ] ) ]
[ IGNORE uint64_num { LINES | ROWS }]
[ CHARSET string ]
[ THREADS uint32_threads ]
[ ERRORS uint32_num ]
[ NOLOGGING ]
[ NULL2SPACE ]
[ DEBUG ];

Parameter Description
l file_name
Specifies the path and name of a file to be imported.
l table_name
Specifies the name of a table to store imported data.
l FIELDS
Specifies the format of each column.
l COLUMNS
Specifies the format of each column. It is equal to FIELDS.
l ENCLOSED BY
Encloses column values with a pair of characters.
l ascii_char

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Specifies the characters used to enclose each column value. By default, no characters are
specified.
Value range: a single ASCII character, or an empty string ('') which indicates that no
characters are specified.
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-4.
l OPTIONALLY
Encloses only character and binary data. By default, they are enclosed with a pair of
single quotation marks ('').
l TERMINATED BY
Separates columns with delimiters.
string
Specifies a column delimiter. The default value is a comma (,).
Value range: one or more ASCII characters. A maximum of 10 characters are allowed.
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-4.
l LINES
Separates rows with delimiters if a record contains multiple rows.
l ROWS
It is a synonym of LINES.
string
Specifies a row delimiter. The default value is \n.
Value range: a single ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 2-4.
l IGNORE
Specifies the number of lines to be ignored.
l uint64_num
Ignores the first uint64_num lines. The default value is 0.
l THREADS
Specifies the number of threads for concurrent data import.
l uint32_threads
Specifies the number of threads for concurrent import. The default value is 1. Multi-
thread import is used to improve efficiency. Deviation is allowed to collect statistics
about the number of errors. In addition, detailed information about records that cause
errors is recorded and the errors will not affect the subsequent import.
Value range: [1, 128]
l ERRORS
Specifies the number of SQL statements that are allowed to cause errors.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

l uint32_num
Specifies the number of SQL statements that are allowed to cause errors. The default
value is 0.
l NOLOGGING
Does not record redo or undo logs for imported data. This parameter is available only
when the target table is set to append only.
l DEBUG
Prints debugging information generated during tool running to a screen.
l CHARSET
Specifies the character set to be imported.
string
Currently, only the UTF8 (without BOM) character set (CHARSET = UTF8) and GBK
character set (CHARSET = GBK) are supported. The former is used by default.
l TRAILING COLUMNS( COLUMN1[ , COLUMN2, ... ] )
Specifies the columns to which data is to be imported. COLUMN1[, COLUMN2, ...]
specifies column names and at least one name must be specified.
l NULL2SPACE
Inserts a space to replace NULL, if an empty value of the CHAR or LOB type is to be
imported and NOT NULL is specified.

Table 2-4 Common escape characters

Escape Description ASCII (Decimal) ASCII


Character (Hexadecimal)

\a BELL (BEL) 007 \x07

\f Form feed (FF). Move to the 012 \x0C


beginning of the next page.

\n Line feed (LF). Move to the 010 \x0A


beginning of the next line.

\r Carriage return (CR). Move 013 \x0D


to the beginning of the
current line.

\t Horizontal table (HT). Jump 009 \x09


to the next tab.

\v Vertical tab (VT) 011 \x0B

\\ One backslash (\) 092 \x5C

Two single One single quotation mark 039 \x27


quotation (')
marks ('')

\" One double quotation mark 034 \x22


(")

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Escape Description ASCII (Decimal) ASCII


Character (Hexadecimal)

\? One question mark (?) 063 \x3F

\0 Null character (NULL) 000 \x00

\ooo One- to three-digit octal Three-digit octal -


character code

\xhh One- to two-digit Two-digit -


hexadecimal character code hexadecimal

NOTE

The single quotation mark (') is an escape character of SQL. If you need to use it as a delimiter, use two
single quotation marks ('') to represent it. For example:
.... enclosed by ''''....

The outer two single quotation marks are used to enclose the inner ones ('') that represent a single
quotation mark (').
If the character specified by ascii_char is included in the column value, the character will be escaped
again when the column value is exported. For example, if the specified character is the double quotation
mark (") which is included in the column value 1"1, the value will be exported as "1""1".

Examples
Import data from a file places_backup to a table places_new.
-- Create the file places_backup in the /gaussdb/backup directory:
|1|,|address_aa|,|0001|,|xian|,|shanxi|,|01|
|2|,|address_bb|,|0002|,|hangzhou|,|zhejiang|,|02|
|3|,|address_cc|,|0003|,|chengdu|,|sichuan|,|03|
|4|,|address_dd|,|0004|,|shenzhen|,|guangdong|,|04|
-- Create the table places_new:
CREATE TABLE places_new(place_id number(4,0),
STREET_ADDRESS VARCHAR(40),
POSTAL_CODE VARCHAR(12),
CITY VARCHAR(64),
STATE_PROVINCE VARCHAR(25),
STATE_ID CHAR(2)
);
-- Import places_backup to places_new:
LOAD DATA INFILE "/gaussdb/backup/places_backup" INTO TABLE places_new FIELDS
ENCLOSED BY '|' ;
Complete the data load.
4 rows are totally read.
0 rows are ignored.
4 rows are loaded into table.
4 rows are committed into table.

2.2.11 Logically Exporting Data

Description
EXP logically exports data from a database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Precautions
l When EXP is used to export data, SQL statements are assembled on the client before
being sent to a server, which then receives complete, specific DDL and DML statements.
l The client operation log is specified by the LOG parameter and records the EXP
command.
l The server audit log {GSDB_DATA}/log/audit records the DDL and DML statements.
l User SYS cannot be used to logically export data.
l Users must have required operation permissions to objects which will be logically
exported.
l EXP uses the -h parameter, help parameter, or option parameter, and ends with ;. or /.
Help information about the EXP command can be displayed.
l If FILETYPE=BIN is set, the following three types of files are exported: metadata files
(specified by users), data files (.D files), and LOB files (.L files).
l When data is logically exported, a metadata file and a data subdirectory are generated in
the specified export file path. If no file path is specified, they are generated in the current
path by default. If FILETYPE=BIN is set, the generated subfiles (data files and LOB
files) will be stored in the data subdirectory. If the specified metadata file and the
generated subfiles already exist, an error will be reported.
l If a file with the same name exists in the target directory when data is logically exported,
the system overwrites the existing file without any prompt.

Syntax
{EXP | EXPORT}[ keyword =param [ , ... ] ] [ ... ];

Parameters
l EXP
Specifies the command for logical export. It is equivalent to EXPORT.
l keyword
Specifies the keyword for logical export.
– USERS
Specifies users whose data is to be exported. Multiple users are separated by
commas (,), and % indicates all users.
No user can export data of user SYS, but user SYS can export the data of other
users. Common users must have the DBA role to export data of specified users.
Common users can export their own data only when they have the SELECT ANY
TABLE or READ ANY TABLE permission.
– TABLES
Specifies the tables to be exported. Multiple tables are separated by commas (,), and
% indicates all tables.
– DIST_RULES
Specifies distribution rules of exported data. Multiple rules are separated by
commas (,), and % indicates all rules.
This parameter is used only when GaussDB 100 is deployed in distributed mode.
– FILE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Specifies the file that stores exported data. The value is a file name and its full path,
enclosed with double quotation marks (""). If the path is not specified, the file will
be stored in the current directory where the command is executed.
– FILETYPE
Specifies the type of the files that store exported data.
The value can be TXT or BIN.
(The default value is TXT.)
– LOG
Specifies the name and path of the log file generated during logical export. The
value must be enclosed with double quotation marks ("").
– COMPRESS
Specifies a compression level for data export.
Value range: [0,9]. 0 indicates no compression, and level 9 indicates the highest
compression ratio.
Default value: 0
– CONTENT
Specifies whether to export table data or table definitions.
Valid value:
n ALL: Export both.
n DATA_ONLY: Export only data.
n METADATA_ONLY: Export only table definitions.
Default value: ALL
– QUERY
Specifies the query condition for exporting a table. The value must be enclosed with
double quotation marks (""), for example, "where rownum <= 10".
– SKIP_COMMENTS
Specifies whether to add comments when exporting DDL.
Valid value:
n Y: Add comments.
n N: Do not add comments.
Default value: N
– FORCE
Specifies whether to export the next object when an error occurs.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N
– SKIP_ADD_DROP_TABLE
Specifies whether to add DROP to the statement before exporting a table.
Valid value:
n Y: Do not add.
n N: Add.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Default value: N
– SKIP_TRIGGERS
Specifies whether to export triggers.
Valid value:
n Y: Do not export.
n N: Export.
Default value: N
– QUOTE_NAMES
Specifies whether to enclose exported objects with double quotation marks ("").
Valid value:
n Y: Enclose.
n N: Do not enclose.
Default value: N
– COMMIT_BATCH
Specifies the amount of data to be batch submitted.
Value range: natural number. 0 indicates that all the data in a table.
Default value: 1000
– INSERT_BATCH
Specifies the amount of data inserted by a single INSERT statement.
Value range: natural number
Default value: 1
– FEEDBACK
Specifies how many records need to be exported to trigger the display of the export
progress.
Value range: natural number 0 indicates that the progress is displayed once for a
table.
Default value: 10000, indicating the progress is displayed when 10000 records are
exported.
– PARALLEL
Specifies the number of concurrent threads. This parameter is valid only for TEXT
mode.
Value range: natural number
n A value from 2 to 16 indicates the number of concurrent threads.
n Value 1 or a value greater than 16 indicates a single thread.
Default value: 0
– CONSISTENT
Specifies whether to export the consistency of global data.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

– CREATE_USER
Specifies whether to export user definition statements, that is, DDL statements used
for creating users. This keyword must be used in conjunction with USERS.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N
– ROLE
Specifies whether to export role (non-SYS) definition statements, that is, DDL
statements used for creating roles. This keyword must be used in conjunction with
USERS.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N
– GRANT
Specifies whether to export GRANT statements of users or roles. This keyword
must be used in conjunction with USERS and ROLES.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N
– TABLESPACE
Specifies whether to export all tablespaces. Currently, exporting all tablespaces
allows for only those created by users, excluding system-reserved ones. The file
storage directory is the same as the default tablespace path of the system.
Valid value:
n Y: Export.
n N: Do not export.
Default value: N
– TABLESPACE_FILTER
Specifies the filter for specifying tablespaces. Multiple tablespaces are separated by
commas (,). The specified tablespace is used only for filtering. No creation
statement is generated. The symbol % is not supported, that is, filtering all
tablespace is not supported.
– WITH_CR_MODE
Specifies whether to add CR_MODE for exporting tables and index scripts.
Valid value:
n Y: Add.
n N: Do not add.
Default value: N

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Examples
l Export data from tab1 and tab2 of the current user.
EXP TABLES=tab1,tab2 FILE="file1.dmp";

l Export the data of users EMP, DEPT, and MGR.


EXP USERS = EMP,DEPT,MGR FILE="file1.dmp";

l Export data from RULE1 and RULE2.


EXP DIST_RULES = RULE1,RULE2 FILE="file1.dmp";

l Create a user TEST_USER and a role TEST_ROLE, grant permissions to them, and
export the user, role, and user table structure information.
-- Delete the existing user test_user:
DROP USER IF EXISTS test_user;
-- Delete the existing role test_role:
DROP ROLE test_role;
-- Create user test_user:
CREATE USER test_user IDENTIFIED BY 'huawei_123';
-- Create role test_role:
CREATE ROLE test_role IDENTIFIED BY 'exp_user123';
-- Grant permissions to test_user:
GRANT DBA TO test_user;
-- Grant permissions to test_role:
GRANT CREATE TABLE TO test_role;
-- Assign the test_role role to user test_user:
GRANT test_role TO test_user;
-- Export user test_user, role test_role, and table structure information of
the user:
EXP USERS = TEST_USER CONTENT = METADATA_ONLY CREATE_USER = Y ROLE = Y GRANT
= Y FILE = "file1.dmp";

l Export tablespaces.
EXP USERS = TEST_USER CONTENT = METADATA_ONLY TABLESPACE= Y FILE =
"file1.dmp";

l Exports data from a tablespace that is filtered out.


EXP USERS = TEST_USER TABLESPACE_FILTER = A,B FILE = "file1.dmp";

l Export data of specified users as compressed files.


EXP USERS = TEST_USER FILE = "file1.dmp" COMPRESS = 1;

2.2.12 Logically Importing Data


Description
IMP logically imports data to a database.

Precautions
l When IMP is used to import data, SQL statements are assembled on the client before
being sent to a server, which then receives complete, specific DDL and DML statements.
l The client operation log is specified by the LOG parameter and records the IMP
command.
l The server audit log {GSDB_DATA}/log/audit records the DDL and DML statements.
l When you import a .bin file and set content to DATA_ONLY or METADATA_ONLY,
the exported file must use the same content value.
l If IMP uses the -h, help, or option parameter and ends with a semicolon (;) or slash (/),
the help information about IMP will be displayed.
l User SYS cannot be used to logically import data.
l When FILETYPE is TXT, a maximum of 8 KB data of the CLOB, BLOB, TEXT, or
IMAGE type can be imported.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

l If FILETYPE is BIN, user, table, and remap cannot be selected. You can only fully
import an exported file.
l IMP can import a file from the database of an earlier version to the current database.
l If a file with the same name exists in the target directory when data is logically imported,
the system overwrites the existing file without any prompt.

Syntax
{IMP | IMPORT} [ keyword =param [ , ... ] ] [ ... ];

Parameters
l IMP
Specifies the command for logical import. It is equivalent to IMPORT.
l keyword
Specifies the keyword for logical import.
– USERS
Specifies users whose data is to be imported. Multiple users are separated by
commas (,), and % indicates all users.
A common user must have the DBA role to import data of other users (except
SYS). Common users can import their own data only when they have the required
permissions. For example, to import data for creating a table, the CREATE
TABLE permission is required.
– TABLES
Specifies the tables to be imported. Multiple tables are separated by commas (,),
and % indicates all tables.
– FILE
Specifies the file that stores imported data. The value is a file name and its full path,
enclosed with double quotation marks ("").
The file name must be specified. If no path is specified, the default path \pkg\bin\
will be used.
– LOG
Specifies the name and path of the log file generated during logical import. The
value must be enclosed with double quotation marks ("").
– FILETYPE
Specifies the type of the files that store imported data.
Valid value:
n TXT: TEXT format
n BIN: Binary format
Default value: TXT
– FULL
Specifies whether to perform a full import.
Valid value:
n Y: Perform.
n N: Do not perform.
Default value: N

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

– CONTENT
Specifies whether to import table data or table definitions.
Valid value:
n DATA_ONLY: Import only table data.
n METADATA_ONLY: Import only table definitions.
n ALL: Import both.
Default value: ALL
– REMAP_SCHEMA
Specifies schema mapping. For example, to import data from users A, B, C to user
D, REMAP_SCHEMA will be A,B,C:D.
n SHOW
Specifies whether to print SQL statements or import them.
Valid value:
○ Y: Print but do not import.
○ N: Import but do not print.
Default value: N
n FEEDBACK
Specifies how many records need to be imported to trigger the display of the
import progress.
Value range: natural number
Default value: 10000
n IGNORE
Specifies whether to execute the next statement when a statement fails to be
executed.
Valid value:
○ Y: Execute.
○ N: Do not execute.
Default value: N
n REMAP_TABLESPACE
Specifies tablespace mapping. For example, to import data from tablespace A
to tablespace B, REMAP_TABLESPACE will be A: B. Use commas (,) to
separate multiple mapping relationships.
n CREATE_USER
Specifies whether to import user definition statements, that is, DDL statements
for creating users.
Valid value:
○ Y: Import.
○ N: Do not import.
Default value: N
n PARALLEL
Specifies the number of parallel DML statements.
Value range: [1,32]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Default value: 1
n DDL_PARALLEL
Specifies the number of parallel DDL statements.
Value range: [1,32]
Default value: 1
n NOLOGGING
Specifies whether to enable nologging of redo logs. Only the bin format is
supported.
Valid value:
○ Y: Enable.
○ N: Disable.
Default value: N
n TIMING
Specifies whether to print the timing statistics about the import.
Valid value:
○ ON: Print.
○ OFF: Do not print.
Default value: OFF
n BATCH_COUNT
Specifies the number of rows to be imported in each batch. This parameter
takes effect only if filetype=bin is set.
Value range: [1,10000]
Default value: 10000

Examples
l Import data from tab1 and tab2 of the current user.
IMP TABLES=tab1,tab2 FILE="file1.dmp";

l Import the data of users EMP, DEPT, and MGR.


IMP USERS=EMP,DEPT,MGR FILE="file1.dmp";

l Import only the table structure.


IMP USERS=TEST_USER CONTENT=METADATA_ONLY FILE = "file1.dmp";

l Import only user data.


IMP USERS=USR1,USR2 FILE="file1.dmp" CONTENT=DATA_ONLY;

2.2.13 Generating an Analysis Report


Scenario
Workload Statistics Report (WSR) is provided to generate performance analysis reports. By
default, only user SYS has permission to perform related operations. If a common user wants
to use WSR, it must be authorized by user SYS through grant statistics to user;, which
grants the statistics role to the common user. After grating, the common user has the
permission to create snapshots, delete snapshots, view snapshots, and generate WSR reports.
However, it has no permission to change WSR parameters. When a common user performs an
operation, it must carry SYS to execute the corresponding stored procedure, for example,
CALL SYS.WSR$CREATE_SNAPSHOT;.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Procedure
Step 1 Use zsql to log in to a database as user SYS.
zsql SYS/database_123@127.0.0.1:1888

Or
zsql / as SYSDBA

Step 2 (Optional) Execute WSR to obtain help information.


WSR
The syntax of generating a WSR report is as follows:

Format: WSR snap_id1 snap_id2 "FILENAME"


snap_id1 and snap_id2 indicate the IDs of the start and end snapshots,
respectively. FILENAME is optional.
You can create a snapshot using the WSR$CREATE_SNAPSHOT stored procedure and
obtain snapshot IDs from the adm_hist_snapshot system view.
You can drop snapshots using the WSR$DROP_SNAPSHOT_RANGE stored procedure and
obtain the latest 20 snapshot IDs by running the WSR list command.
Example1: WSR 10 20
Use snapshot 10 and snapshot 20 to generate a report, with a default report name.
Example2: WSR 10 20 "e:\wsr.html"
Use snapshot 10 and snapshot 20 to generate a report, with a specified report
name.
Example3: WSR list
Obtain information about the latest 20 snapshots.
Example4: CALL WSR$CREATE_SNAPSHOT;
Create a snapshot.
Example5: CALL WSR$DROP_SNAPSHOT_RANGE(10, 20);
Drop snapshots from snapshot 10 to snapshot 20.
Note: For WSR, the values of the SQL_STAT and TIMED_STATS system parameters are
true.

Step 3 Run WSR LIST to obtain the snapshot IDs corresponding to the two time points.
WSR LIST
Listing the lastest Completed Snapshots
Snap Id Snap Started DB_startup_time
--------------- ------------------- ------------------
2 2018-09-21 17:11:20 2018-09-20 11:44:36
1 2018-09-21 17:11:14 2018-09-20 11:44:36

NOTE

l The system automatically generates snapshots. To manually create a snapshot, run the following
command:
CALL WSR$CREATE_SNAPSHOT;
l For details about how to delete a snapshot, see Deleting a Specified Snapshot.
l To modify the WSR configuration, use the WSR$MODIFY_SETTING stored procedure. For
details, see Table 2-5.
l A unique snapshot ID is generated for either an automatically or manually created snapshot. A
generated snapshot can be operated based on the ID. The ID is automatically generated when the
global sequence SNAP_ID$ is created. The minimum value is 1 and the value increments by 1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Table 2-5 WSR configuration information


WSR Unit and Configuration Modification
Configuration Value Command Command Example

Whether to Valid value: SELECT STATUS call WSR


automatically l Y: automatic from $MODIFY_SETTING(S
collect snapshots collection ADM_HIST_WR_ TR_IN_STATUS=> 'Y');
CONTROL;
l N: non-
automatic
collection
Unit: number
Default value:
Y

Interval for Value range: [5, SELECT call WSR


automatically 1440] SNAP_INTERVAL $MODIFY_SETTING(I_
generating Unit: minute from IN_INTERVAL_MINUT
snapshots ADM_HIST_WR_ ES => 30);
Default value: CONTROL;
30 minutes
The parameter
value must be an
integer.

Retention days for a Value range: [1, SELECT call WSR


snapshot 3000] RETENTION from $MODIFY_SETTING(I_
Unit: day ADM_HIST_WR_ IN_RETENTION_DAYS
CONTROL; => 30);
Default value: 2
days
The parameter
value must be an
integer.

Number of top SQL Value range: [1, SELECT call WSR


statements in the 1000] TOPNSQL from $MODIFY_SETTING(I_
report Unit: number ADM_HIST_WR_ IN_TOPSQL=> 100);
CONTROL;
Default value:
200
The parameter
value must be an
integer.

Step 4 Generate a performance analysis report.


WSR 1 2 "/export/home/gaussdba/wsr12.html"

WSR report file name : /export/home/gaussdba/wsr12.html


WSR report Generation Success.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

NOTE

l The path where the analysis report is generated can be modified based on site requirements, and the
modifier must have write permission for the path.
l When a performance analysis report is generated, a smaller snapshot ID must be placed before a
larger snapshot ID. Otherwise, the error "GS-00601, [1:3]sql syntax error: start_snap_id is greater
than end_snap_id!" will be reported and the message "WSR Report Build failed." will be returned.

----End

2.2.14 Other Functions

Deleting a Specified Snapshot


call WSR$DROP_SNAPSHOT_RANGE(n,m);

l n: ID of the start snapshot to be deleted


l m: ID of the end snapshot to be deleted

WSR-related Views
ADM_HIST_SNAPSHOT: historical snapshot information

ADM_HIST_WR_CONTROL: WSR configurations

ADM_HIST_SYSSTAT: DV_SYS_STATS snapshot information

ADM_HIST_SYSTEM: DV_SYSTEM snapshot information

ADM_HIST_SYSTEM_EVENT: DV_SYS_EVENTS snapshot information

ADM_HIST_SQLAREA: DV_SQLS snapshot information

ADM_HIST_PARAMETER: DV_PARAMETERS snapshot information

ADM_HIST_WAITSTAT: DV_WAIT_STATS snapshot information

ADM_HIST_LATCH: DV_LATCHS snapshot information

ADM_HIST_LIBRARYCACHE: DV_LIBRARY_CACHE snapshot information

ADM_HIST_SEGMENT: DV_SEGMENT_STATS snapshot information

ADM_HIST_DBASEGMENTS: ADM_SEGMENTS snapshot information

ADM_JOBS: snapshot-related job information

WSR-related Stored Procedures


WSR$DROP_SNAPSHOT_RANGE: snapshot deletion by snapshot ID range

WSR$DROP_SNAPSHOT_TIME: snapshot deletion by retention period

WSR$CREATE_SNAPSHOT: snapshot creation

WSR$MODIFY_SETTING: WSR configuration modification

WSR$INSERT_SQL_LIST: used internally to generate an SQL text list

WSR$DROP_SNAPSHOT_PARTITION: used internally to delete a table partition

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

SSL Security Notification in Interaction Mode


l Description
When the zsql client detects that no SSL CA certificate is configured on the local end, it
generates an alarm in man-machine interaction screens and asks the user whether to
continue.
l Procedure
Assume that no SSL CA certificate is configured and the zsql client is connected to a
server.
-- Keep the connection to the server:
[root@localhost linux]$ zsql gaussdba/database_123@127.0.0.1:1888

Warning: SSL connection to server without CA certificate is insecure.


Continue anyway? (y/n):Y
connected.

-- Disconnect from the server and log out zsql:


[root@localhost linux]$ zsql gaussdba/database_123@127.0.0.1:1888

Warning: SSL connection to server without CA certificate is insecure.


Continue anyway? (y/n):n
[root@localhost linux]

-- Confirm the timeout, enabling zsql to automatically log out:


[zongchao@localhost linux]$ zsql gaussdba/database_123@127.0.0.1:1888

Warning: SSL connection to server without CA certificate is insecure.


Continue anyway? (y/n):
Confirming SSL connection without CA certificate has timed out.

l ZSQL_INTERACTION_TIMEOUT specifies the timeout period for SSL security


interaction. Its default value is 5s.
You can set the period using either of the following methods: (parameter priority:
configuration file > environment variable)
Method 1: Configure the file zsql.ini in the following format:
ZSQL_INTERACTION_TIMEOUT=6

The client configuration file zsql.ini is stored in the cfg directory in the parent directory
of the zsql installation directory. For example, if the storage path of zsql is /opt/
zenith/app/bin/zsql, the storage path of the configuration file zsql.ini will be /opt/
zenith/app/cfg/zsql.ini. To ensure database security, you are advised to set the
permission for the cfg directory to 700 and that for zsql.ini to 600.
NOTE

l The zsql.ini file needs to be created by users and stored in the cfg directory in the parent
directory of the zsql installation directory.
l The default value of ZSQL_INTERACTION_TIMEOUT is 5. If zsql.ini has the
ZSQL_INTERACTION_TIMEOUT parameter incorrectly set or missing, the default value
will be used.
Method 2: Configure a zsql environment variable
ZSQL_INTERACTION_TIMEOUT.
export ZSQL_INTERACTION_TIMEOUT=6

l Method of Shielding Interaction In Non-Human-Machine Interaction Scenarios


When zsql is directly invoked by installation and continuous integration test scripts, zsql
interaction needs to be shielded to avoid affecting normal functions. The following three
methods are available (parameter priority: command line parameter > configuration file
> environment variable):

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

Method 1: Run the zsql command by using the -q parameter, which indicates quiet
(silent).
Method 2: Configure the file zsql.ini in the following format:
ZSQL_SSL_QUIET=TRUE

The client configuration file zsql.ini is stored in the cfg directory in the parent directory
of the zsql installation directory. For example, if the zsql directory is /opt/
zenith/app/bin/zsql, the configuration file directory will be /opt/zenith/app/cfg/zsql.ini.
To ensure database security, you are advised to set the permission for the cfg directory to
700 and that for zsql.ini to 600.
NOTE

l The zsql.ini file needs to be created by users and stored in the cfg directory in the parent
directory of the zsql installation directory.
l The default value of ZSQL_SSL_QUIET is FALSE. If zsql.ini has the ZSQL_SSL_QUIET
parameter incorrectly set or missing, the default value will be used.
Method 3: Configure a zsql environment variable ZSQL_SSL_QUIET (silent zsql
startup).
export ZSQL_SSL_QUIET=TRUE

HA Rebuilding
l Description
HA rebuilding helps restore a standby node from its primary node.
l Rebuilding mode
Currently, only full rebuilding is supported.
– All data files and log files on a standby node need to be deleted, but the
configuration files and data file directories must be retained.
– The rebuilding command copies data from the primary node to the standby node.
After the rebuilding is complete, the primary and standby nodes will have the same
data files.
l Prerequisites
HA has been correctly configured.
l Related concepts
– HA rebuilding is needed upon initial HA configuration to ensure database
consistency between primary and standby nodes.
– HA rebuilding is needed if primary and standby nodes are not synchronized.
l Procedure
a. Configure primary-standby links in configuration files.
n LSNR_ADDR indicates an IP address for listening.
n REPL_PORT indicates a port for copying data between primary and standby
nodes.
n ARCHIVE_DEST_2 = SERVICE indicates a peer link.
For example:
On the primary node:
LSNR_ADDR = 127.0.0.1,172.16.1.123
REPL_PORT = 15401
ARCHIVE_DEST_2 = SERVICE=172.16.1.124:15401 SYNC

On the standby node:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

LSNR_ADDR = 127.0.0.1,172.16.1.124
REPL_PORT = 15401
ARCHIVE_DEST_2 = SERVICE=172.16.1.123:15401 SYNC

b. Create a database on the primary node.


c. Start the standby node in the NOMOUNT state.
d. Run the SQL statement BUILD DATABASE to connect to the standby node
through zsql.

COL
l Description
COL sets the width of a column.
l Syntax
-- Clear a column format:
COLUMN|COL clear;
-- Set a column width:
COLUMN|COL column_name FOR|FORMAT A{column_width};
-- Enable or disable column width settings:
COLUMN|COL column_name ON | OFF ;

l Parameters
– column_name
Column name
– column_width
Column width
NOTE

l By default, the width of a column is set to the default width supported by the zsql tool.
l ON and OFF mean enabling and disabling column width settings, respectively.
l Examples
COL F1 FOR A12

WHENEVER
l Description
WHENEVER determines whether to continue or exit a connection when there is a script
running error. This function is disabled by default. If COMMIT or ROLLBACK is not
specified when WHENEVER is enabled, the default value ROLLBACK will be used.
l Syntax
WHENEVER SQLERROR
{ CONTINUE [ COMMIT | ROLLBACK ]
| EXIT [ COMMIT | ROLLBACK ] }

l Examples
-- Perform a rollback and exit if there is an error:
whenever sqlerror exit rollback
-- Query a table that does not exist:
select 1 from sys_dummy;

2.2.15 Exiting zsql


Scenario
Run the EXIT or QUIT statement on zsql to exit the zsql tool. If EXITCOMMIT is set to
ON, the data commit operation will be triggered on the exit or quit. This ensures that data is
not lost.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
Operation Guide to Tools (Standalone) 2 Client Tools

You can also use the CLEAR statement to clear the current command line.

Examples
l Run the EXIT statement to exit the zsql tool.
EXIT

l Run the QUIT statement to exit the zsql tool.


QUIT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

3 Database Management Tools

During the use of GaussDB 100, database installation, upgrade, uninstallation, and database
O&M are required. To facilitate database maintenance, GaussDB 100 provides a set of
database management tools.

3.1 Tool Support


GaussDB 100 provides a variety of tools. You can use them to better maintain GaussDB 100.
Table 3-1 can be used for standalone deployment.

Table 3-1 GaussDB 100 standalone management tools


Tool Description

install.py install.py is a tool for installing and deploying GaussDB


100 in standalone mode. It provides the one-click
installation function.

uninstall.py in standalone mode. It provides the one-click


uninstallation function.

upgrade.py upgrade.py is used for GaussDB 100 upgrade and


downgrade in standalone mode. It is in the root directory
of the GaussDB 100 database installation package and
provides database upgrade, downgrade, and rollback
functions.

zctl.py zctl.py is a tool for controlling GaussDB 100 in


standalone mode. It provides functions such as starting a
database, stopping a database, and viewing database
status.

zencrypt zencrypt encrypts the password for user SYS in


standalone deployment, enhancing communication
security without disturbing users.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Tool Description

ztrst ztrst is a restoration tool for GaussDB 100 in standalone


mode. It can restore data of a specified schema based on
the full physical backup file in one-click mode. Backup
files and database instances can be distributed on different
servers.

The python tool autofills incomplete long parameters when parsing commands. For example,
the execution results of the python zctl.py --h, python zctl.py --he, and python zctl.py --
help commands are the same. The help information about zctl.py is returned.

3.2 install.py
Function
install.py is a tool for installing and deploying GaussDB 100 in standalone mode. It provides
the one-click installation function.

install.py mainly checks whether an installation package is integrated, whether listening IP


addresses and ports are occupied, whether system parameters are valid, and whether a
standalone database has been installed; checks the sizes of disks for installation and data
directories; decompresses an installation package to an installation directory; sets
environment variables; and creates and starts a database.

Syntax
l Show help information.
python install.py --help

l Install a standalone database.


python install.py -U user:group -R installpath -D DATADIR [-O] [-C
PARAMETER=VALUE] [-g withoutroot] [-P] [-X]

Parameter Description

Table 3-2 install.py parameters


Parameter Description

--help Shows the help page.

-U Specifies the user and user group.

-R Specifies the installation path.

-O Installs a single server without creating a database or starting it.

-D Specifies the data file path, that is, GAUSSDB.

-g Specifies a non-root user to uninstall databases. Ensure the user


has the access permission to the installation directory.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-C Specifies configuration parameters. By default, these


configurations overwrite the configuration items in the
zengine.ini file during installation.

-l Specifies the log file. The default value is /var/log/


zengineinstall.log.

-P If you disable password-free login during installation, you need


to specify this parameter at the end of the command line. During
the command execution, you will be prompted to enter the
username and password for connecting to the database. The
username is SYS, and the default password is Changeme_123. If
password-free login is enabled, you do not need to specify this
option.

-X Specifies that no compatibility package is installed. The


compatibility package is used to offer compatibility with the view
names of mainstream databases.

3.3 uninstall.py
Description
uninstall.py is a tool for installing and deploying GaussDB 100 in standalone mode. It
provides the one-click uninstallation function.

Syntax
l Show the help page.
python uninstall.py --help

l Uninstall a standalone database.


python uninstall.py -U user [-F] [-D DATADIR] [-g withoutroot] [-P]

Parameters

Table 3-3 uninstall.py parameters

Parameter Description

--help Shows the help page.

-F Deletes the data file directory.

-g Specifies a non-root user to uninstall databases. Ensure the user has the
access permission to the uninstallation directory.

-D Specifies the data file path, that is, GAUSSDATA. The path must follow
the -F parameter.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-P Specifies that the tool connects to the database using a username and a
password. During command execution, you will be prompted to enter the
username and password for connecting to the database so as to stop the
database instance. The username is SYS, and the default password is
Changeme_123. If the process instance has been stopped in advance, the
entered username and password will neither undergo correctness
verification nor be used.
This parameter can be left empty. If empty, the database can be connected
in password-free login mode.

3.4 upgrade.py
Description
upgrade.py is used for GaussDB 100 upgrade and downgrade in standalone mode. It is in the
root directory of the GaussDB 100 database installation package and provides database
upgrade, downgrade, and rollback functions. The python version of upgrade.py must be
2.7.*.

Syntax
l Show help information.
python upgrade.py --help | -?

l Perform manual upgrade.


python upgrade.py -t { upgrade-type | pretest | precheck | prepare | replace
| start | upgrade | sync | dbcheck | flush } --package=path_to_package_file --
backupdir=path_to_backup [--GSDB_HOME=path_to_gsdb_home] [--
GSDB_DATA=path_to_data_dir] [-f cmd_config_file]

l Manual downgrade
python upgrade.py -t { upgrade-type | pretest | precheck | prepare | replace
| start | upgrade | sync | restart | upgrade-view | checkpoint | dbcheck |
flush } --package=path_to_package_file --backupdir=path_to_backup [--
GSDB_HOME=path_to_gsdb_home] [--GSDB_DATA=path_to_data_dir] [-f
cmd_config_file]

l Perform manual rollback.


python upgrade.py -t { rollback-check | rollback | rollback-clean } --
backupdir=path_to_backup [--GSDB_HOME=path_to_gsdb_home] [--
GSDB_DATA=path_to_data_dir] [-f cmd_config_file]

l Check the configurations before an automatic upgrade or downgrade.


python upgrade.py -s pre-check --config-file=CONFIG_FILE [--upgrade-mode=ha|
single] [-f cmd_config_file]

l Perform an automatic upgrade or downgrade.


python upgrade.py -s run --config-file=CONFIG_FILE [--auto-rollback=true|
false] [--upgrade-mode=ha|single] [-f cmd_config_file]

l Delete the configurations after an automatic upgrade or downgrade.


python upgrade.py -s cleanup --config-file=CONFIG_FILE [--upgrade-mode=ha|
single] [-f cmd_config_file]

l Perform an automatic rollback.


python upgrade.py -s { rollback-check | rollback } --config-file=CONFIG_FILE
[--upgrade-mode=ha|single] [-f cmd_config_file]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameters

Table 3-4 upgrade.py parameters


Parameter Description

--help Shows the help page.

-t Specifies the operation to be performed.


Valid value: upgrade-type, pretest, precheck, prepare, replace, start,
upgrade, sync, restart, upgrade-view, checkpoint, dbcheck, flush,
rollback-check, rollback, rollback-clean (Only one operation can be
specified in one statement.)
This parameter is mandatory for the manual upgrade or downgrade in
HA or standalone mode and cannot be left empty.
This parameter cannot be set for the automatic upgrade or downgrade in
HA or standalone mode.

-- Specifies the installation directory where BIN and LIB files are stored.
GSDB_HOME You can enter a path.
This parameter is optional for the manual upgrade or downgrade in HA
or standalone mode. It can be left empty. If empty, the environment
variable GSDB_HOME will be used. If GSDB_HOME does not exist,
an error is reported.
This parameter cannot be set for the automatic upgrade or downgrade in
HA or standalone mode.

-- Specifies the data file directory. You can enter multiple data paths
GSDB_DATA corresponding to the same BIN file for simultaneous upgrade or
downgrade.
This parameter is optional for the manual upgrade or downgrade in HA
or standalone mode. It can be left empty. If empty, the environment
variable GSDB_DATA will be used. Only the databases whose data file
directory is specified by GSDB_DATA can be upgraded. If the
environment variable is omitted, an error will be reported.
This parameter cannot be set for the automatic upgrade or downgrade in
HA or standalone mode.

--package Specifies the installation package of the new version. You need to enter
an absolute path.
This parameter is mandatory for the manual upgrade or downgrade in
HA or standalone mode and cannot be left empty.
This parameter cannot be set for the automatic upgrade or downgrade in
HA or standalone mode.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

--backupdir Specifies the backup folder, that is, the location where the backup system
tablespace, admin, and LIB files of the old version are stored during an
upgrade or downgrade. The backup folder can be created by using
scripts.
This parameter is mandatory for the manual upgrade or downgrade in
HA or standalone mode and cannot be left empty.
This parameter cannot be set for the automatic upgrade or downgrade in
HA or standalone mode.

-P Specifies that the tool connects to the database using a username and a
password. During the command execution, you will be prompted to enter
the username and password for connecting to the database. The username
is SYS, and the default password is Changeme_123.
This parameter is available and can be left empty. If empty, the database
can be connected in password-free login mode.

--config-file Prepare the upgrade configuration file.


For an automatic upgrade or downgrade in standalone scenarios, you can
add information about only one node in the upgrade or downgrade file.
For an automatic upgrade or downgrade in HA scenarios, you need to
add information about each node. The configuration information of each
node is in a separate line, and the configuration information in the first
line must be about the node for running the upgrade command. The
configurations following the equal sign (=) must be in the following
sequence: Upgrade package path, database installation path, backup path,
data file directory of database instance
The format of the upgrade configuration file is as follows:
IP=package_path,app_path,backup_path,data_path [, ...]

l IP: IP address of a node


l package_path: absolute path of the upgrade or downgrade package
l app_path: installation path of the database
l backup_path: path for storing backup files during the upgrade or
downgrade
l data_path: database instance path. Multiple database instance paths
can be specified, and commas (,) can be used to separate them.
The following is an example of the upgrade configuration file (assume
that two nodes are involved in the database to be upgraded or
downgraded and the IP address of the upgrade command execution node
is 192.168.0.1):
192.168.0.1=/opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/home/gaussdba/app,/home/gaussdba/
backup,/home/gaussdba/data
192.168.0.2=/opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/home/gaussdba/app,/home/gaussdba/
backup,/home/gaussdba/data

This parameter cannot be set for the manual upgrade or downgrade in


HA or standalone mode.
This parameter is mandatory for the automatic upgrade or downgrade in
HA or standalone mode.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-s Specify a step in the one-click upgrade, including pre-check, run,


rollback-check, rollback, and cleanup.
This parameter cannot be set for the manual upgrade or downgrade in
HA or standalone mode.
This parameter is mandatory for the automatic upgrade or downgrade in
HA or standalone mode.

--packtype Specifies the upgrade package type.


Valid value: run and package. The default value is package.
This parameter is optional.

--upgrade- Specifies the upgrade mode.


mode Valid value: ha and single (The default value is single.)
This parameter cannot be set for the manual upgrade or downgrade in
HA or standalone mode.
This parameter is optional for the automatic upgrade or downgrade in
HA or standalone mode.

--auto-rollback Specifies whether to enable automatic rollback.


Valid value: true and false (The default value is true.)
This parameter cannot be set for the manual upgrade or downgrade in
HA or standalone mode.
This parameter is optional for the automatic upgrade or downgrade in
HA or standalone mode.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-f Specifies the path and name of a parameter configuration file.


During manual upgrade or downgrade, you can configure the --
GSDB_HOME, --GSDB_DATA, --package, --backupdir, and -P
parameters in a file. During automatic upgrade, you can configure the --
packtype, --upgrade-mode, --auto-rollabck, --config-file, and -P
parameters in a file. This file is called a parameter configuration file.
During an upgrade or downgrade, you can either specify the parameters
in the upgrade or downgrade command, or use the -f parameter to specify
the parameter configuration file. If the file is used, you do not need to
specify the parameters in the command.
Example of the parameter configuration file for manual upgrade or
downgrade:
GSDB_HOME=value
GSDB_DATA=value
package=value
backupdir=value
interactive=TRUE/FALSE

Example of the parameter configuration file for automatic upgrade or


downgrade:
packtype=run/package
upgrade-mode=ha/single
auto-rollabck=TRUE/FALSE
config-file=value
interactive=TRUE/FALSE

In the parameter configuration file, -P is represented by interactive. If -P


is specified, interactive=TRUE will be used. If -P is not specified,
interactive=FALSE will be used.
This parameter is optional.

3.5 zctl.py
Description
l zctl.py is a tool for controlling GaussDB 100 in standalone mode. It provides functions
such as starting a database, stopping a database, and viewing database status.
l zctl.py must be executed by database installation users.
l A zctl.py log is generated in the log directory of each instance. The file name format is
zctl-YYYY-MM-DD_xxxxxx.log, where YYYY is a year, MM is a month, DD is a date, and
xxxxxx is a randomly-generated six digits. For example, zctl-2018-10-01_055246.log
l zctl.py logs can be dumped, supporting a maximum of 10 log files with a size no more
than 10 MB.
l zctl.py logs record usernames and host information. If the username or host information
in a zctl log is NULL, check whether the user used non-SSH login (for example, VNC or
other login modes) or check the zctl.py execution mode.

Syntax
l Show the help page.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

python zctl.py --help

l View the database version.


python zctl.py -v

l Start a database.
python zctl.py -t start [-D DATADIR] [-m START-MODE]

l Stop a database.
python zctl.py -t stop [-D DATADIR] [-m SHUTDOWN-MODE] [-P]

l Forcibly stop a database.


python zctl.py -t kill [-D DATADIR]

l View database status.


python zctl.py -t status [-D DATADIR] [-P]

l Perform a switchover of the primary and standby databases.


python zctl.py -t switchover [-D DATADIR] [-P]

l Promote the standby database to primary.


python zctl.py -t failover [-D DATADIR] [-P]

l Rebuild the database baseline.


python zctl.py -t build [-D DATADIR] [-m BUILD-MODE] [-c] [-a ALGORITHM] [-l
LEVEL] [-P]

l Demote the primary database to standby.


python zctl.py -t demote [-D DATADIR] [-m DEMOTE-MODE] [-P]

Parameters

Table 3-5 zctl.py parameters


Parameter Description

--help Shows the help page.

-v Shows the database version.

-t Specifies the working mode for zctl.py, including start (start),


stop (stop), status (status viewing), switchover (primary/standby
switchover), failover (standby promoted to primary), build
(baseline rebuilding), demote (primary demoted to standby), and
kill (forcible stop).
NOTE
Changing a port or address online fails the system stop operation.
Therefore, you are not advised to modify current connection information
online. If the connection is abnormal or the connection information is
modified online, run the kill command to stop the instance corresponding
to a specific data directory.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-m Specifies the mode to start and stop the database, rebuild the
database baseline mode, and demote the primary database to
standby.
l In database start scenarios, -m can be set to nomount, mount,
or open. If it is not specified, value open will be used.
l In database stop scenarios, -m can be set to immediate,
abort, or normal. If it is not specified, value normal will be
used.
l When the database baseline is rebuilt, the mode can be
standby or cascaded. standby rebuilds the database as a
standby. cascaded rebuilds the database as a cascaded
standby. If -m is not specified, the rebuild mode depends on
the peer database. If the peer is a standby database, the
database is rebuilt as a cascaded standby. If the peer a primary
database, the database is rebuilt as a standby.
l When the primary database is demoted to standby, the mode
can be standby or cascaded. standby demotes the primary
database to standby. cascaded demotes the primary or standby
database to cascaded standby. If -m is not specified, the
database is demoted to standby by default.

-c Specifies compression for build. This parameter is valid only for


build.

-a Specifies a compression algorithm for compression-based build.


Currently, ZSTD, ZLIB, and LZ4 are supported. The default
value is ZSTD.

-l Specifies a compression ratio for compression-based build. The


value range is [1, 9]. The default value is 1.

-D Specifies the data file path, that is, GSDB_DATA.

-P Specifies that the tool connects to the database using a username


and a password. During the command execution, you will be
prompted to enter the username and password for connecting to
the database. The username is SYS, and the default password is
Changeme_123.
This parameter can be left empty. If empty, the database can be
connected in password-free login mode.

Table 3-6 Commands for HA scenarios


Command Scenario

switchover Performs a switchover when both primary and standby nodes are
running properly. This command is executed on a standby node.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Command Scenario

failover Promotes a standby node to primary when there is a fault on the


primary node. This command is executed on a standby node.

build (Executed on a standby node) Rebuilds the baseline when a


standby node is in the need repair state.
(Executed on a primary node) Demotes the primary node to
standby and rebuilds the baseline with the new primary node.
DANGER
If the command is executed on a primary node, ensure connections to both
the old and new primary node. Otherwise, the rebuilding will fail and data
cannot be restored.

demote Demotes a primary node to standby when the node is faulty and a
standby node has been promoted to primary by failover. This
command is executed on a primary node.

3.6 zencrypt
Description
zencrypt encrypts the password for user SYS in standalone deployment, enhancing
communication security without disturbing users. By default, zencrypt operation logs are
stored in $GSDB_HOME/log/oper. The log files are named zencrypt.olog. The number of
zencrypt logs that can be retained is 10; the maximum size of a log file is 10 MB; the log file
permission is 600; and the log directory permission is 700.

NOTE

l If the key factor (_FACTOR_KEY) is updated online, the working key (LOCAL_KEY) will be
updated synchronously. If an SSL private key password has been configured, it will also be updated
synchronously.
l You can use zencrypt -g -f <factor_key> to specify a key factor to generate a new working key, and
then update the working key by running ALTER SYSTEM or updating the configuration file.
l For security purposes, the zencrypt tool can be executed only by non-root users. If it is executed by
user root, an error will be reported. The following is an example.
"root" execution of the zencrypt tool is not permitted.

Syntax
l Show the help page.
zencrypt {-h|-H}

l Show version information.


zencrypt {-v|-V}

l Use PBKDF2 to encrypt a user password.


zencrypt {-e|-E} PBKDF2

l Use SCRAM_SHA256 to encrypt a user password.


zencrypt {-e|-E} SCRAM[_SHA256] [-i iter_count]

l Use AES256 to encrypt an SSL private key password.


zencrypt {-e|-E} AES[256] {-f|-F} factor_key {-k|-K} work_key

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

l Generate a key factor and a working key.


zencrypt {-g|-G} [{-f factor_key | -o key_file}]

Parameters

Table 3-7 zencrypt parameters


Parameter Description

-h, -H Shows the help page.

-v, -V Shows version information.

-g, -G Generates a key factor and a working key.

-e, -E Specifies an encryption algorithm. Currently, the following


algorithms are supported:
l SCRAM_SHA256: Encrypts the password of user SYS.
l AES256: Encrypts SSL private key passwords.
l PBKDF2: Encrypts the password of user SYS.

-f, -F Specifies a key factor.


This parameter is valid only when the AES-256 algorithm is used
or a working key is to be generated.

-k, -K Specifies a working key.


This parameter is valid only when the AES-256 algorithm is
used.

-o, -O Specifies a file to which the HMAC operation result of a


specified key factor is written. The file can be used to change the
default key factor during database creation.
This parameter is valid only when a key factor is to be generated.
NOTE
l The file must be stored in a path to which the current user has write
permission.
l If you change the key factor by replacing the file, you also need to
modify the LOCAL_KEY parameter in the configuration file to
ensure the key pair. The working key can be the WorkKey value
generated by the zencrypt tool.

-i Specifies the number of iterations.


This parameter is valid only when the SCRAM-SHA-256
algorithm is used to encrypt user passwords.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

3.7 ztrst
Description
ztrst is a restoration tool for GaussDB 100 in standalone mode. It can restore data of a
specified schema based on the full physical backup file in one-click mode. Backup files and
database instances can be distributed on different servers.

Syntax
l Show help information.
ztrst -h|-H

l Use the backup set to repair damaged pages in one-click mode.


ztrst -p [syspassword:]port -D export_data_path -B backup_file_path -P
page_id -S ip:port

l Restore the data of a specified schema based on the full physical backup file in one-click
mode.
ztrst -p [syspassword:]port -D export_data_path -B backup_file_path -U
schema[/passwd] -T tablespace_name -S ip:port [-C import_parameters]

Parameters

Table 3-8 ztrst parameters


Parameter Description

-h, -H Shows the help page.

-p (lowercase) Specifies the password of database user SYS and the temporary
port for restoration. The value format is syspasswd:port. The
temporary port used for restoration must be specified and the
password of user SYS is optional. If the password is not
specified, it should be entered in interactive mode.

-D Specifies the directory for storing temporary files generated


during restoration.

-B Specifies the directory of the full backup file

-U Specifies the name and password of the schema to be restored.


The value format is schema/passwd. The username of the
schema must be specified and the password of the schema is
optional. If the password is not specified, it should be entered in
interactive mode.

-T Specifies the name of the tablespace corresponding to the


schema.

-S Specifies the IP address and port number of the database


instance. The value format is IP:Port.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
Operation Guide to Tools (Standalone) 3 Database Management Tools

Parameter Description

-C Specifies import parameters. Four parameters can be set and


should be separated by commas (,):
l PARALLEL (Number of concurrent DML lines. The value
range is [1, 32]. The default value is 16.)
l DDL_PARALLEL (Number of parallel DDLs. The value
range is [1, 32]. The default value is 16.)
l NOLOGGING (Whether REDO logs are recorded. The value
can be 0 or 1. The value 0 indicates that redo logs are
recorded, and 1 indicates that redo logs are not recorded. The
default value is 0.)
l BATCH_COUNT (Number of data rows imported in each
batch. The value range is [1,10000]. The default value is
10000.)
The format is as follows:
PARALLEL=8,DDL_PARALLEL=8,NOLOGGING=0,BATCH_COUNT=10000

-P (uppercase) Specifies the ID of the page to be repaired. The value format is


datafile_page. For example, 3_44 indicates page 44 in data file
3.

Configuring Environment Variables


After the ztrst tool is decompressed and installed, you need to configure the environment
variable LD_LIBRARY_PATH and PATH to ensure that the ztrst tool can be started and
used normally.
Add the lib and add-ons paths in the tool package to the environment variable
LD_LIBRARY_PATH.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/ztrstdba/GaussDB100-V300R001C00-
RESTORE/lib:/home/ztrstdba/GAUSSDB100-V300R001C00-RESTORE/add-ons

Add the bin path in the tool package to the environment variable PATH.
export PATH=$PATH:/home/ztrstdba/GAUSSDB100-V300R001C00-RESTORE/bin

If you do not add the bin path in the tool package to the environment variable PATH, the
format for using the ztrst tool in the bin path of the tool will be ./ztrst. If you add the path,
the format will be ztrst or ./ztrst.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
Operation Guide to Tools (Standalone) 4 Tools Used in the System

4 Tools Used in the System

This chapter describes tools used in GaussDB 100 processes or invoked among modules.
These tools are used only for internal invoking and their accuracy in other scenarios has not
been verified. Therefore, you are not advised to execute tasks by directly using these tools to
avoid impact on the system.

4.1 sql_process.py
Description
sql_process.py is used to generate SQL files for standalone GaussDB 100 upgrades. It
compares the initdb.sql files of old and new versions to locate the differences in system
catalogs and generates SQL files for upgrading the system catalogs. The sql_process.py
version must be 2.7.*.

Syntax
l Show the help page.
python sql_process.py -?|--help

l Generate an upgrade SQL file.


python sql_process.py -t generate --new-initdb=NEW_INITDB_SQL_FILE --old-
initdb=OLD_INITDB_SQL_FILE --outdir=OUT_DIR

Parameters

Table 4-1 sql_process.py parameters


Parameter Description

--help Shows the help page.

-t Specifies the function to be executed, including generate. Only one


function can be specified in a single command. You must assign a value
to this parameter.

--new-initdb Specifies the name of the initdb.sql file of the new version. It is an
absolute path. You must assign a value to this parameter.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
Operation Guide to Tools (Standalone) 4 Tools Used in the System

Parameter Description

--old-initdb Specifies the name of the initdb.sql file of the old version. It is an
absolute path. You must assign a value to this parameter.

--outdir Specifies the output folder of SQL files used for the upgrade. You must
assign a value to this parameter.

4.2 zengine
Description
zengine is an internal tool. It starts a database, and you are not advised to use it directly.

Syntax
l Show the help page.
zengine [-h|-H]

l View the database version.


zengine [-v|-V]

l Start the database whose data file path is GSDB_DATA.


If GSDB_DATA is not configured, the current path is used as the data path.
zengine [mode]

l Start the database with a specified data file path.


zengine [mode] -D db_home_path

l Start the database in CN or DN mode.


If no startup modes are specified, the database is started in OPEN mode.
zengine [mount/open] node_type -D db_home_path

Parameters
l -h/-H
Obtains help information.
l -v/-V
Obtains version information.
l mode
Specifies the startup mode. Its value can be NOMOUNT, MOUNT, or OPEN. This
parameter is optional. If no startup modes are specified, the database is started in OPEN
mode.
l db_home_path
Specifies the GSDB_HOME path.
l node_type
(Valid only in distributed deployment) Specifies the start mode of a database instance.
The value can be --coordinator or --datanode. --coordinator indicates that a database
CN is started, and --datanode indicates that a database DN is started.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
Operation Guide to Tools (Standalone) 4 Tools Used in the System

4.3 shutdowndb.sh
Description
shutdowndb.sh is a script for graceful shutdown. You are not advised to use it directly.

Syntax
shutdowndb.sh -h HOSTIP -p PORT -U SYS -w|-W -m IMMEDIATE|NORMAL|ABORT [-D
GSDB_DATADIR]

Parameters
l -h/--host
Specifies a database host.
l -p/--port
Specifies a port.
l -U/--username
Specifies a database user.
l -W/--password
Specifies a password for the user. You must enter both the username and password for
login.
l -w/--no-password
Specifies password-free login.
l -D/--data-directory
Specifies an instance data directory when an OS user installs multiple database instances.
This parameter can be skipped if username- and password-based login is used.
l -m
Specifies the stop mode, supporting IMMEDIATE, NORMAL, and ABORT. The
value must be all uppercase or lowercase.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

5 Interface Mapping (Basic Packages vs.


Compatible Packages)

5.1 Data Dictionary Tables


Table 5-1 Name mapping of data dictionary tables (basic packages vs. compatible packages)
Basic Package Compatible Package

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

5.2 DBA Views


Table 5-2 Name mapping of DBA views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

5.3 User Views


Table 5-3 Name mapping of user views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_ARGUMENTS ALL_ARGUMENTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

5.4 Dynamic Performance Views


Table 5-4 Name mapping of dynamic performance views (basic packages vs. compatible
packages)
Basic Package Compatible Package

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100 5 Interface Mapping (Basic Packages vs. Compatible
Operation Guide to Tools (Standalone) Packages)

Basic Package Compatible Package

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 70


GaussDB 100
Operation Guide to Tools (Standalone) 6 Glossary

6 Glossary

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 71


GaussDB 100
V300R001C00

Product Description (Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Product Description (Standalone) About This Document

About This Document

Overview
GaussDB 100 is a high-performance and high-reliability relational disk database developed by
Huawei Technologies Co., Ltd.

This document describes the positioning, characteristics, system architecture, basic features
and enterprise-level enhanced features, application scenarios, operating environment, and
technical specifications of the standalone GaussDB 100.

Intended Audience
This document is intended for the personnel who need to have an overall knowledge of
GaussDB 100, such as application product planning personnel and system architects.

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not avoided, will


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in equipment damage, data loss, performance deterioration, or
unanticipated results.
NOTICE is used to address practices not related to personal injury.

Calls attention to important information, best practices, and tips.


NOTE is used to address information not related to personal injury,
equipment damage, and environment deterioration.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Product Description (Standalone) About This Document

Change History
Version Change Date
Description

03 This issue is the third 2019-06-06


official release.

02 This issue is the 2019-04-05


second official
release.

01 This issue is the first 2018-10-30


official release.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Product Description (Standalone) Contents

Contents

About This Document.....................................................................................................................ii


1 Product Positioning.......................................................................................................................1
2 Product Features.............................................................................................................................3
3 System Architecture...................................................................................................................... 5
4 Typical Application Scenarios.................................................................................................... 9
5 Basic Functions and Features.................................................................................................... 11
6 Enterprise-Level Enhanced Features........................................................................................12
6.1 Syntax Compatibility With Multiple Databases........................................................................................................... 12
6.2 High Availability with RTO ≈ 0................................................................................................................................... 12
6.3 Enterprise-Level Security Assurance........................................................................................................................... 13
6.4 Logical replication........................................................................................................................................................ 15
6.5 Huawei-Developed High-Performance Database Kernel.............................................................................................16
6.6 E2E Tool Chain.............................................................................................................................................................16
6.7 ARM Chips and Huawei EulerOS................................................................................................................................17

7 Technical Specifications.............................................................................................................18
8 Running Environment................................................................................................................ 20
9 Standards Compliance................................................................................................................21
10 Glossary....................................................................................................................................... 22

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
Product Description (Standalone) 1 Product Positioning

1 Product Positioning

A relational database is an important part of an end-to-end solution and satisfies the


requirements of on-line transaction processing for data storage and access. Traditional
relational databases for commercial use have mature enterprise-level capabilities. However,
their technical architecture is relatively closed, requirement response is slow, and procurement
and maintenance costs remain high. In addition, open source databases have the kernel
capabilities at different levels and insufficient technology and O&M support, which cannot
meet the requirements of key services in high-load scenarios.
GaussDB 100, an enterprise-level high-performance and high-availability relational database,
adopts the self-developed database kernel architecture. The technology is independent and
controllable, providing quick response and sufficient O&M support. It supports SQL:2003
and is compatible with SQL syntax of mainstream commercial databases, greatly reducing the
technology and time costs caused by database migration. The powerful self-developed
database kernel and various enterprise-level enhanced features meet the data storage and
access requirements of service systems in large and medium enterprises (especially the core
service systems in fields, such as finance and telecom). It is the best choice as an enterprise-
level OLTP relational database.
GaussDB 100 can be deployed in standalone or cluster mode. This document describes the
database capabilities in standalone mode. The standalone database can be deployed in
primary/standby mode and provides a complete set of solutions, such as data migration,
O&M, disaster recovery (DR), and backup and restoration.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Product Description (Standalone) 1 Product Positioning

Figure 1-1 Application scenarios

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Product Description (Standalone) 2 Product Features

2 Product Features

High performance
l Concurrency control
In GaussDB 100, a series of concurrency control mechanisms, such as multi-level read/
write locks, multi-version concurrency control (MVCC), and transaction isolation levels,
are used for high concurrent access on the premise of data consistency.
Row-level MVCC based on timestamps and rollback segments supports data query and
modification without blocking each other, greatly improving the performance of
concurrent query and modification.
l Query optimization
In GaussDB 100, the built-in rule-based optimizer (RBO) and cost-based optimizer
(CBO) provide hints to generate optimal execution plans.
High reliability
l Primary/standby replication and switchover
GaussDB 100 generates redo logs on the primary server and replay the logs on the
standby servers to ensure data consistency between the primary and standby servers. In
addition, primary/standby switchover is used for high availability (HA).
l Logical replication
GaussDB 100 provides logical replication independent from physical logs to synchronize
data between GaussDB 100 in different versions and between GaussDB 100 and other
heterogeneous databases. Logical replication can be used for incremental data backup
from the primary to standby databases, data synchronization between different service
systems, online data migration during the upgrade without service interruption, and other
operations.
l Flashback and recycle bin
GaussDB 100 provides flashback and a recycle bin. You can specify a timestamp to
perform flashback query, or to flash back table data that is incorrectly deleted or updated.
After being flashed back from the recycle bin, table data can be quickly restored to the
state before an error event. This greatly improves user data reliability and prevents
service interruption caused by point-in-time recovery (PITR).
Large capacity
In GaussDB 100, a single node supports a maximum of 8 PB storage capacity and a single
table supports a maximum of 7.8 TB. In addition, you can create bigfile tablespaces to

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Product Description (Standalone) 2 Product Features

simplify storage O&M. A bigfile tablespace can be created to store files with large capacity,
which significantly reduces the number of data files in the database.
Proper compatibility with SQL
GaussDB 100 supports the SQL:2003 standard and partially supports SQL:2006, SQL:2008,
SQL:2011, and SQL:2016. In addition, it supports the syntax that is widely used in
mainstream commercial databases to greatly reduce the cost of migrating data from other
commercial databases to GaussDB 100.
High maintainability
The kernel status of GaussDB 100 is transparent, O&M methods are diverse, and enterprise-
level O&M capabilities are provided. The built-in performance views cover various key
performance indicators, such as waiting events, transaction status, session status, slow SQL
statements, space statistics, and memory statistics. Comprehensive load statistics reports are
provided, covering instance load overview, instance efficiency percentage, and top 10
background events.
High security
For data security purposes, GaussDB 100 provides access control, password protection,
permission management, data encryption, sensitive data masking, connection encryption, and
operation auditing.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Product Description (Standalone) 3 System Architecture

3 System Architecture

The standalone GaussDB 100 adopts a layered architecture. Applications access data through
standard database interfaces, such as JDBC and ODBC. Dual-host hot backup is supported.
Standby servers synchronize with the primary server by replaying redo logs. Data on the
standby servers is read-only. The following figure shows the system architecture.

Figure 3-1 System architecture

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Product Description (Standalone) 3 System Architecture

Table 3-1 Logical architecture description


Name Description

Connection Distributes and manages client requests.


management

SQL engine Parses SQL statements, optimizes SQL execution plans, invokes the
storage layer, and returns results.

Storage engine Manages and permanently stores data.

HA module Backs up data on the primary server in quasi-real-time and replays the
data on standby servers.

CLI Command line interface (CLI) tools used for database management,
management and including the tools for system start/stop, database initialization, SQL
maintenance execution, parameter configuration, and backup and restoration
tool set

Monitoring and WebUI-based tools used for monitoring and managing database running
management status
tools

Development Browses and manages database objects, executes and commissions


tool set SQL statements, and collects statistics about the code coverage in
stored procedure tests.

SQL SQL performance audit tool, SQL execution workload statistics reports
performance (WSRs), views for SQL execution plan analysis and dynamic
diagnosis tool performance statistics collection.
set

Standard data JDBC, ODBC, C-API, and Python-API


access interfaces

GaussDB 100 Kernel Architecture


GaussDB 100 adopts an enterprise-level kernel architecture developed by Huawei. For details
about the architecture, see Figure 3-2.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Product Description (Standalone) 3 System Architecture

Figure 3-2 GaussDB 100 Kernel Architecture

Table 3-2 Kernel architecture description

Name Description

Thread Listening thread Processes client requests, supporting the TCP and IPC
protocols.

Work thread pool Efficiently manages the scheduling of internal work


threads, avoiding the overhead of thread creation and
destruction.

Redo log Writes logs in buffers into disks.

Checkpoint Permanently writes dirty pages into to disks and updates


control files.

Monitoring Monitors the system status, for example, deadlock, and


rectifies abnormal sessions.

Scheduled task Manages scheduled tasks.

Archiving Archives log files.

Log replication Replicates logs for HA and GR.

Buffer Redo log buffer Global log buffer

Data buffer Global data page buffer

SQL cache Global execution plan buffer

Session pool Session buffer pool

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Product Description (Standalone) 3 System Architecture

Name Description

Private area Private buffer

Sort area Global sorting/materialization buffer

Data dictionary Global data dictionary (metadata) buffer


cache

File type Data files Store data such as tables, indexes, and rollback data of
(including the database.
temporary files)

Redo log files Online redo log files store write ahead logs (WAL)
generated by the database. At least three redo log files are
used cyclically.
If archive is enabled and an online redo log is switched,
the log file will be archived to a specified directory for
database restoration.

Control files Store key control information of the database, such as


configurations of data files, redo log files, and
tablespaces.

Alarm log files Store the alarms generated during database running.

Audit log files Store records of historical operations in the database. The
records can be traced and audit logs can be disabled.

Run log files Store key information about database running.

Performance Automatically collect application load information for


diagnosis log files performance diagnosis.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Product Description (Standalone) 4 Typical Application Scenarios

4 Typical Application Scenarios

GaussDB 100, a common relational database, can be used for online transaction processing in
various service scenarios, especially in scenarios where the requirements of data storage
access performance and reliability are high, such as telecom and finance services.
GaussDB 100 provides multiple networking modes to meet different requirements of data
capacity, processing performance, and reliability. The network modes include but are not
limited to standalone deployment, primary/standby deployment, and primary/standby HA
deployment based on RDMA hardware.
The following figure shows the use of GaussDB 100 on the OSS platform. The database is
deployed in primary/hot standby mode based on service requirements.

Figure 4-1 GaussDB 100 on the OSS platform

GaussDB 100 synchronously or asynchronously replicates redo logs from the primary server
to standby servers and replay the logs on the standby servers to ensure data consistency
between the primary and standby servers. When a fault occurs on the primary server,

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Product Description (Standalone) 4 Typical Application Scenarios

GaussDB 100 quickly switches services to a standby server. OSS software accesses the
database through a standard interface and a floating IP address. In this way, GaussDB 100 is
unaware of the primary/standby switchover.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Product Description (Standalone) 5 Basic Functions and Features

5 Basic Functions and Features

GaussDB 100, a common relational database, can provide the basic functions and features of
a standard relational database.

l Standard SQL
Supports the SQL:2003 standard and partially supports SQL:2006, SQL:2008, SQL:
2011, and SQL:2016.
l Character set
Supports the UTF-8 character set.
l Database storage management
Supports tablespaces.
l Transaction
Supports atomicity, consistency, isolation, and durability (ACID) and two transaction
isolation levels: Read Committed, Serializable, Read Current Committed.
l Data node HA
Supports primary/standby replication and failover.
l Standard application access interface
Supports ODBC 2.0 and JDBC 4.0.
l Multiple programming languages
Supports C, Java, and Python.
l SQL optimization
Supports RBO, CBO, and hints.
l Data export and import
Provides tools for quick, parallel data export and import.
l Management tool
Provides installation and deployment tools, client tools, status monitoring tools, backup
and restoration tools, and upgrade tools.
l Security management
Supports SSL Internet connections, user permission management, password
management, and security audit, to ensure data security at the management, application,
system, and Internet layers.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

6 Enterprise-Level Enhanced Features

6.1 Syntax Compatibility With Multiple Databases


GaussDB 100 supports the SQL:2003 standard and service applications that comply with this
standard can be seamlessly migrated to GaussDB 100. In addition, this greatly reduces the
learning costs of application developers and shortens the development period of new services.
Service applications constructed based on mainstream commercial databases also use objects
and syntax specific to the database, such as data types, built-in functions, SQL syntax, and
views. GaussDB 100 is fully compatible with the features widely used by service
applications. In this way, application code can be quickly migrated to GaussDB 100 with
minimum modification.

6.2 High Availability with RTO ≈ 0


Recovery Time Objective (RTO) refers to the duration between the database system failure
caused by a disaster and its restoration to proper running. GaussDB 100 provides industry-
leading Global Buffer Pool (GBP) to shorten the time for promoting the standby server to
primary and reduce the impact of exceptions on service applications. The RTO is close to
zero.
If GBP is enabled and the primary server is abnormal, the standby server is promoted to
primary within 1s to provide read and write services. If the redo log for a page is not replayed
on the new primary server, the page reads data from GBP, ensuring the page data consistency.
GBP occupies some resources. If GBP is enabled during log synchronization between the
primary and standby servers, the performance of the primary server deteriorates 10% or less.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

Figure 6-1 GaussDB 100 HA solution

6.3 Enterprise-Level Security Assurance


Based on the Microsoft STRID threat model (spoofing of user identity, tampering,
repudiation, information disclosure, denial of service, and elevation of privilege), GaussDB
100 comprehensively analyzes external entities, internal processes, data storage, and data
flows and provides access control, password protection, permission management, data
encryption, sensitive data masking, connection encryption, and operation auditing to block
invalid users, inhibit malicious users, protect against interception, and make attacks traceable.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

No. Security Policy Threat Security Feature

1 Access control Spoofing SSL connection


Denial of Service IP blacklist/whitelist
Repudiation Limited connections

2 Password policies Information Account locking


Disclosure mechanisms
Privacy disclosure (automatic/manual)
Username/password
Password security
(password
complexity,
password change
period, secure
password storage,
and password reuse
policies)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

No. Security Policy Threat Security Feature

3 Permission Elevation of Separated


management Privilege permissions of
system
administrators,
security
administrators, and
auditors
System permission
control
Object permission
control

4 Data encryption Information Sensitive column


Disclosure encryption
Tampering Backup data
encryption
Table and tablespace
encryption

5 Sensitive data Tampering Log masking


protection Information Dynamic data
Disclosure masking

6 Operation auditing Repudiation Database operation


log auditing
Minimum log file
permissions

7 Connection Tampering SSL transmission


encryption Information encryption
Disclosure Authentication
process encryption
Password
transmission
encryption

6.4 Logical replication


GaussDB 100 logical replication parses table column changes recorded in online or archived
redo logs to reversely generate SQL statements for replay, and then executes the SQL
statements in a target database, replicating GaussDB 100 data changes to the target database
in real time.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

Figure 6-2 Basic process of logical replication

Unlike physical replication that strongly depends on physical formats of logs, logical
replication depends on only logical changes of data and is more flexible. Replication between
GaussDB 100 of different versions, replication from GaussDB 100 to other heterogeneous
databases (such as Oracle and MySQL), and replication to a target database whose table
structure is different from the source database are supported.

Logical replication can be used for incremental data backup between primary and standby
databases, data synchronization between different service systems, and online data migration
during system upgrade without service interruption.

6.5 Huawei-Developed High-Performance Database


Kernel
The GaussDB 100 kernel is developed by Huawei and adopts the following key technologies
to ensure high performance in high concurrency scenarios:

l Unique row storage is used to support online table structure changes without delay.
l The B-tree index data structure adopts lock-free node mirroring, greatly improving the
performance of concurrency processing.
l Catalog optimistic locking ensures that DDL changes do not affect data query.
l Multi-Version Concurrency Control (MVCC) based on rollback segments are used.
l Checkpoint page mirroring is used to ensure that checkpoint processes do not affect data
access.
l SQL Cache multi-version lifecycle management ensures that online DDL does not need
to wait for DML.
l A dynamic thread pool is used to automatically adjust thread resources without the
intervention of database administrators.
l Redo logs are stored in multiple partitions without locks to ensure high performance in
high concurrency scenarios.

6.6 E2E Tool Chain


An end-to-end (E2E) enterprise-level visualized tool chain, covering development,
optimization, monitoring, alarm, inspection, configuration, and node management, is provided
to support E2E process management from development, test, to O&M, reducing enterprise
operation costs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Product Description (Standalone) 6 Enterprise-Level Enhanced Features

6.7 ARM Chips and Huawei EulerOS


Huawei ARM chips work with Huawei EulerOS to provide effective costs and are used in
extended scenarios, for example, development.
l Huawei HiSilicon ARM chips are installed on Taishan servers and have low power
consumption. With the development of the ARM ecosystem, more and more applications
have been migrated to the ARM architecture.
l EulerOS is an OS developed by Huawei. It is easy to use and provides enhanced security,
high compatibility, and high reliability. It meets enterprises' increasing requirements of
OSs and provides a competitive open IT platform for users.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Product Description (Standalone) 7 Technical Specifications

7 Technical Specifications

The following table describes the technical specifications of GaussDB 100.

Table 7-1 Technical specifications


Technical Recommended Value Maximum Value
Specifications

Single-node capacity ≤ 5 TB 8 PB

Number of users ≤ 100 15000

Number of tables ≤ 2000 4 million

Single-table size ≤ 100 GB (per table/ 7.8 TB (per table/partition)


partition)

Size of data in each 8000 (excluding CLOB/ 8000 (row chaining: 64 KB)
row BLOB)

Size of data in each 8000 (excluding CLOB/ 8000 (excluding CLOB/BLOB)


column BLOB)

LOB size - 4 GB

Number of records ≤ 50 million Unlimited


in each table

Number of columns ≤ 200 4095


in each table

Number of indexes ≤8 32
in each table

Number of columns ≤4 16
contained in each
table

Index length ≤ 30 3900

Tablespace size ≤ 5 TB 7.8 PB

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Product Description (Standalone) 7 Technical Specifications

Technical Recommended Value Maximum Value


Specifications

Number of table ≤ 1024 1 million


partitions

Number of ≤ 500 8000


concurrent
connections of a
single DN

Number of standby ≤3 9
servers

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Product Description (Standalone) 8 Running Environment

8 Running Environment

GaussDB 100 supports multiple software and hardware environments. Enterprises can select
software and hardware as needed.

Hardware
l Universal PC server, x86_64
l Universal PC server, ARM_64
l ARM-based servers
l Local storage (SATA, SAS, and SSD)
l Gigabit Ethernet and faster

OSs
The x86 architecture supports the following operating systems:
l Red Hat Enterprise Linux Server release 7.4 x86_64
l SUSE Linux Enterprise Server 11.3 (SUSE 11 for short), x86_64
l SUSE Linux Enterprise Server 12.4 (SUSE 12 for short), x86_64
l EulerOS Server V2.0SP3 x86_64
l EulerOS Server V2.0SP5 x86_64
The ARM architecture supports the following operating systems:
EulerOS Server V2.0SP8 ARM_64

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Product Description (Standalone) 9 Standards Compliance

9 Standards Compliance

For details about the standards complied by GaussDB 100, see Table 9-1.

Table 9-1 Standards compliance


Standard Description

SQL SQL:2003

Application access interfaces l C-API (standalone)


l JDBC 4.0
l ODBC 3.0
l Python 2.7.x and Python 3.x
l GO 1.12.x

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Product Description (Standalone) 10 Glossary

10 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are a set of
features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a database. The
thread thread is used to archive database logs to a specified path.

atomicity One of the ACID features of database transactions. Atomicity means that a
transaction is composed of an indivisible unit of work. All operations
performed in a transaction must either be committed or uncommitted. If an
error occurs during transaction execution, the transaction will be rolled
back to the state when it was not committed.

backup A backup, or the process of backing up, refers to the copying and archiving
of computer data. Backup data can be used for restoration in case of data
loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false logical
condition. A bit is physically represented by an element such as high or low
voltage at one point in a circuit, or a small spot on a disk that is magnetized
in one way or the other. A single bit conveys little information a human
would consider meaningful. A group of eight bits, however, makes up a
byte, which can be used to represent many types of information, such as a
letter of the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at a certain
time. GaussDB 100 periodically stores the data of committed transactions
and data of uncommitted transactions to disks. The data and redo logs can
be used for database restoration if a database restarts or breaks down.

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands are entered
through keyboards or similar devices and are compiled and executed by
applications. The results are displayed in text or graphic forms on the
terminal interface.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

coding Coding is representing data and information using code so that it can be
processed and analyzed by a computer. Characters, digits, and other objects
can be converted into digital code, or information and data can be converted
into the required electrical pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or more


columns.

compression Data compression, source coding, or bit-rate reduction involves encoding


information that uses fewer bits than the original representation.
Compression can be either lossy or lossless. Lossless compression reduces
bits by identifying and eliminating statistical redundancy. No information is
lost in lossless compression. Lossy compression reduces bits by identifying
and removing unnecessary or less important information. The process of
reducing the size of a data file is commonly referred as data compression,
although its formal name is source coding (coding done at the source of
data, before it is stored or transmitted).

concurrency A DBMS service that ensures data integrity when multiple transactions are
control concurrently executed in a multi-user environment. In a multi-threaded
GaussDB 100 environment, concurrency control ensures that database
operations are safe and all database transactions remain consistent at any
given time.

consistency One of the ACID features of database transactions. Consistency is a


database state. In such a state, integrity constraints on tables are not
damaged.

convergence Downlink to uplink bandwidth ratio of a switch. A high convergence ratio


ratio indicates a highly converged traffic environment and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or system
dump records the state of working memory of the program at that point in
time. The states of key programs are often dumped at the same time. For
example, information about processor registers, including program metrics,
stack pointers, memory management, other processors, and OS flags are
often dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

core file A file that is created when memory overwriting, assertion failures, or access
to invalid memory occurs in a process, causing it to fail. This file is then
used for further analysis.
A core file stores memory dump data, and supports binary mode and
specified ports. The name of a core file consists of the word "core" and the
OS process ID.
The core file is available regardless of the type of platform.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

crash A crash (or system crash) is when a computer or program, such as a


software application or an operating system, stops functioning properly.
Often the program will exit after encountering this type of error. The
program experiencing the crash can hang or freeze until a crash reporting
service reports the crash and any details relating to it. If the program is a
critical part of the operating system and crashes, the entire system may be
paralyzed, often resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes constants,
variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored procedure
information, user rights, user statistics, database process information,
database increase statistics, and database performance statistics.

data flow An operator that exchanges data among query fragments. By their input/
operator output relationships, data flows can be categorized into Gather flows,
Broadcast flows, and Redistribution flows. Gather combines multiple query
fragments of data into one. Broadcast forwards the data of one query
fragment to multiple query fragments. Redistribution reorganizes the data
of multiple query fragments and then redistributes the reorganized data to
multiple query fragments.

data A division of a logical database or its constituent elements into multiple


partitioning parts (partitions) whose data does not overlap based on ranges or lists. The
target storage location is mapped based on the range of the values in the
column that is specified in the tuple.

database A collection of data that is stored together and can be accessed, managed,
and updated. Data in a view in a database can be classified into the
following types: numeral, full text, digit, and image.

database file A binary file that stores user data and the internal data of a database system.

database HA GaussDB 100 provides a highly reliable HA solution. Every logical node in
GaussDB 100 is identified as a primary or standby node. At the same time,
only one GaussDB 100 node is identified as the primary server. In
GaussDB 100, standby nodes first perform full synchronization from the
primary node and later incremental synchronization. When the HA system
is running, the primary node can receive data read and write requests in
GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database instances
to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database maintenance


operations.

DBLINK An object of the path from one database to another. A remote database
object can be queried with DBLINK.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a database.
It is a collection of programs that allows users to access, manage, and query
data in a database. A DBMS can be classified as memory DBMS or disk
DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data during an
event response, whereas a trace file contains continuously generated
diagnostic data.

durability One of the ACID features of database transactions. Transactions that have
been committed will permanently survive and not be rolled back.

encryption A function hiding information content during data transmission to prevent


unauthorized use of the information.

environment An environment variable defines a part of the environment in which a


variable process runs. For example, it can define a main directory, command search
path, terminal that is in use, or the current time zone.

error A technique that automatically detects and corrects errors in software and
correction data streams to improve system stability and reliability.

F–J

failover Automatic switchover from a faulty node to its standby node. Reversely,
automatic switchback from the standby node to the primary node is called
failback.

failover Automatic substitution of a functionally equivalent system component for a


failed one. The system component can be a processor, server, network, or
database.

free space A mechanism for managing free space in a table. This mechanism enables a
management database system to record free space in each table and establish an easy-to-
find data structure, accelerating operations (such as INSERT) performed on
the free space.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

freeze An operation automatically performed by the AutoVacuum Worker process


when transaction IDs are exhausted. GaussDB 100 records transaction IDs
in the row heading. When a transaction reads a row, the transaction ID in
the row heading and the actual transaction ID are compared to determine
whether this row is explicit. Transaction IDs are integers containing no
symbols. If exhausted, transaction IDs are re-calculated outside of the
integer range, causing the explicit rows to become implicit. To prevent such
a problem, the freeze operation marks a transaction ID as a special ID.
Rows marked with these special transaction IDs are explicit to all
transactions.

full A data synchronization mechanism specified in the GaussDB 100 HA


synchronizat solution. Used to synchronize all data from the primary server to a standby
ion server.

GNU The GNU Project was publicly announced on September 27, 1983 by
Richard Stallman, aiming at building an OS composed wholly of free
software. GNU is a recursive acronym for "GNU's Not Unix!". Stallman
announced that GNU should be pronounced as Guh-NOO. Technically,
GNU is similar to Unix in design, a widely used commercial OS. However,
GNU is free software and contains no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for each
node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration of


service interruptions caused by routine maintenance (planned) or sudden
system breakdowns (unplanned), improving system and application
usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on behalf of


all or some of the system users.

incremental Incremental backup stores all file changes since the last valid backup.
backup

index An ordered data structure in a DBMS. An index accelerates data query and
update in database tables.

isolation One of the ACID features of database transactions. Isolation means that the
operations inside a transaction and data used are isolated from other
concurrent transactions. Concurrent transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java APIs of
SQL statements. It provides unified access to multiple relational databases,
consisting of a set of classes and interfaces written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements. When
deleting a tuple, GaussDB 100 only marks the tuples that are to be cleared.
The VACUUM thread will then periodically clear these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

metadata Data that provides information about other data. Metadata describes the
source, size, format, or other characteristics of data. In database columns,
metadata explains the content of a data warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that allows a


tuple to have multiple versions, on which different query operations can be
performed. One basic advantage is that read and write operations do not
conflict.

network Network backup provides a comprehensive, flexible data protection


backup solution for Microsoft Windows, UNIX, and Linux platforms. Network
backup can back up, archive, and restore files, folders, directories, volumes,
and partitions on a computer.

OS An operating system (OS) manages applications or application programs on


a computer.

P–T

page Smallest memory unit for row storage in the relational object structure in
GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature of


GaussDB 100. Data can be restored to a specified point in time if backup
data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB 100 HA
server system and works with all standby servers. At any time, only one node in
the HA system is identified as the primary server.

process An instance of a computer program that is being executed. A process may


be made up of one or more threads. A process cannot use a thread occupied
by another process.

QPS Query Per Second (QPS) means the number of queries that a server can
respond to per second.

query Each query job can be split into one or more query fragments. Each query
fragment fragment consists of one or more query operators and can independently
run on a node. Query fragments exchange data through data flow operators.

query An iterator or a query tree node, which is a basic unit for the execution of a
operator query. Execution of a query can be split into one or more query operators.
Common query operators include scan, join, and aggregation.

record In a relational database, a record corresponds to data in each row of a table.

redo log A log that contains information required for performing an operation again
in a database. If a database is faulty, redo logs can be used to restore the
database to its original state.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

relational A database created using the relational model. It processes data using
database methods of set algebra.

resource A collection of resources that can be accessed to obtain information.


library

RPO Recovery point objective (RPO) refers to the latest status that a database
system and the data can be restored to after a disaster, and it is usually
represented by time.

RTO Recovery time objective (RTO) refers to the duration between the database
system failure caused by a disaster and its restoration to proper running.

schema A database object set that includes the logical structure, such as tables,
views, sequences, stored procedures, synonyms, clusters, and database
links.

segment A segment in a database indicates a part containing one or more extents. An


extent is the smallest range of a database and consists of data blocks. One
or more segments comprise a tablespace.

session A job created by a database system for connection purposes when an


application attempts to connect to the database. Sessions are managed by
the session manager. They execute initial jobs to perform all user
operations.

SGA System global area (SGA). It is the cache management framework of


GaussDB 100. It contains most cache management components of the
storage engine and SQL engine, including PlanCache, DataBuffer,
DcCache, RedoBuffer, CkptBuffer, LockBuffer, TransactionBuffer, and
ReplicationBuffer.

shared pool A shared pool is created for repeatedly executed SQL statements to save
memory. It contains the explain trees and execution plans of given SQL
statements.

SQL Structured Query Language (SQL) is a standard database query language. It


consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used by
Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides three
basic security services, all of which use the public key technology. SSL
ensures the security of service communication through a network by
establishing a secure connection between a client and a server and then
sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup of the


server primary server. If the primary server is behaving abnormally, the standby
server is promoted to primary, ensuring uninterrupted data services.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Product Description (Standalone) 10 Glossary

Term Description

statistics Information that is automatically collected by databases, including table-


level information (number of tuples and number of pages) and column-level
information (column value range distribution histograms). Statistics in
databases are used to estimate the costs of query plans to find the plan with
the lowest cost.

stop word In computing, stop words are words which are filtered out before or after
processing of natural language data (text), saving storage space and
improving search efficiency.

stored A group of SQL statements compiled into a single execution plan and
procedure stored in a large database system. Users can specify a name and parameters
(if any) for a stored procedure to execute the procedure.

system A table storing meta information about a database. The meta information
catalog includes user tables, indexes, columns, functions, and data types in a
database.

table A set of columns and rows. Each column is referred to as a field. Values in
each field represent a data type. For example, if a table contains three fields
of person names, cities, and states, it has three columns: Name, City, and
State. In every row in the table, the Name column contains a name, the City
column contains a city, and the State column contains a state.

tablespace A tablespace is a logical storage structure that contains tables, indexes, and
objects. A tablespace provides an abstract layer between physical data and
logical data, and provides storage space for all database objects. When you
create an object, you can specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and are used
for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a database. A


transaction consists of a limited database operation sequence, and must
have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information library. A


WSR is generated by comparing statistics collected by two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively enter
queries, issue them to GaussDB 100, and view the query results. Queries
can also be entered from files. zsql supports many meta commands and
shell-like commands, allowing you to conveniently compile scripts and
automate jobs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
V300R001C00

R&D Documentation (Standalone)

Issue 04
Date 2019-12-28

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties, guarantees
or representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
R&D Documentation (Standalone) Contents

Contents

1 About This Document.............................................................................................................1


2 Database Development Guide........................................................................................... 10
2.1 Overview.................................................................................................................................................................................. 10
2.1.1 Physical Structure of a Database................................................................................................................................. 10
2.1.2 SQL Syntax........................................................................................................................................................................... 11
2.1.3 Related Concepts............................................................................................................................................................... 11
2.2 Development Based on C APIs......................................................................................................................................... 12
2.2.1 Related Libraries and Header Files.............................................................................................................................. 12
2.2.2 Development Process....................................................................................................................................................... 12
2.2.3 Connecting to a Database.............................................................................................................................................. 12
2.2.4 API Reference...................................................................................................................................................................... 13
2.2.5 Examples...............................................................................................................................................................................47
2.3 Development Based on JDBC............................................................................................................................................49
2.3.1 JDBC Package and Driver Class.................................................................................................................................... 49
2.3.2 Development Process....................................................................................................................................................... 49
2.3.3 Loading a Driver................................................................................................................................................................ 50
2.3.4 Connecting to a Database.............................................................................................................................................. 50
2.3.5 Running SQL Statements................................................................................................................................................ 54
2.3.6 Processing Data in a Result Set.................................................................................................................................... 56
2.3.7 DataSource Support and Configuration Description.............................................................................................58
2.3.8 Closing a Connection....................................................................................................................................................... 61
2.3.9 Examples...............................................................................................................................................................................61
2.3.10 JDBC Interface Reference............................................................................................................................................. 64
2.3.10.1 java.sql.Connection..................................................................................................................................................... 64
2.3.10.2 java.sql.DatabaseMetaData..................................................................................................................................... 65
2.3.10.3 java.sql.Driver................................................................................................................................................................ 71
2.3.10.4 java.sql.PreparedStatement...................................................................................................................................... 71
2.3.10.5 java.sql.ResultSet......................................................................................................................................................... 74
2.3.10.6 java.sql.ResultSetMetaData...................................................................................................................................... 77
2.3.10.7 java.sql.Statement....................................................................................................................................................... 78
2.3.10.8 java.sql.CallableStatement....................................................................................................................................... 79
2.3.10.9 java.sql.Blob................................................................................................................................................................... 83
2.3.10.10 java.sql.Clob................................................................................................................................................................ 83

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
R&D Documentation (Standalone) Contents

2.3.11 Non-standard Interfaces Provided by Zenith.........................................................................................................84


2.3.11.1 com.huawei.gauss.jdbc.GaussConnection........................................................................................................... 84
2.3.11.2 com.huawei.gauss.jdbc.GaussPrepareStatement.............................................................................................. 84
2.4 Development Based on Python........................................................................................................................................85
2.4.1 Python Driver Dynamic Library.................................................................................................................................... 85
2.4.2 Development Process....................................................................................................................................................... 85
2.4.3 Connecting to a Database.............................................................................................................................................. 86
2.4.4 Running SQL Statements................................................................................................................................................ 87
2.4.5 Closing a Connection....................................................................................................................................................... 89
2.4.6 Python Interface Reference............................................................................................................................................ 89
2.5 基于 GO 开发...........................................................................................................................................................................94
2.5.1 Go Driver.............................................................................................................................................................................. 94
2.5.2 Driver Installation and Use............................................................................................................................................ 94
2.5.3 Development Process....................................................................................................................................................... 95
2.5.4 Connecting to a Database.............................................................................................................................................. 96
2.5.5 Running SQL Statements................................................................................................................................................ 97
2.5.6 Closing a Connection....................................................................................................................................................... 98
2.5.7 Go Interfaces....................................................................................................................................................................... 99
2.5.8 Examples............................................................................................................................................................................ 103
2.6 Development based on ODBC....................................................................................................................................... 104
2.6.1 ODBC Package and Its Dependent Libraries and Header Files....................................................................... 104
2.6.2 Configuring a Data Source in the Linux OS........................................................................................................... 105
2.6.3 Development Process.....................................................................................................................................................110
2.6.4 Example.............................................................................................................................................................................. 112
2.6.5 ODBC Interfaces.............................................................................................................................................................. 113

3 SQL Syntax Reference........................................................................................................ 128


3.1 Conventions.......................................................................................................................................................................... 128
3.2 Example................................................................................................................................................................................. 129
3.2.1 示例库说明......................................................................................................................................................................... 129
3.2.2 Reference Scripts............................................................................................................................................................. 129
3.3 Keyword................................................................................................................................................................................. 137
3.4 Data Types............................................................................................................................................................................ 162
3.4.1 Numeric Data Types....................................................................................................................................................... 162
3.4.1.1 Integer............................................................................................................................................................................. 162
3.4.1.1.1 32-Bit Signed Integer.............................................................................................................................................. 162
3.4.1.1.2 32-Bit Unsigned Integer......................................................................................................................................... 163
3.4.1.1.3 64-Bit Signed Integers............................................................................................................................................ 164
3.4.1.2 Floating-Point Numbers............................................................................................................................................ 165
3.4.1.3 High-Precision Numbers........................................................................................................................................... 166
3.4.2 Character Data Types.....................................................................................................................................................168
3.4.2.1 Fixed-Length String..................................................................................................................................................... 168
3.4.2.2 Variable-Length String............................................................................................................................................... 169

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
R&D Documentation (Standalone) Contents

3.4.3 Binary Data Types........................................................................................................................................................... 170


3.4.4 Datetime Data Types..................................................................................................................................................... 171
3.4.5 Boolean Data Type......................................................................................................................................................... 177
3.4.6 Interval Data Types.........................................................................................................................................................178
3.5 Functions............................................................................................................................................................................... 183
3.5.1 Numeric Functions.......................................................................................................................................................... 184
3.5.2 Character Processing Functions..................................................................................................................................192
3.5.3 Time/Date Functions......................................................................................................................................................212
3.5.4 Interval Functions........................................................................................................................................................... 220
3.5.5 Type Conversion Functions.......................................................................................................................................... 227
3.5.6 Aggregate Functions...................................................................................................................................................... 238
3.5.7 Analytic Functions...........................................................................................................................................................246
3.5.8 Table Functions................................................................................................................................................................ 248
3.5.9 Other Functions............................................................................................................................................................... 253
3.5.10 Window Functions........................................................................................................................................................ 278
3.6 Operators.............................................................................................................................................................................. 279
3.6.1 Logical Operators............................................................................................................................................................ 279
3.6.2 Comparison Operators.................................................................................................................................................. 279
3.6.3 Arithmetic Operators..................................................................................................................................................... 280
3.6.4 Test Operators.................................................................................................................................................................. 282
3.6.5 Wildcard Characters....................................................................................................................................................... 284
3.6.6 Other Operators.............................................................................................................................................................. 284
3.7 Type Conversion.................................................................................................................................................................. 284
3.8 Type Mapping...................................................................................................................................................................... 286
3.9 Transaction Management................................................................................................................................................ 288
3.10 Expressions......................................................................................................................................................................... 289
3.10.1 SQL Expressions.............................................................................................................................................................289
3.10.2 Simple Expressions....................................................................................................................................................... 289
3.10.3 Compound Expressions............................................................................................................................................... 290
3.10.4 CASE Expressions.......................................................................................................................................................... 290
3.11 Data Query......................................................................................................................................................................... 290
3.11.1 Overview.......................................................................................................................................................................... 291
3.11.2 Simple Query..................................................................................................................................................................296
3.11.3 Condition Query............................................................................................................................................................ 297
3.11.4 JOIN Query..................................................................................................................................................................... 299
3.11.5 Subquery.......................................................................................................................................................................... 305
3.11.6 Query from SYS_DUMMY.......................................................................................................................................... 307
3.11.7 UNION.............................................................................................................................................................................. 307
3.11.8 MINUS.............................................................................................................................................................................. 310
3.11.9 Hierarchical Query........................................................................................................................................................311
3.11.10 GROUP BY..................................................................................................................................................................... 313
3.11.11 HAVING......................................................................................................................................................................... 315

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
R&D Documentation (Standalone) Contents

3.11.12 ORDER BY..................................................................................................................................................................... 316


3.11.13 WITH AS........................................................................................................................................................................ 317
3.11.14 LIMIT............................................................................................................................................................................... 318
3.11.15 FOR UPDATE................................................................................................................................................................ 319
3.12 Function Syntax................................................................................................................................................................ 320
3.12.1 BACKUP............................................................................................................................................................................ 321
3.12.2 BUILD DATABASE......................................................................................................................................................... 323
3.12.3 DUMP............................................................................................................................................................................... 324
3.12.4 EXP..................................................................................................................................................................................... 327
3.12.5 IMP.....................................................................................................................................................................................333
3.12.6 LOAD................................................................................................................................................................................. 336
3.12.7 RECOVER DATABASE................................................................................................................................................... 340
3.12.8 RESTORE DATABASE.................................................................................................................................................... 341
3.12.9 RESTORE BLOCKRECOVER......................................................................................................................................... 342
3.12.10 SHUTDOWN.................................................................................................................................................................343
3.12.11 VALIDATE...................................................................................................................................................................... 344
3.13 SQL Syntax......................................................................................................................................................................... 345
3.13.1 DCL Syntax...................................................................................................................................................................... 345
3.13.2 DDL Syntax..................................................................................................................................................................... 346
3.13.3 DML Syntax.................................................................................................................................................................... 351
3.13.4 DDL Syntax..................................................................................................................................................................... 352
3.13.5 ALTER DATABASE.......................................................................................................................................................... 352
3.13.6 ALTER INDEX.................................................................................................................................................................. 360
3.13.7 ALTER PROFILE.............................................................................................................................................................. 361
3.13.8 ALTER SESSION..............................................................................................................................................................363
3.13.9 ALTER SQL_MAP............................................................................................................................................................366
3.13.10 ALTER SEQUENCE...................................................................................................................................................... 367
3.13.11 ALTER SYSTEM............................................................................................................................................................ 369
3.13.12 ALTER SYSTEM KILL SESSION................................................................................................................................ 371
3.13.13 ALTER TABLESPACE.................................................................................................................................................... 372
3.13.14 ALTER TABLE................................................................................................................................................................ 375
3.13.15 ALTER USER.................................................................................................................................................................. 385
3.13.16 ANALYZE........................................................................................................................................................................ 387
3.13.17 COMMENT ON............................................................................................................................................................388
3.13.18 COMMIT........................................................................................................................................................................ 389
3.13.19 CREATE DATABASE.................................................................................................................................................... 390
3.13.20 CREATE INDEX.............................................................................................................................................................393
3.13.21 CREATE PROFILE........................................................................................................................................................ 396
3.13.22 CREATE ROLE.............................................................................................................................................................. 398
3.13.23 CREATE SEQUENCE................................................................................................................................................... 399
3.13.24 CREATE SYNONYM.................................................................................................................................................... 401
3.13.25 CREATE TABLE............................................................................................................................................................. 403

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. v


GaussDB 100
R&D Documentation (Standalone) Contents

3.13.26 CREATE TABLESPACE................................................................................................................................................ 412


3.13.27 CREATE TABLE PARTITION...................................................................................................................................... 414
3.13.28 CREATE USER............................................................................................................................................................... 422
3.13.29 CREATE VIEW...............................................................................................................................................................425
3.13.30 DELETE........................................................................................................................................................................... 426
3.13.31 DROP INDEX................................................................................................................................................................ 428
3.13.32 DROP PROFILE............................................................................................................................................................ 429
3.13.33 DROP ROLE.................................................................................................................................................................. 429
3.13.34 DROP SEQUENCE....................................................................................................................................................... 430
3.13.35 DROP SQL_MAP..........................................................................................................................................................431
3.13.36 DROP SYNONYM........................................................................................................................................................432
3.13.37 DROP TABLE................................................................................................................................................................. 432
3.13.38 DROP TABLESPACE.................................................................................................................................................... 433
3.13.39 DROP USER.................................................................................................................................................................. 435
3.13.40 DROP VIEW.................................................................................................................................................................. 436
3.13.41 EXPLAIN PLAN............................................................................................................................................................. 436
3.13.42 FLASHBACK TABLE.....................................................................................................................................................437
3.13.43 GRANT........................................................................................................................................................................... 439
3.13.44 INSERT............................................................................................................................................................................467
3.13.45 LOCK TABLE..................................................................................................................................................................469
3.13.46 MERGE........................................................................................................................................................................... 471
3.13.47 PURGE............................................................................................................................................................................ 473
3.13.48 REALEASE SAVEPOINT............................................................................................................................................. 475
3.13.49 REPLACE........................................................................................................................................................................ 475
3.13.50 REVOKE.......................................................................................................................................................................... 477
3.13.51 ROLLBACK..................................................................................................................................................................... 479
3.13.52 SAVEPOINT................................................................................................................................................................... 480
3.13.53 SELECT............................................................................................................................................................................481
3.13.54 SET TRANSACTION.................................................................................................................................................... 488
3.13.55 TRUNCATE TABLE...................................................................................................................................................... 489
3.13.56 UPDATE......................................................................................................................................................................... 490
3.13.57 WITH AS........................................................................................................................................................................ 492
3.14 Stored Procedure.............................................................................................................................................................. 493
3.14.1 Examples.......................................................................................................................................................................... 493
3.14.2 Executing a Stored Procedure.................................................................................................................................. 496
3.14.3 Deleting a Stored Procedure..................................................................................................................................... 499
3.14.4 Creating a Stored Procedure..................................................................................................................................... 499
3.14.5 Data Type........................................................................................................................................................................ 501
3.14.6 DECLARE Syntax............................................................................................................................................................ 503
3.14.7 Basic Statements........................................................................................................................................................... 507
3.14.8 Dynamic Statements................................................................................................................................................... 511
3.14.9 Control Statements...................................................................................................................................................... 512

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. vi


GaussDB 100
R&D Documentation (Standalone) Contents

3.14.10 Exception Statements............................................................................................................................................... 517


3.14.11 Other Statements....................................................................................................................................................... 520
3.14.12 Cursors........................................................................................................................................................................... 524
3.14.13 Anonymous Blocks..................................................................................................................................................... 532
3.15 Built-in Advanced Packages......................................................................................................................................... 533
3.15.1 DBMS_LOB...................................................................................................................................................................... 534
3.15.2 DBMS_JOB....................................................................................................................................................................... 535
3.15.3 DBMS_OUTPUT............................................................................................................................................................. 539
3.15.4 DBMS_RAFT.................................................................................................................................................................... 540
3.15.5 DBMS_RANDOM........................................................................................................................................................... 540
3.15.6 DBMS_SQL...................................................................................................................................................................... 542
3.15.7 DBMS_STANDARD........................................................................................................................................................ 543
3.15.8 DBMS_STATS.................................................................................................................................................................. 544
3.15.9 DBMS_UTILITY............................................................................................................................................................... 547
3.15.10 DBMS_DIAGNOSE...................................................................................................................................................... 548
3.16 User-defined Functions.................................................................................................................................................. 554
3.17 Triggers................................................................................................................................................................................ 558
3.17.1 Examples.......................................................................................................................................................................... 558
3.17.2 Creating a Trigger......................................................................................................................................................... 561
3.17.3 Deleting a Trigger......................................................................................................................................................... 563
3.17.4 Modifying a Trigger..................................................................................................................................................... 564
3.18 Object Dependencies...................................................................................................................................................... 564

4 Interface Mapping (GaussDB 100 Native Interface Names vs. Mainstream


Database Interface Names)................................................................................................. 566
4.1 Data Dictionary Tables..................................................................................................................................................... 566
4.2 DBA Views............................................................................................................................................................................. 568
4.3 User Views............................................................................................................................................................................ 571
4.4 Dynamic Performance Views..........................................................................................................................................573
4.5 Configuration Parameters............................................................................................................................................... 576

5 Glossary................................................................................................................................. 577

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. vii


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

1 About This Document

GaussDB 100 is a high-performance and high-reliability distributed relational


database developed by Huawei Technologies Co., Ltd. It supports automatic
horizontal sharding and breaks the storage and performance bottlenecks of a
single server. The framework of GaussDB 100 is component-based and can be
used for a standalone database or a cluster. This document is intended for
application developers, helping them develop applications based on GaussDB 100.

GaussDB 100 is compatible with the user habits of mainstream databases. You can
use native GaussDB 100 interface names or their corresponding names in the
mainstream databases. For details, see Interface Mapping (GaussDB 100 Native
Interface Names vs. Mainstream Database Interface Names). The interfaces
mentioned in this document use their native GaussDB 100 names.

Intended Audience
This document is intended for developers on C/Java application based on GaussDB
100, providing necessary references.

As an application developer, you need to be familiar with:

● Knowledge about OSs, which is the foundation for application development.


● C/Java language, through which you can develop applications.
● An IDE of the C/Java language, which is the prerequisite for efficient
application development.
● SQL syntax, using which you can operate databases.

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not


avoided, will result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in death or serious injury.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Symbol Description

Indicates a potentially hazardous situation which, if not


avoided, could result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in equipment damage, data loss,
performance deterioration, or unanticipated results.
NOTICE is used to address practices not related to personal
injury.

Calls attention to important information, best practices, and


tips.
NOTE is used to address information not related to personal
injury, equipment damage, and environment deterioration.

Example Conventions
The following table describes some example information in this document. You
can replace the example information as needed.

Information Description

$GSDB_HOME Environment variable of the GaussDB 100 installation


directory that is automatically written when install.py is
used for installation. Assume that /opt/gaussdb/app is set
as the installation directory.

$GSDB_DATA Environment variable of the GaussDB 100 data directory


that is automatically written when install.py is used for
installation. Assume that /opt/gaussdb/data is set as the
data directory.

gaussdba GaussDB 100 administrator manually created after the


installation

database_123 Password of the database administrator gaussdba

192.168.0.1 IP address of the GaussDB 100 server

1888 Port number used by GaussDB 100 to listen to client


connection requests

Parameters of GaussDB 100 tools are parsed in sequence. If a parameter is


specified for multiple times, the last value takes effect.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are


in italics.

[] Items (keywords and parameters) in brackets [ ] are


optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more


options or no item is selected.

{ x | y | ... } Indicates that one item is selected from two or more


options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
commas (,).

Change History
Version Change Description Date

04 This issue is the fourth official release. 2019-07-18

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Version Change Description Date

03 Added: 2019-06-26
● Load Balancing
● MEDIAN function
● BUILD DATABASE syntax
● RESTORE BLOCKRECOVER syntax
● VALIDATE syntax
● UUID function
● MD5 function
● 32-Bit Unsigned Integer
● REALEASE SAVEPOINT syntax
Modified:
● Parameters added to BACKUP
● CANCEL parameter added to
RECOVER DATABASE
● clear parameter added to ALTER
DATABASE
● System role STATISTICS added to
CREATE ROLE
● Function SQLNumResultCols added to
ODBC Interfaces
● Syntax ORDER SIBLINGS BY added to
SELECT
● AS OF SCN or TIMESTAMP
parameter added in SELECT
● The parameter of forcibly submitting
residual transactions added in
COMMIT
● Method of the Cursor class added in
Python Interface Reference
● Description of overwriting the file
with the same name added in EXP
● IMP supports importing an exported
file of an earlier version to the current
version.
● ALTER TABLESPACE supports
shrinking undo tablespaces.
● ALTER DATABASE supports data file
management.
● RESTORE DATABASE supports
specifying a tablespace whose data is
to be restored based on full backup.
● GROUP BY supports bracket
expressions after GROUP BY.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Version Change Description Date

● Syntax formats and parameters of


BACKUP and RESTORE DATABASE
are modified.
● The
DBMS_STATS.GATHER_SCHEMA_STAT
S interface of DBMS_STATS can
collect statistics on index columns
separately.
● Usage of LSNR_ADDR added in
ALTER SYSTEM
● The SHRINK parameter supported in
ALTER TABLE and ALTER
TABLESPACE
● The syntax format of SELECT is
modified. Sorting of NULL values
based on the ORDER BY column is
supported.
● The EXTENTS parameter in CREATE
TABLESPACE is modified.
● Support for renaming indexes in
ALTER INDEX
● Support for renaming constraints in
ALTER TABLE
● Support for AUTOOFFLINE in ALTER
TABLESPACE and CREATE
TABLESPACE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Version Change Description Date

02 Added: 2019-04-05
● Added the section Type Mapping.
● Added the section Development
based on ODBC.
● Added section Table Functions.
● Added section Data Query.
● Added the gsc_describle and
gsc_get_batch_error interfaces.
● Added the EXP and LOG functions in
Numeric Functions.
● Added the SPACE, TO_NCHAR, and
SUBSTRING_INDEX functions in
Character Processing Functions.
● Added the built-in advanced package
DBMS_JOB.
● Added the interface
java.sql.CallableStatement.
● Added description about creating SQL
mapping in ALTER SQL_MAP.
● DROP SQL_MAP
● Add the DECODE_NAME function in
Other Functions.
● Added the interface java.sql.Blob.
● Added the interface java.sql.Clob.
● Added the section Modifying a
Trigger.
● Added the section DBMS_LOB.
Modified:
● In GRANT, added the Whether the
Role Has This Permission and
Whether the User Has This
Permission columns to Table 3-53.
● In Creating a Stored Procedure,
added the description of the
sequences OBJECT_ID$ and
SEQ_PROC_001.
● In DBMS_JOB, added description of
the sequence JOBSEQ.
● Optimized the "Data Types" section.
Provided all data types and optimized
the document structure.
● In Time/Date Functions, added the
SLEEP and SYSTIMESTAMP functions.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Version Change Description Date

● In Other Functions, added the


UPDATING and VERSION functions.
● In Connecting to a Database, added
the SSL communication encryption
configuration method
Modified:
● In gsc_rollback and gsc_xa_rollback,
added the gsc_xa_rollback interface.
● In Functions, optimized the function
descriptions and added an example
for each function.
● In JDBC Interface Reference,
optimized the methods supported by
interfaces.
Deleted:
● Deleted the section 3.12.14
"Debugging and Restriction
Information".

01 This issue is the first official release. 2018-10-30

Example Database
A human resource (HR) database is provided for users to learn and verify GaussDB
100 For details about how to install the database, see Installation Guide.
The database contains eight tables: staffs, sections, places, states, areas,
employments, employment_history, and college. For the relationship between
these tables, see Figure 1-1.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Figure 1-1 Relationship between tables in the HR database

The following table describes the objects in the HR database.

Table 1-1 hr
Object Name Object Description
Type

states(state) Table Contains the country of each


employee.

sections Table Contains the section where each


employee works.

staffs Table Contains employees.

employment_history Table Contains the employment history of


each employee.

employments Table Contains the job of each employee.

places Table Contains the place where each


employee works.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
R&D Documentation (Standalone) 1 About This Document

Object Name Object Description


Type

areas Table Contains the area where each


employee works.

staff_details_view View Used to query for detailed information


about an employee.

The following figure shows details about the staff_details_view view.

Figure 1-2 staff_details_view column details

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

2 Database Development Guide

2.1 Overview
GaussDB 100 supports application development based on C, Java, Python, and GO.
Understanding its system structure and related concepts can facilitate
development.

2.1.1 Physical Structure of a Database


The instances, SQL engine, and storage engine in GaussDB 100 are decoupled.
Understanding the system structure and related concepts of GaussDB 100 helps
you quickly develop applications.

Figure 2-1 Database system architecture

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● The instances can start service listening; allocate memory, such as the system
global area (SGA); initialize the thread pool and buffers; and open control
files and data files.
● The SQL engine parses SQL statements, generates query plans, and calculates
expressions.
● The storage engine manages physical and logical storage; implements data
storage, fetch, and persistence; ensures transaction Atomicity, Consistency,
Isolation, Durability (ACID); and controls concurrency.

2.1.2 SQL Syntax


Structured Query Language (SQL) is the standard language on relational
databases (RDB). SQL is a universal and useful RDB language.

GaussDB 100 is compatible with SQL:2003.

GaussDB 100 has the following compatibility restrictions:

● The unique constraint takes effect only in a standalone database.


● CREATE TABLE AS EXECUTE cannot be used.
● WHERE CURRENT OF cannot be used.
● WITH HOLD is not supported.
● FOREIGN DATA WRAPPER cannot be used.
● SECURITY LABEL cannot be used.
● The distribution columns in a table cannot be updated.

For details about error information during SQL execution, see GaussDB 100
V300R001C00 Error Code Reference.

2.1.3 Related Concepts


This section explains the important concepts in the document.

Instances
In GaussDB 100, instances are a group of database processes running in the
memory. An instance can manage one or more databases that form a cluster. A
cluster is an area in the storage disk. This area is initialized during installation and
contains a directory, which is called data directory and stores all data.
Theoretically, one server can start multiple instances on different ports, but
GaussDB 100 manages only one instance at a time. The start and stop of an
instance rely on the specific data directory.

Databases
Databases manage various data objects and are isolated from each other. While
creating a database, you can specify its tablespace. If you do not specify it, the
object will be saved to your default tablespace. Objects managed by a database
can be distributed to multiple tablespaces.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Tablespaces
In GaussDB 100, a tablespace is a directory storing physical files of databases.
Multiple tablespaces can coexist. Files are physically isolated using tablespaces
and managed by a file system.

User and Role


GaussDB 100 uses users and roles to control the access to databases. A role is a
set of permissions. The permissions are grouped and granted to different roles for
hierarchical management of permissions. After one or more roles are granted to a
user, this user inherits all the permissions of the roles.

2.2 Development Based on C APIs


GaussDB 100 provides a complete set of C library functions, using which you can
easily develop applications based on the database.

2.2.1 Related Libraries and Header Files


● Library: libzeclient.so
● Header file: gsc.h

2.2.2 Development Process


Step 1 Use the C API library and header file for local compilation.
-L${include_path} -lzeclient

Step 2 Invoke required C API interfaces to perform database operations.

----End

2.2.3 Connecting to a Database


To use a C API to create a database connection, use the following function:
int gsc_connect(gsc_conn_t conn, const char * url, const char * user, const char * password);

Parameters

Table 2-1 Database connection parameters


Parameter Description

conn Connection object, which is created through the


gsc_alloc_conn interface

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter Description

url Database connection descriptor. Its format is as


follows:
ip:port
NOTE
● ip: name of a database server
● port: port number of the database server

user Database user

password Password of a database user

Examples
// Create a connection object and connect to the database by specifying the URL, username, and password.
int test_conn_db(char * url, char * user, char * password)
{
gsc_conn_t conn;
if (gsc_alloc_conn(&conn) != GSC_SUCCESS)
{
return GSC_ERROR;
}
if (gsc_connect(conn, url, user, password) != GSC_SUCCESS)
{
return GSC_ERROR;
}
// Use the connection to perform other operations.
gsc_free_conn(conn);
conn = NULL;//to avoid using wild pointer, user should set conn NULL after free
return GSC_SUCCESS;
}

2.2.4 API Reference


gsc_alloc_conn
Description: Creates a connection object and use it to invoke gsc_connect to
connect to the database.
API:
int gsc_alloc_conn(gsc_conn_t * conn);

Parameter: conn specifies the connection object to be created.


Return value:
● 0: successful
● !=0: failed
Thread-safe: yes

gsc_free_conn
Description: Releases a connection object. This API is invoked after the
gsc_disconnect (database disconnection) operation is performed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Precautions:

To use the conn variable again after gsc_free_conn is used, set conn to NULL.

API:
void gsc_free_conn(gsc_conn_t conn);

Parameter: conn specifies the connection object to be released.

Return value: empty

Thread-safe: no

gsc_connect
Description: Connects to the database. The URL format is ip:port and only
supports TCP connections.

API:
int gsc_connect(gsc_conn_t conn, const char * url, const char * user, const char * password);

Parameter:

● conn: object to be connected


● url: URL to be connected
● user: name of the user to connect to the database
● password: password of the user to connect to the database

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_set_conn_attr
Description: Sets connection attributes.

The following table lists the supported connection attributes.

Table 2-2 Connection attributes

Attribute Description Value


Name

GSC_ATTR_A Whether to 1: automatically commit


UTO_COMMI automatically commit a 0: manually commit
T connection

GSC_ATTR_EX Whether to commit 1: commit on exit


IT_COMMIT when exiting a zsql 0: do not commit on exit
connection

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Attribute Description Value


Name

GSC_ATTR_SE Whether zsql displays 1: print the serveroutput information


RVEROUTPUT the serveroutput 0: do not print the serveroutput
information. information

GSC_ATTR_C Client character set UTF8 or GBK


HARSET_TYPE

GSC_ATTR_N Precision of numeric [6, 52]


UM_WIDTH value output from zsql

GSC_ATTR_IN Whether to enable 1: Enable interactive timeout.


TERACTIVE_M interactive timeout 0: Disable interactive timeout.
ODE

GSC_ATTR_NL Session date format. It The default value is YYYY-MM-DD


S_DATE_FOR value is a string of up HH:MI:SS.
MAT to 60 characters,
including the end
character.

GSC_ATTR_NL Session timestamp The default value is YYYY-MM-DD


S_TIMESTAM format. It value is a HH:MI:SS.FF.
P_FORMAT string of up to 60 NOTE
characters, including FF indicates the number of digits after
the end character. the decimal point. Its maximum value is
6.
For example, FF1 indicates that the value
has one digit after the decimal point. FF3
indicates that the value has three digits
after the decimal point.

GSC_ATTR_SS Path of the SSL client Full path of the CA certificate file. If
L_CA root certificate file used this parameter is not set, the server
for verifying the device certificate is not checked
certificate on the server Default value: N/A

GSC_ATTR_SS Path of device Full path of the device certificate file


L_CERT certificate files on the Default value: N/A
SSL client, which are
used by the server to
check the client identity

GSC_ATTR_SS Private key of the SSL Full path of the private key file
L_KEY client certificate used Default value: N/A
for decryption and
digital signatures

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Attribute Description Value


Name

GSC_ATTR_SS SSL connection mode Valid value:


L_MODE 0: DISABLED, indicating that no SSL
connection is set up.
1: PREFERRED, indicating that SSL
connections will be set up on servers
supporting SSL and common
connections on other servers.
2: REQUIRED: indicating that SSL
connections are mandatory and
errors will be reported on servers not
supporting SSL.
3: VERIFY_CA, indicating that SSL
connections and certificate checks
are mandatory. (CA certificate must
be configured).
4: VERIFY_FULL, indicating that SSL
connections and certificate checks
are mandatory, and that the system
checks whether the CN field in the
certificate is the server IP address.

GSC_ATTR_SS Path of the SSL client Full path of the CRL file
L_CRL revocation list (CRL) file Default value: N/A

GSC_ATTR_SS Encryption password for Plaintext encrypted password of the


L_KEYPWD the private key file of private key
the SSL client. If this Default value: N/A
parameter is left blank,
the private key file is
not encrypted. You are
advised to encrypt it.

GSC_ATTR_CI Encryption algorithm Name of the encryption algorithm


PHER suite used by the SSL suite
client For details about supported
encryption algorithms, see Table 2-3.

GSC_ATTR_C Timeout interval for The unit is s and the default value is
ONNECT_TIM connection 10. The value -1 indicates no
EOUT timeout.

GSC_ATTR_S Communication interval The unit is s and the default value is


OCKET_TIME for a connection -1 indicating no timeout.
OUT

GSC_ATTR_AP Client type The default value is 1, indicating the


P_KIND GSC client. The value 0 indicates an
unknown client, 2 indicates a JDBC
client, and 3 indicates a zsql client.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-3 Encryption algorithms

Encryption 安全程度 Encryption Algorithm


Strength

stronger high DHE-RSA-AES256-GCM-SHA384

stronger high DHE-RSA-AES128-GCM-SHA256

stronger high ECDHE-ECDSA-AES256-GCM-


SHA384

stronger high ECDHE-ECDSA-AES128-GCM-


SHA256

stronger high ECDHE-RSA-AES256-GCM-SHA384

stronger high ECDHE-RSA-AES128-GCM-SHA256

stronger high DHE-DSS-AES256-GCM-SHA384

stronger high DHE-DSS-AES128-GCM-SHA256

stronger medium DHE-RSA-AES256-SHA256

stronger medium DHE-RSA-AES128-SHA256

stronger medium DHE-DSS-AES256-SHA256

stronger medium DHE-DSS-AES128-SHA256

stronger high DHE-RSA-AES256-CCM

stronger high DHE-RSA-AES128-CCM

API:
int gsc_set_conn_attr(gsc_conn_t conn, int attr, const void * data, unsigned int len);

Parameter:

● conn: object to be connected


● attr: connection attribute
● data: connection attribute value
● len: attribute value length. This parameter is valid only if the attribute value is
a string.

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_get_conn_attr
Description: Obtains the attributes of a connection. The following table lists the
supported connection attributes.

Table 2-4 Connection attributes

Attribute Name Function

GSC_ATTR_AUTO_C Whether to automatically commit a connection


OMMIT

GSC_ATTR_XACT_ST Not in use


ATUS

GSC_ATTR_EXIT_CO Whether to commit when exiting a zsql connection


MMIT

GSC_ATTR_SERVERO Whether zsql displays the serveroutput information.


UTPUT

GSC_ATTR_CHARSET Client character set


_TYPE

GSC_ATTR_NUM_WI Precision of numeric value output from zsql


DTH

GSC_ATTR_INTERAC Whether to enable interactive timeout


TIVE_MODE

GSC_ATTR_LOB_LOC Size of the LOB locator on the server


ATOR_SIZE

GSC_ATTR_SSL_CA Path of the SSL client root certificate file

GSC_ATTR_SSL_CERT Path of the SSL client device certificate file

GSC_ATTR_SSL_KEY Private key of the SSL client certificate

GSC_ATTR_SSL_MO SSL connection mode


DE

GSC_ATTR_SSL_CRL Path of the SSL CRL file

GSC_ATTR_SSL_KEYP Encryption password for the private key file of the SSL
WD client

GSC_ATTR_SSL_CIPH Encryption algorithm suite used by the SSL client


ER

GSC_ATTR_CONNEC Timeout interval for connection


T_TIMEOUT

GSC_ATTR_SOCKET_ Timeout interval for connection


TIMEOUT

GSC_ATTR_APP_KIN Client type


D

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

API:
int gsc_get_conn_attr(gsc_conn_t conn, int attr, void * data, unsigned int len, unsigned int * attr_len);

Parameter:
● conn: object to be connected
● attr: connection attribute
● data: address to be written to attributes
● len: length of the address to be written to attributes
● attr_len: attribute value length. This parameter is valid only if the attribute
value is a string.
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_error
Description: Obtains the error codes and error information on the connection.
This interface can be invoked if an interface fails to be executed.
API:
void gsc_get_error(gsc_conn_t conn, int * code, const char ** message);

Parameter:
● conn: object to be connected
● code: obtained error code
● message: obtained the error message
Return value: empty
Thread-safe: no

gsc_get_error_position
Description: Obtains the error location of a SQL statement that fails to be
executed on the connection and analyzes the cause of the error.
API:
void gsc_get_error_position(gsc_conn_t conn, unsigned short * line, unsigned short * column)

Parameter:
● conn: object to be connected
● line: error row
● column: error column
Return value: empty

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Thread-safe: no

gsc_get_message
Description: Obtains the error information about a connection. This interface can
be invoked when an interface fails to be executed.
API:
char* gsc_get_message(gsc_conn_t conn);

Parameter: conn specifies the object to be connected.


Return value: an error message
Thread-safe: no

gsc_disconnect
Description: Disconnects the database.
API:
void gsc_disconnect(gsc_conn_t conn);

Parameter: conn specifies the object to be connected.


Return value: empty
Thread-safe: no

gsc_get_sid
Description: Obtains the connection ID.
API:
unsigned int gsc_get_sid(gsc_conn_t conn);

Parameter: conn specifies the object to be connected.


Return value:
sid: connection ID
Thread-safe: no

gsc_cancel
Description: Cancels the ongoing operation on the connection, usually when the
operation times out.
API:
int gsc_cancel(gsc_conn_t conn, int sid);

Parameter:
● conn: object to be connected
● sid: connection ID
Return value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● 0: successful
● !=0: failed
Thread-safe: no

gsc_alloc_stmt
Description: Creates a handle object and uses it to prepare and execute SQL
statements.
API:
int gsc_alloc_stmt(gsc_conn_t conn, gsc_stmt_t * stmt);

Parameter:
● conn: object to be connected
● stmt: handle to be created
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_free_stmt
Description: Releases a handle
Precautions:
To use the stmt variable again after gsc_free_stmt is used, set stmt to NULL.
API:
void gsc_free_stmt(gsc_stmt_t stmt);

Parameter: stmt specifies the handle to be released.


Return value: empty
Thread-safe: no

gsc_set_stmt_attr
Description: Sets handle attributes.
The following table lists the supported handle attributes.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-5 Handle attributes

Attribute Name Description Value

GSC_ATTR_PREFETCH_R Maximum number of Maximum number of


OWS prefetched records in a prefetched records
response packet returned
by an SQL statement. If
this parameter is set to
0, the server returns a
maximum of 100 records
by default.

GSC_ATTR_PREFETCH_B Maximum prefetch Prefetch buffer size


UFFER buffer size used for
returning a response
packet during SQL
statement execution. If It
is set to 0, the server
returns 65536 by default.

GSC_ATTR_PARAMSET_SI Number of batch records Number of batch bound


ZE records

GSC_ATTR_ALLOWED_BA Maximum number of Number of allowed


TCH_ERRS errors allowed for batch errors
execution. Once the
number of errors exceeds
the value of this
parameter, the batch
execution stops.

GSC_ATTR_FETCH_SIZE Sets the number of Number of records to be


records to be read in read in batches
batches.

API:
int gsc_set_stmt_attr(gsc_stmt_t stmt, int attr, const void * data, unsigned int len);

Parameter:
● stmt: handle to be set
● attr: handle attribute to be set
● data: handle attribute value to be set
● len: attribute value length. This parameter is valid only if the attribute value is
a string.
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_get_stmt_attr
Description: Obtains the attributes of a handle.

The following table lists the supported handle attributes.

Table 2-6 Handle attributes

Attribute Name Function

GSC_ATTR_FETCHED Number of returned records in a query


_ROWS

GSC_ATTR_PREFETC Number of prefetched records (in a query)


H_ROWS

GSC_ATTR_PREFETC Size of the prefetch buffer (in a query)


H_BUFFER

GSC_ATTR_PARAMS Number of batch records


ET_SIZE

GSC_ATTR_AFFECTE Number of affected records in a query


D_ROWS

GSC_ATTR_RESULTS Whether any query results are returned for a query


ET_EXISTS

GSC_ATTR_COLUMN Number of queried columns


_COUNT

GSC_ATTR_STMT_TY Handle type (GSC_STMT_DML, GSC_STMT_DCL,


PE GSC_STMT_DDL, GSC_STMT_PL, or
GSC_STMT_EXPLAIN)

GSC_ATTR_PARAM_ Number of parameters bound to a SQL statement


COUNT

GSC_ATTR_MORE_R Whether any query records are to be returned (query


OWS records are returned in several batches)

GSC_ATTR_STMT_EO Whether the operation of obtaining a handle is complete


F

GSC_ATTR_FETCH_SI Obtains the number of records to be read in batches.


ZE

GSC_ATTR_ACTUAL_ Number of errors in batch execution


BATCH_ERRS

GSC_ATTR_ALLOWE Number of errors allowed for batch execution


D_BATCH_ERR

GSC_ATTR_SEROUTP Whether to output dbms_output.put_line of a stored


UT_EXISTS procedure

GSC_ATTR_RETURN Whether to output dbms_sql.return_result of a stored


RESULT_EXISTS procedure

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Attribute Name Function

GSC_ATTR_OUTPAR Number of output parameters of a stored procedure


AM_COUNT

API:
int gsc_get_stmt_attr(gsc_stmt_t pstmt, int attr, const void * data, unsigned int buf_len, unsigned int * len)

Parameter:

● stmt: handle to be obtained


● attr: handle attribute to be obtained
● data: address to be written to attributes
● buf_len: length of the address to be written to attributes
● len: attribute value length. This parameter is valid only if the attribute value is
a string.

Return value:

● 0: successful
● !=0: failed

Thread-safe: no

gsc_prepare
Description: Preprocesses SQL statements. To run SQL statements, you need to
invoke gsc_prepare and gsc_execute.

API:
int gsc_prepare(gsc_stmt_t stmt, const char * sql);

Parameter:

● stmt: handle
● sql: SQL statement

Return value:

● 0: successful
● !=0: failed

Thread-safe: no

gsc_bind_by_pos and gsc_bind_by_pos2


Description: Binds parameters based on their positions. The ind parameter is
optional and usually used in batch binding to identify the size of parameters to be
bound to each column. To bind to empty values, specify GSC_NULL. direction
indicates the parameter binding direction. Its value can be GSC_INPUT (default),
GSC_OUTPUT, or GSC_INOUT.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

NOTICE

● In this version, type cannot be set to the GSC_TYPE_TIMESTAMP type.


● If the binding is based on the GSC_TYPE_DATE type, the bound value must be
a 7-byte code. The encoding and decoding algorithms are as follows:
Converting the day, month, day, hour, minute, and second to a 7-byte code
date:
date[0] = year / 100 + 100;
date[1] = year % 100 + 100;
date[2] = mon;
date[3] = day;
date[4] = hour + 1;
date[5] = min + 1;
date[6] = sec + 1;
Converting a 7-byte code date to the year, month, day, hour, minute, and
second:
year = (date[0] - 100) * 100 + (date[1] - 100);
mon = date[2];
day = date[3];
hour = date[4] - 1;
min = date[5] - 1;
sec = date[6] - 1;

API:
int gsc_bind_by_pos(gsc_stmt_t stmt, unsigned int pos, int type, const void * data, int size, unsigned short *
ind);
int gsc_bind_by_pos2(gsc_stmt_t stmt, unsigned int pos, int type, const void * data, int size, unsigned short *
ind, int direction);

Parameter:

● stmt: handle
● pos: binding position
● type: type of the data to be bound
● data: value to be bound
● size: size of the data to be bound
● ind: size of the value to be bound
● direction: parameter binding direction

Return value:

● 0: successful
● !=0: failed

Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_bind_by_name and gsc_bind_by_name2


Description: Binds parameters based on their names. The ind parameter is
optional and usually used in batch binding to identify the size of parameters to be
bound to each column. To bind to empty values, specify GSC_NULL. direction
indicates the parameter binding direction. Its value can be GSC_INPUT (default),
GSC_OUTPUT, or GSC_INOUT.

NOTICE

In this version, type cannot be set to the GSC_TYPE_TIMESTAMP type.

API:
int gsc_bind_by_name(gsc_stmt_t stmt, const char * name, int type, const void * data, int size, unsigned
short * ind);
int gsc_bind_by_name2(gsc_stmt_t stmt, const char * name, int type, const void * data, int size, unsigned
short * ind, int direction);

Parameter:
● stmt: handle
● name: parameter name
● type: type of the data to be bound
● data: value to be bound
● size: size of the data to be bound
● ind: size of the value to be bound
● direction: parameter binding direction
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_column_count
Description: Obtains the number of queried columns by using handles. It should
be invoked after gsc_prepare.
API:
int gsc_get_column_count(gsc_stmt_t stmt, unsigned int * column_count);

Parameter:
● stmt: handle
● column_count: number of queried columns
Return value:
● 0: successful
● !=0: failed

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Thread-safe: no

gsc_desc_column_by_id
Description: Obtains the column description by column subscript, which starts
from 0.

The following table describes the column description.

Table 2-7 Column description

Name Description

*name Column name

size Column definition size

precision Column definition precision

scale Column definition scale

type Column data type

nullable Whether the column definition can be null (currently,


the value is always 1)

is_character Data type (0 indicates BYTE and 1 indicates CHAR)

API:
int gsc_desc_column_by_id(gsc_stmt_t stmt, unsigned int id, gsc_column_desc_t * desc);

Parameter:

● stmt: handle
● id: column subscript
● desc: description of the column to be returned

Return value:

● 0: successful
● !=0: failed

Thread-safe: no

gsc_desc_column_by_name
Description: Obtains the description of a column based on the column name. For
details about the column description, see Table 2-7.

API:
int gsc_desc_column_by_name(gsc_stmt_t pstmt, const char* col_name, gsc_column_desc_t * desc);

Parameter:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● pstmt: handle
● col_name: column name
● desc: description of the column to be returned
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_column_by_id
Description: Obtains query column data by column subscript. The returned
column data is encoded and can be converted.

Table 2-8 Conversion modes

Data Type Mode

GSC_TYPE_UINT32 uint32 value = *(uint32 *)data

GSC_TYPE_INTEGER int32 value = *(int32 *)data

GSC_TYPE_BIGINT int64 value = *(int64 *)data

GSC_TYPE_REAL double value = *( double *)data

GSC_TYPE_NUMBER Internal encoded data

GSC_TYPE_DECIMAL Internal encoded data

GSC_TYPE_DATE Internal encoded data

GSC_TYPE_TIMESTAMP Internal encoded data

GSC_TYPE_CHAR char *value = (char *)data

GSC_TYPE_VARCHAR char *value = (char *)data

GSC_TYPE_STRING char *value = (char *)data

GSC_TYPE_BINARY Internal encoded data

GSC_TYPE_VARBINARY Internal encoded data

GSC_TYPE_CLOB Internal encoded data

GSC_TYPE_BLOB Internal encoded data

GSC_TYPE_CURSOR -

GSC_TYPE_COLUMN -

GSC_TYPE_BOOLEAN int32 value = *(int32 *)data

GSC_TYPE_TIMESTAMP_TZ Internal encoded data

GSC_TYPE_TIMESTAMP_LTZ Internal encoded data

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Data Type Mode

GSC_TYPE_INTERVAL -

GSC_TYPE_INTERVAL_YM Internal encoded data

GSC_TYPE_INTERVAL_DS Internal encoded data

API:
int gsc_get_column_by_id(gsc_stmt_t stmt, unsigned int id, void ** data, unsigned int * size, unsigned int *
is_null);

Parameter:

● stmt: handle
● id: column subscript
● data: column data to be returned
● size: size of the column to be returned
● is_null: whether the column to be returned is empty

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_get_column_by_name
Description: Obtains query column data by column name. The returned column
data is encoded and can be converted.

For details about conversion modes, see Table 2-8.

API:
int gsc_get_column_by_name(gsc_stmt_t stmt, const char* name, void ** data, unsigned int * size, unsigned
int * is_null);

Parameter:

● stmt: handle
● name: column name
● data: column data to be returned
● size: size of the column to be returned
● is_null: whether the column to be returned is empty

Return value:

● 0: successful
● !=0: failed

Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_get_affected_rows
Description: Obtains the number of records in the current response packet for
SELECT and EXPLAIN statements; or obtains the number of affected records for
INSERT, DELETE, UPDATE, and MERGE statement.

API:
unsigned int gsc_get_affected_rows(gsc_stmt_t pstmt);

Parameter:

● pstmt: handle

pstmt: handle

Thread-safe: no

gsc_column_as_string
Description: Obtains column data by string.

Before importing column data, you need to apply for the required memory. The
memory size is the column description size returned by gsc_desc_column_by_id. If
available memory is insufficient, strings will be truncated, and errors will be
reported for other data types.

API:
int gsc_column_as_string(gsc_stmt_t stmt, unsigned int id, char * str, unsigned int buf_size);

Parameter:

● stmt: handle
● id: column subscript
● str: memory address where the column data is to be written
● buf_size: size of the column data to be written

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_bind_column
Description: Binds the queried column memory and applies for memory according
to the specified column description size.

● The interface invoking sequence is as follows: gsc_prepare, gsc_execute,


gsc_bind_column, and gsc_fetch. After gsc_fetch is invoked, the column data is
written to the bound memory. Only the data of the type of the queried
column or of the GSC_TYPE_STRING type can be bound.
– Method 1: If the data of the type of the queried column is bound, the
returned data is encoded and needs to be converted. (For basic data
types, you are advised to use this method to directly convert the data.)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

– Method 2: If data of the GSC_TYPE_STRING type is bound, the returned


data is a string. (If the bound memory is insufficient, the original data
will be truncated. Errors will be reported for other data types.)
For details about the memory bound to data types, see Table 2-9.
● The batch read capability is supported. The system queries the column
memory application based on the value of GSC_ATTR_FETCH_SIZE. Assume
that the column data type is GSC_TYPE_INTEGER. If the number of reads in a
batch is set to 3, the bind_ptr memory size transferred by the
gsc_bind_column interface is sizeof(int)x3 and the bind_size is sizeof(int).

Table 2-9 Bound memory


Data Type Bound Memory Size Bound Memory Size
(Method 1) (Method 2)

GSC_TYPE_UINT32 desc->size or GSC_NUMBER_BOUND_S


sizeof(uint32) IZE
uint32 value = *(uint32
*)data

GSC_TYPE_INTEGER desc->size or GSC_NUMBER_BOUND_S


sizeof(int32) IZE
int32 value = *(int32
*)data

GSC_TYPE_BIGINT desc->size or GSC_NUMBER_BOUND_S


sizeof(int64) IZE
int64 value = *(int64
*)data

GSC_TYPE_REAL desc->size or GSC_NUMBER_BOUND_S


sizeof(double) IZE
double value = *( double
*)data

GSC_TYPE_NUMBER desc->size GSC_NUMBER_BOUND_S


Internal encoded data IZE

GSC_TYPE_DECIMAL desc->size GSC_NUMBER_BOUND_S


Internal encoded data IZE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Data Type Bound Memory Size Bound Memory Size


(Method 1) (Method 2)

GSC_TYPE_DATE desc->size The bound memory is 7


Internal encoded data B.
The result format is as
follows:
The first byte is the
century + 100.
The second byte is the
year + 100.
The third byte is the
month.
The fourth byte is the
day.
The fifth byte is the hour
+ 1.
The sixth byte is the
minute + 1.
The seventh byte is the
second + 1.
(1) Converting the day,
month, day, hour,
minute, and second to a
7-byte date:
date[0] = year / 100
+ 100;
date[1] = year % 100
+ 100;
date[2] = mon;
date[3] = day;
date[4] = hour + 1;
date[5] = min + 1;
date[6] = sec + 1;
(2) Converting a 7-byte
code date to the year,
month, day, hour,
minute, and second:
year = (date[0] - 100) *
100 + (date[1] - 100);
mon = date[2];
day = date[3];
hour = date[4] - 1;
min = date[5] - 1;
sec = date[6] - 1;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Data Type Bound Memory Size Bound Memory Size


(Method 1) (Method 2)

GSC_TYPE_TIMESTAMP desc->size GSC_TIME_BOUND_SIZE


Internal encoded data The result format is
yyyy-mm-dd
hh24:mi:ss.ff3.

GSC_TYPE_CHAR desc->size+1 desc->size+1


char *value = (char
*)data

GSC_TYPE_VARCHAR desc->size+1 desc->size+1


char *value = (char
*)data

GSC_TYPE_STRING desc->size+1 desc->size+1


char *value = (char
*)data

GSC_TYPE_BINARY desc->size desc->size*2+1


Internal encoded data

GSC_TYPE_VARBINARY desc->size desc->size*2+1


Internal encoded data

GSC_TYPE_CLOB desc->size Specify the size of the


Internal encoded data input Character Large
Object (CLOB) data and
apply for memory as
needed.

GSC_TYPE_BLOB desc->size Specify the size of the


Internal encoded data input CLOB data and
apply for memory as
needed.

GSC_TYPE_CURSOR - -

GSC_TYPE_COLUMN - -

GSC_TYPE_BOOLEAN desc->size or GSC_BOOL_BOUND_SIZE


sizeof(int32) The result is true or
int32 value = *(int32 false.
*)data

GSC_TYPE_TIMESTAMP_T desc->size GSC_TIME_BOUND_SIZE


Z Internal encoded data The result format is
yyyy-mm-dd
hh24:mi:ss.ff3.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Data Type Bound Memory Size Bound Memory Size


(Method 1) (Method 2)

GSC_TYPE_TIMESTAMP_L desc->size GSC_TIME_BOUND_SIZE


TZ Internal encoded data The result format is
yyyy-mm-dd
hh24:mi:ss.ff3.

GSC_TYPE_INTERVAL - -

GSC_TYPE_INTERVAL_YM desc->size GSC_YM_INTERVAL_BOU


Internal encoded data ND_SIZE

GSC_TYPE_INTERVAL_DS desc->size GSC_DS_INTERVAL_BOU


Internal encoded data ND_SIZE

API:
int gsc_bind_column(gsc_stmt_t stmt, unsigned int id, unsigned short bind_type, unsigned short bind_size,
void * bind_ptr, unsigned short * ind_ptr);

Parameter:
● stmt: handle
● id: column subscript
● bind_type: type of the data to be bound
● bind_size: size of memory to be bound
● bind_ptr: address of memory to be bound
● ind_ptr: size of the column to be written
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_execute
Description: Runs SQL statements. This interface should be invoked after
gsc_prepare.
API:
int gsc_execute(gsc_stmt_t stmt);

Parameter: stmt specifies a handle.


Return value:
● 0: successful
● !=0: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_fetch
Description: Returns the number of rows obtained in a query. The interface is
invoked after the gsc_execute or gsc_query interface. The returned number of
rows is 0 or the number of records found.
API:
int gsc_fetch(gsc_stmt_t stmt, unsigned int * rows);

Parameter:
● stmt: handle
● rows: number of records to be returned
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_commit
Description: Commits uncompleted transactions. If manual committing is enabled,
after an update operation is performed, use this interface to commit the
transaction.
API:
int gsc_commit(gsc_conn_t conn);

Parameter: conn specifies the connection object.


Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_rollback and gsc_xa_rollback


Description: Rolls back uncompleted transactions.
If manual committing is enabled, to cancel the result of an update operation, call
this interface to roll back the transaction.
API:
int gsc_rollback(gsc_conn_t conn);
int gsc_xa_rollback(gsc_conn_t conn);

Parameter: conn specifies the connection object.


Return value:
● 0: successful
● !=0: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_set_autocommit
Description: Its function is the same as that of setting the
GSC_ATTR_AUTO_COMMIT parameter (whether to automatically commit
transactions) for gsc_set_conn_attr.
API:
void gsc_set_autocommit(gsc_conn_t conn, unsigned int auto_commit);

Parameter:
● conn: object to be connected
● auto_commit: whether to automatically commit transactions. 1: automatic, 0:
manual
Return value: none
Thread-safe: no

gsc_set_paramset_size
Description: Its function is the same as that of gsc_set_stmt_attr when setting
the GSC_ATTR_PARAMSET_SIZE parameter.
API:
void gsc_set_paramset_size(gsc_stmt_t pstmt, unsigned int sz);

Parameter:
● pstmt: handle
● sz: number of batch bound records
Return value: none
Thread-safe: no

gsc_query
Description: Runs SQL statements in query mode.
This interface is equivalent to gsc_prepare plus gsc_execute and cannot bind
parameters.
API:
int gsc_query(gsc_conn_t conn, const char * sql);

Parameter:
● conn: object to be connected
● sql: SQL statement to be executed
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_get_query_stmt
Description: Obtains the handle of a query. The handle can be used to invoke an
interface related to the handle.
API:
gsc_stmt_t gsc_get_query_stmt(gsc_conn_t conn);

Parameter: conn specifies the connection object.


Return value: query handle
Thread-safe: no

gsc_query_get_affected_rows
Description: Obtains the number of rows affected by SQL execution.
API:
unsigned int gsc_query_get_affected_rows(gsc_conn_t conn);

Parameter: conn specifies the connection object.


Return value: number of rows
Thread-safe: no

gsc_query_get_column_count
Description: Obtains the number of columns returned by the SQL query.
API:
unsigned int gsc_query_get_column_count(gsc_conn_t conn);

Parameter: conn specifies the connection object.


Return value: number of columns
Thread-safe: no

gsc_query_fetch
Description: Obtains the query result.
API:
int gsc_query_fetch(gsc_conn_t conn, unsigned int * rows);

Parameter:
● conn: object to be connected
● rows: number of obtained records
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_query_describe_column
Description: Obtains the description of a column.
API:
int gsc_query_describe_column(gsc_conn_t conn, unsigned int id, gsc_column_desc_t * desc);

Parameter:
● conn: object to be connected
● id: sequence number of a column (starting from 0)
● desc: description of the column to be returned
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_query_get_column
Description: Obtains column values.
API:
int gsc_query_get_column(gsc_conn_t conn, unsigned int id, void ** data, unsigned int * size, unsigned int *
is_null);

Parameter:
● conn: object to be connected
● id: sequence number of a column (starting from 0)
● data: column value to be returned
● size: length of the column value to be returned
● Is_null: whether the column value to be returned is empty
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_write_blob
Description: Writes data to BLOB columns.
API:
int gsc_write_blob(gsc_stmt_t pstmt, unsigned int pos, const void * data, unsigned int size);

Parameter:
● pstmt: handle
● pos: sequence number of a column (starting from 0)
● data: data to be written

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● size: length of the data to be written

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_write_clob
Description: Writes CLOB column data.

API:
int gsc_write_clob(gsc_stmt_t pstmt, unsigned int pos, const void * data, unsigned int size, unsigned int
*nchars);

Parameter:

● pstmt: handle
● pos: sequence number of a column (starting from 0)
● data: data to be written
● size: length of the data to be written
● nchars: number of characters to be written

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_write_batch_blob
Description: Writes data to BLOB columns in batches.

API:
int gsc_write_batch_blob(gsc_stmt_t pstmt, unsigned int id, unsigned int piece, const void * data, unsigned
int size);

Parameter:

● stmt: handle
● id: sequence number of a column (starting from 0)
● piece: sequence number of a batch (starting from 0)
● data: data to be written
● size: length of the data to be written

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

gsc_write_batch_clob
Description: Writes data to CLOB columns in batches.
API:
int gsc_write_batch_clob(gsc_stmt_t stmt, unsigned int id, unsigned int piece, const void * data, unsigned int
size, unsigned int *nchars);

Parameter:
● stmt: handle
● id: sequence number of a column (starting from 0)
● piece: sequence number of a batch (starting from 0)
● data: data to be written
● size: length of the data to be written
● nchars: number of characters to be written
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_read_blob_by_id
Description: Reads data from BLOB columns.
API:
int gsc_read_blob_by_id(gsc_stmt_t pstmt, unsigned int id,
unsigned int byte_offset, void * buffer, unsigned int size, unsigned int * nbytes, unsigned int *eof);

Parameter:
● pstmt: handle
● id: sequence number of a column (starting from 0)
● byte_offset: start byte of read data
● buffer: read column data
● size: length of read column data
● nbytes: length of read column (unit: byte)
● eof: whether column data reading is complete
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_read_blob
Description: Reads data from BLOB columns.
API:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

int gsc_read_blob(gsc_stmt_t pstmt, void * locator,


unsigned int byte_offset, void * buffer, unsigned int size, unsigned int * nbytes, unsigned int *eof);

Parameter:
● pstmt: handle
● locator: column pointer
● byte_offset: start byte of read data
● buffer: read column data
● size: length of read column data
● nbytes: length of read column (unit: byte)
● eof: whether column data reading is complete
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_read_clob_by_id
Description: Reads data from CLOB columns.
API:
int gsc_read_clob_by_id(gsc_stmt_t pstmt, unsigned int id, unsigned int byte_offset,
void * buffer, unsigned int size, unsigned int *nchars, unsigned int * nbytes, unsigned int *eof);

Parameter:
● pstmt: handle
● id: sequence number of a column (starting from 0)
● byte_offset: start byte of read data
● buffer: read column data
● size: length of read column data
● nchars: length of read characters
● nbytes: length of read column (unit: byte)
● eof: whether column data reading is complete
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_read_clob
Description: Reads data from CLOB columns.
API:
int gsc_read_clob(gsc_stmt_t pstmt, void * locator, unsigned int byte_offset, void * buffer, unsigned int
size, unsigned int *nchars, unsigned int * nbytes, unsigned int *eof);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter:
● pstmt: handle
● locator: column pointer
● byte_offset: start byte of read data
● buffer: read column data
● size: length of read column data
● nchars: length of read characters
● nbytes: length of read column (unit: byte)
● eof: whether column data reading is complete
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_fetch_serveroutput
Description: Obtains serveroutput information.
To use this interface, execute gsc_set_conn_attr to set GSC_ATTR_SERVEROUTPUT
to 1 to enable the serveroutput function.
API:
int gsc_fetch_serveroutput(gsc_stmt_t stmt, char ** data, unsigned int * len);

Parameter:
● stmt: handle
● data: serveroutput data
● len: size of the serveroutput data
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_implicit_resultset
Description: Obtains multiple result sets (dbms_sql.return_result).
If the returned value of resultset is NULL, there is no more result set. You can use
resultset to invoke other interfaces, such as gsc_fetch, to further obtain cursor
data.
API:
int gsc_get_implicit_resultset(gsc_stmt_t stmt, gsc_stmt_t * resultset);

Parameter:
● stmt: handle

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● resultset: cursor of a single result set


Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_fetch_outparam
Description: Obtains output parameters. Currently, it can only be used for stored
procedures.
API:
int gsc_fetch_outparam(gsc_stmt_t stmt, unsigned int * rows);

Parameter:
● stmt: handle
● rows: number of output parameter records to be returned
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_outparam_by_id
Description: Obtains the data of the output parameter column.
The following table describes the data in the output parameter columns obtained
based on subscripts.

Table 2-10 Output parameter columns

Name Description

*data Output parameter data

size Size of output parameter data

* is_null Whether the output parameter is


empty

API:
int gsc_get_outparam_by_id(gsc_stmt_t stmt, unsigned int id, void ** data, unsigned int * size, unsigned int
* is_null)

Parameter:
● stmt: handle
● id: subscript of the output parameter

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● data: pointer used for obtaining output parameters


● size: output parameter length
● is_null: whether the output parameter is empty.
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_desc_outparam_by_id
Description: Obtains the description of output parameters based on their
subscripts.
API:
int gsc_desc_outparam_by_id(gsc_stmt_t stmt, unsigned int id, gsc_outparam_desc_t * desc);

Parameter:
● stmt: handle
● id: subscript of the output parameter
● desc: description of the output parameter column
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_desc_outparam_by_name
Description: Obtains the description of output parameters based on their names.
API:
int gsc_desc_outparam_by_name(gsc_stmt_t stmt, const char* name, gsc_outparam_desc_t * desc);

Parameter:
● stmt: handle
● name: output parameter name
● desc: description of the output parameter column
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_outparam_by_name
Description: Obtains the data of a specified output parameter column based on
the output parameter column name.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

API:
int gsc_get_outparam_by_name(gsc_stmt_t stmt, const char* name, void ** data, unsigned int * size,
unsigned int * is_null);

Parameter:
● stmt: handle
● name: output parameter column name
● * data: output parameter column data
● size: size of the output parameter column
● Is_null: whether the output parameter column is NULL
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_outparam_as_string_by_id
Description: Obtains the information about output parameters based on their
subscripts.
API:
int gsc_outparam_as_string_by_id(gsc_stmt_t stmt, unsigned int id, char * str, unsigned int buf_size);

Parameter:
● stmt: handle
● id: subscript of the output parameter column
● str: start address that stores data of the output parameter column
● buf_size: data size of the output parameter column
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_outparam_as_string_by_name
Description: Obtains the information about output parameters based on their
names.
API:
int gsc_outparam_as_string_by_name(gsc_stmt_t stmt, const char* name, char * str, unsigned int buf_size);

Parameter:
● stmt: handle
● name: output parameter column name
● str: start address that stores data of the output parameter column

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● buf_size: data size of the output parameter column

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_query_multiple
Description: Runs multiple SQL statements.

API:
int gsc_query_multiple(gsc_conn_t conn, const char * sql);

Parameter:

● conn: connection handle


● sql: SQL statements to be executed

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_get_query_resultset
Description: Obtains the result set of running multiple SQL statements.

API:
int gsc_get_query_resultset(gsc_conn_t pconn, gsc_stmt_t * resultset);

Parameter:

● pconn: connection handle


● resultset: result set

Return value:
● 0: successful
● !=0: failed

Thread-safe: no

gsc_describle
Description: Obtains the description of a specified object. The column description
of the object is obtained by invoking the gsc_desc_column_by_id interface.

API:
int gsc_describle(gsc_stmt_t stmt, char * objptr, gsc_desc_type_t dtype);

Parameter:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● stmt: handle
● objptr: object whose description information is to be obtained
● dtype: object type Currently, the following object types are supported:
– 0 or 1: table
– 2: view
– 3: synonym
– 4: query statement
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

gsc_get_batch_error
Description: Obtains the error information about batch execution. The number of
errors that can be obtained can be set by invoking the gsc_set_stmt_attr interface
to set GSC_ATTR_ALLOWED_BATCH_ERRS of the handle.
API:
int gsc_get_batch_error(gsc_stmt_t stmt, unsigned int * line, char ** err_message, unsigned int * rows);

Parameter:
● stmt: handle
● line: batch execution location where errors occur
● err_message: error information about batch execution
● rows: number of error SQL statements
Return value:
● 0: successful
● !=0: failed
Thread-safe: no

2.2.5 Examples
The following example demonstrates how to develop an application based on the
C APIs provided by GaussDB 100. For example, bind parameters to insert data.
// This example shows how to insert a row of data into the test_num table by binding parameters.
#include <stdio.h>
#include "gsc.h"

#define CM_RETURN_IF_FALSE(ret, expect) \


do { \
if ((ret) != (expect)) \
{\
printf("failed line = %u\r\n", __LINE__);\
return GSC_ERROR; \
}\
} while (0)

int test_num()
{

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

int f0 = 2147483647;
long long f1 = 9223372036854775807;
double f2 = 222.222;
unsigned int f3 = 4294967295;
char f4[50] = "1234567890";
char f5[50] = "333.333";
unsigned short len[6] = { 4, 8, 8, 4, 10, 7 };

gsc_conn_t gsc_conn = NULL;


gsc_stmt_t gsc_stmt = NULL;

// Create a connection.
CM_RETURN_IF_FALSE(gsc_alloc_conn(&gsc_conn) , GSC_SUCCESS);

// Establish the connection.


CM_RETURN_IF_FALSE(gsc_connect(gsc_conn, "127.0.0.1:1611", "sys", "sys") , GSC_SUCCESS);

// Apply for handles.


CM_RETURN_IF_FALSE(gsc_alloc_stmt(gsc_conn, &gsc_stmt) , GSC_SUCCESS);

// Prepare to delete the existing test table test_num.


if (gsc_prepare(gsc_stmt, "drop table if exists test_num") != GSC_SUCCESS)
{
return GSC_ERROR;
}

// Delete the existing test table test_num.


if (gsc_execute(gsc_stmt) != GSC_SUCCESS)
{
return GSC_ERROR;
}

// Prepare to create the test table test_num.


if (gsc_prepare(gsc_stmt, "create table test_num(f0 int, f1 bigint, f2 real, f3 uint, f4 number(10,0), f5
decimal)") != GSC_SUCCESS)
{
return GSC_ERROR;
}

// Create the test table.


if (gsc_execute(gsc_stmt) != GSC_SUCCESS)
{
return GSC_ERROR;
}

// Prepare to insert data to the test_num table by binding parameters.


if (gsc_prepare(gsc_stmt, "insert into test_num values (:1, :2, :3, :4, :5, :6)") != GSC_SUCCESS)
{
return GSC_ERROR;
}

gsc_set_paramset_size(gsc_stmt, 1);// Set the number of data records to be inserted by binding


parameters to 1.

// Bind the first column. The rest is processed by analogy.


CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 0, GSC_TYPE_INTEGER, &f0, 4, &len[0]),
GSC_SUCCESS);
CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 1, GSC_TYPE_BIGINT, &f1, 8, &len[1]), GSC_SUCCESS);
CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 2, GSC_TYPE_REAL, &f2, 8, &len[2]), GSC_SUCCESS);
CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 3, GSC_TYPE_UINT32, &f3, 4, &len[3]), GSC_SUCCESS);
CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 4, GSC_TYPE_NUMBER, f4, 50, &len[4]),
GSC_SUCCESS);
CM_RETURN_IF_FALSE(gsc_bind_by_pos(gsc_stmt, 5, GSC_TYPE_DECIMAL, f5, 50, &len[5]),
GSC_SUCCESS);

// Insert the data.


if (gsc_execute(gsc_stmt) != GSC_SUCCESS)
{
return GSC_ERROR;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

// Commit the transaction.


if (gsc_commit(gsc_conn) != GSC_SUCCESS)
{
return GSC_ERROR;
}

gsc_free_stmt(gsc_stmt);// Release handles.


gsc_disconnect(gsc_conn);// Break the connection.
gsc_free_conn(gsc_conn);// Release the connection.
gsc_conn = NULL;
gsc_stmt = NULL;

return GSC_SUCCESS;
}

// The main program calls the definition method test_num().


void main()
{
int result = test_num();
return;
}

2.3 Development Based on JDBC


Java Database Connectivity (JDBC) is Java API for executing SQL statements,
providing unified accessing interface for different relational databases, based on
which applications process data. GaussDB 100 supports JDBC4.0 and requires JDK
1.8 or later for code compiling.

2.3.1 JDBC Package and Driver Class


This section describes the JDBC package and database driver provided by GaussDB
100.

JDBC Package
JDBC package name: com.huawei.gauss.jdbc.ZenithDriver.jar
The JDBC package is in the GAUSSDB100-V300R001C00-CLIENT-JDBC folder in
the installation package directory.

Driver Class
Before establishing a database connection, load the
com.huawei.gauss.jdbc.ZenithDriver database driver class.

2.3.2 Development Process


This section introduces the application development process based on JDBC.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Figure 2-2 Application development process based on JDBC

2.3.3 Loading a Driver


Load the database driver before creating a database connection.
You can load the driver in the following ways:
● Implicitly load it in code:
Class.forName("com.huawei.gauss.jdbc.ZenithDriver");
● Transfer its parameter during JVM startup: java -
Djdbc.drivers=com.huawei.gauss.jdbc.ZenithDriver jdbctest

jdbctest is the name of a test application.

2.3.4 Connecting to a Database


After a database is connected, the database can be used to execute SQL
statements to operate data.
Before remotely accessing the database, set the listening IP address LSNR_IP and
port number LSNR_PORT in the zengine.ini file. A maximum of eight listening IP
addresses can be set at a time. The IP addresses are separated by commas (,).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Function Prototype
To use a JDBC to create a database connection, use the following function:
DriverManager.getConnection(String url, String user, String password);

Parameters

Table 2-11 Database connection parameters


Parameter Description

url Database connection descriptor. Its format is as


follows:
jdbc:zenith:@ip:port[?key=value[&key=value]..]
NOTE
● ip: name of a database server
● port: port number of the database server
● URL connection attributes are separated by
ampersands (&). Each attribute is a key-value pair in
the form of key=value.
● Table 2-12 describes the key values in the URL.

user Database user

password Password of a database user

Table 2-12 Key values supported in the URL


Key Value Description

loginTimeout Timeout duration for establishing a database


connection (unit: second)

socketTimeout Socket timeout duration for connecting to a server


to run commands (unit: second)

useSSL Indicates whether to use SSL to establish a


connection. The default value is true, indicating
that the SSL connection is used. This parameter
specifies whether the client uses SSL. The setting
takes effect only when useSSL is set to true.
NOTE
If useSSL=true is specified when the client establishes a
connection, but the server does not support SSL, the
client sets up a common connection with the server.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Key Value Description

requireSSL Indicates whether to forcibly use SSL to establish a


connection.
● The default value is false, indicating that SSL is
not forcibly used.
● true: This command is used to forcibly use SSL.
If the server does not support SSL, an error is
reported during connection setup.

verifyServerCertificate Indicates whether to verify the server certificate.


The default value is false, indicating that the
verification is not performed.

isRevocationEnabled Indicates whether to enable crl verification. The


default value is false, indicating that the
verification is disabled.

sslCipher Set the SSL key algorithm suite. The following


algorithm suites are supported:
● TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
● TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

● Currently, GaussDB 100 JDBC supports two connection modes: Common TCP and SSL.
SSL modes are classified into unidirectional authentication and bidirectional
authentication.
● If the SSL function is enabled but no certificate information is configured on the JDBC,
the JDBC uses unidirectional authentication to connect to the database.
● If a certificate file is configured on the JDBC and the SSL switch is enabled, the JDBC
uses more secure bidirectional authentication to connect to the database.

The JDBC supports the following certificate configuration modes:

● When the application JVM is started, the Java command line parameters
(recommended) are used, for example, -
Djavax.net.ssl.trustStore=path_to_truststore_file.
● Set system parameters in the code, for example,
System.setProperty("javax.net.ssl.trustStore","path_to_truststore_file").

Table 2-13 The environment variables used for SSL bidirectional authentication
are described as follows:

JVM environment Parameter Description


variable

javax.net.ssl.keyStore Location of the SSL keyStore file. The keystore file can
be regarded as a key library. The key file contains the
public key, private key, and digital signature.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

JVM environment Parameter Description


variable

javax.net.ssl.keyStore keyStore type. The default value is JKS.


Type

javax.net.ssl.keyStore SSL keyStore password


Password

javax.net.ssl.trustStor Location of the SSL trustStore file. The truststore file


e stores only the digital certificate that contains only the
public key, which indicates the trusted certificate.

javax.net.ssl.trustStor trustStore type. The default value is JKS.


eType

javax.net.ssl.trustStor Password for logging in to the SSL trustStore


ePassword

Example for Connecting to the Database


//The following code encapsulates database connection operations into an interface. The database can then
be connected using an authorized username and a password.

public static Connection GetConnection(String username, String passwd)


{
//Set the driver class.
String driver = "com.huawei.gauss.jdbc.ZenithDriver";
//Database connection descriptor.
String sourceURL = "jdbc:zenith:@10.255.255.1:1888";
Connection conn = null;
try {
// Load the database driver.
Class.forName(driver).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}

try {
// Create a database connection.
//getConnection(String url, String user, String password)
conn = DriverManager.getConnection(sourceURL,username,passwd);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
return null;
}

return conn;
};

Configuring the SSL Certificate for the JDBC Client


To configure the SSL certificate for the JDBC client, perform the following steps:
After the configuration, if useSSL=true is set in the connection string, the JDBC
uses SSL bidirectional authentication to establish a connection.

Step 1 Generate and configure the truststore file.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

1. Convert the self-authentication certificate cacert.pem to generate the


truststore certificate available for Java.
For details about how to generate the self-authentication certificate
cacert.pem, see Database Configuration > Configuring the Database
Connection > Establishing TCP/IP Connections in SSL Mode > Creating a
Self-Authentication Certificate in GaussDB 100 V300R001C00 Security
Hardening Guide.
2. Use the java keytool tool to convert the cacert.pem file to the truststore file
in the bin directory of JDK or JRE.
shell> keytool -importcert -alias GaussCACert -file cacert.pem -keystore truststore -storepass
mypassword

3. Configure the new truststore.


The following two configuration modes are supported:
– Use Java command line parameters.
-Djavax.net.ssl.trustStore=path_to_truststore_file
-Djavax.net.ssl.trustStorePassword=mypassword

– Set system parameters.


System.setProperty("javax.net.ssl.trustStore","path_to_truststore_file");
System.setProperty("javax.net.ssl.trustStorePassword","mypassword");

Step 2 Generate and configure the keystore file.


1. Convert the client certificate file (client.crt) and client private key
(client.key) to generate a Java keystore file.
For details about how to generate the client certificate file client.crt and
client private key client.key, see Database Configuration > Configuring the
Database Connection > Establishing TCP/IP Connections in SSL Mode >
Creating a Self-Authentication Certificate in GaussDB 100 V300R001C00
Security Hardening Guide.
2. Use the OpenSSL tool to convert the client certificate and private key file to a
PKCS #12 file.
shell> openssl pkcs12 -export -in client.crt -inkey client.key -name "gaussclient" -passout
pass:mypassword -out client-keystore.p12

3. Use the keytool to convert the file generated in the previous step to java
keystore.
shell> keytool -importkeystore -srckeystore client-keystore.p12 -srcstoretype pkcs12 -srcstorepass
mypassword -destkeystore keystore -deststoretype JKS -deststorepass mypassword

4. Configure the new keystore.


The following two configuration modes are supported:
– Use Java command line parameters.
-Djavax.net.ssl.keyStore=path_to_keystore_file
-Djavax.net.ssl.keyStorePassword=mypassword

– Set system parameters.


System.setProperty("javax.net.ssl.keyStore","path_to_keystore_file");
System.setProperty("javax.net.ssl.keyStorePassword","mypassword");

----End

2.3.5 Running SQL Statements


Applications run SQL statements to perform operations on data in a database.
This section describes how to run SQL statements.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Executing an Ordinary SQL Statement


Perform the following steps to run an ordinary SQL statement (a statement that
does not pass parameters):

Step 1 Create a statement object by triggering the createStatement method in


Connection.
Statement stmt = con.createStatement();

Step 2 Execute the SQL statement by triggering the executeUpdate method in Statement.
int rc = stmt.executeUpdate("CREATE TABLE tab1(id INTEGER, name VARCHAR(32))");

Step 3 Close the statement object.


stmt.close();

----End

Executing a Prepared SQL Statement


Pre-compiled statements were once complied and optimized and can have
additional parameters for different usage. For the statements have been pre-
compiled, the execution efficiency is greatly improved. If you want to execute a
statement for several times, use a precompiled statement. Perform the following
procedures:

Step 1 Create a prepared statement object by calling the prepareStatement method in


Connection.
PreparedStatement pstmt = con.prepareStatement("UPDATE tab1 SET col1 = ? WHERE key = 1");

Step 2 Set parameters by triggering the setShort method in PreparedStatement.


pstmt.setShort(1, (short)2);

Step 3 Execute the precompiled SQL statement by triggering the executeUpdate method
in PreparedStatement.
int rowcount = pstmt.executeUpdate();

Step 4 Close the precompiled statement object by calling the close method in
PreparedStatement.
pstmt.close();

----End

Batch Processing
When a prepared statement batch processes multiple pieces of similar data, the
database creates only one query plan. This improves the compilation and
optimization efficiency. Perform the following procedures:

Step 1 Create a prepared statement object by calling the prepareStatement method in


Connection.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO tab1 VALUES (?)");

Step 2 Call the setShort parameter for each piece of data, and call addBatch to confirm
that the setting is complete.
pstmt.setShort(1, (short)2);
pstmt.addBatch();

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Step 3 Execute batch processing by calling the executeBatch method in


PreparedStatement.
int[] rowcount = pstmt.executeBatch();

Step 4 Close the precompiled statement object by calling the close method in
PreparedStatement.
pstmt.close();

Do not terminate a batch processing action when it is ongoing; otherwise, the database
performance will deteriorate. Therefore, disable the automatic submission function during
batch processing, and manually submit every several lines. The statement for disabling
automatic submission is conn.setAutoCommit(false);.

----End

Calling a Stored Procedure


Step 1 Create a precompiled stored procedure by calling the prepareCall method in
Connection.
CallableStatement callStmt = conn.prepareCall("call p_test(?,?)");

Step 2 Invoke CallableStatement to set input parameter values and registerOutParameter


to set the output parameter types.
callStmt.setInt(1, 999);
callStmt.registerOutParameter(2, java.sql.Types.REF_CURSOR); // The standard type defined in the
java.sql.Types class is used.

Step 3 Invoke the execute method of CallableStatement to run the precompiled stored
procedure.
callStmt.execute();

Step 4 Invoke CallableStatement to obtain output parameters value of the stored


procedures.
-- Obtain the value based on the output parameter subscript.
ResultSet rs = (ResultSet)callStmt.getObject(2);
-- Obtain the value based on the output parameter name.
ResultSet rs = (ResultSet)callStmt.getObject("out_cursor"); // The out_cursor string is the name of the
second parameter in the p_test stored procedure.

Step 5 Invoke the close method of CallableStatement to close the precompiled stored
procedure.
callStmt.close();

----End

2.3.6 Processing Data in a Result Set


After the SELECT statement is executed, a result set is returned. GaussDB 100
provides a series of methods to process data in the result set.

Setting a Result Set Type


Different types of result sets are applicable to different application scenarios.
Applications select proper types of result sets based on requirements. Before
executing an SQL statement, you must create a statement object. Some methods
of creating statement objects can set the type of a result set. The related
Connection methods are as follows:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

// Create a PreparedStatement object.


preparedStatement(String sql, int resultSetType, int resultSetConcurrency);
preparedStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability);

Positioning a Cursor in a Result Set


ResultSet objects include a cursor pointing to the current data row. The cursor is
initially positioned before the first row. The next method moves the cursor to the
next row from its current position. When a ResultSet object does not have a next
row, a call to the next method returns false. Therefore, this method is used in the
while loop for result set iteration. However, the JDBC driver provides more cursor
positioning methods for scrollable result sets, which allows positioning cursor in
the specified row. Table 2-14 describes these methods.

Table 2-14 Methods for positioning a cursor in a result set


Method Description

next() Moves cursor to the next row from its


current position.

Obtaining Data from a Result Set


ResultSet objects provide a variety of methods to obtain data from a result set.
Table 2-15 lists the common methods for obtaining data. If you want to know
more about other methods, see JDK official documents.

Table 2-15 Common methods for obtaining data from a result set
Method Description

int getInt(int columnIndex) Retrieves the value of the column


designated by a column index in the
current row as an int.

int getInt(String columnLabel) Retrieves the value of the column


designated by a column label in the
current row as an int.

String getString(int columnIndex) Retrieves the value of the column


designated by a column index in the
current row as a String.

String getString(String columnLabel) Retrieves the value of the column


designated by a column label in the
current row as a String.

Date getDate(int columnIndex) Retrieves the value of the column


designated by a column index in the
current row as a Date.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Description

Date getDate(String columnLabel) Retrieves the value of the column


designated by a column name in the
current row as a Date.

2.3.7 DataSource Support and Configuration Description


GaussDB 100 JDBC supports the following three DataSource classes:
● com.huawei.gauss.datasource.GSSimpleDataSource
● com.huawei.gauss.datasource.GSConnectionPoolDataSource
● com.huawei.gauss.datasource.GSPoolingDataSource
The common parent class of the three DataSource classes is
com.huawei.gauss.datasource.GSDataSourceBase.
This class is the basis of the three GaussDB 100 DataSource classes. The following
table lists the interfaces contained in this class.

Table 2-16 com.huawei.gauss.datasource.GSDataSourceBase base class interfaces


Return Value Method Thread-safe

Connection getConnection() Yes

Connection getConnection(String, String) Yes

String getServerName() Yes

Void setServerName(String) No

String getDatabaseName() Yes

void setDatabaseName(String) No

String getDescription() Yes

String getUser() Yes

void setUser(String) No

String getPassword() Yes

void setPassword(String); No

int getPortNumber() Yes

void setPortNumber(int) No

String getUrl() Yes

Reference getReference() Yes

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Value Method Thread-safe

void initializeFrom(BaseDataSourc No
e)

int getLoginTimeout() Yes

void setLoginTimeout(int) Yes

PrintWriter getLogWriter() Yes

void setLogWriter(PrintWriter) Yes

Logger getParentLogger() Yes

com.huawei.gauss.datasource.GSSimpleDataSource
This is a simple DataSource that provides non-pooling connections. To use this
DataSource, you must set databaseName. Other parameters (serverName,
portNumber, user, and password) are optional. For details about these
parameters, see the description of the parent class. The following table describes
the exclusive or rewritten interfaces of this class.

Table 2-17 Exclusive or rewritten interfaces of


com.huawei.gauss.datasource.GSSimpleDataSource

Return Value Method Thread-safe

String getDescription() Yes

boolean isWrapperFor(Class<?>) Yes

T unWrap(Class<T>) Yes

com.huawei.gauss.datasource.GSConnectionPoolDataSource
This class is the DataSource that implements the
javax.sql.ConnectionPoolDataSource interface. When the DataSource needs to be
configured for the application or middleware, this class can be set. This class can
be used when you configure the connection pool. To use this DataSource, you
must set databaseName. Other parameters (serverName, portNumber, user,
and password) are optional. For details about these parameters, see the
description of the parent class. The following table describes the exclusive or
rewritten interfaces of this class.

Table 2-18 Exclusive or rewritten interfaces of


com.huawei.gauss.datasource.GSConnectionPoolDataSource

Return Value Method Thread-safe

String getDescription() Yes

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Value Method Thread-safe

PooledConnecti getPooledConnection() Yes


on

PooledConnecti getPooledConnection(String, Yes


on String)

boolean isDefaultAutoCommit() Yes

void setDefaultAutoCom- No
mit(boolean)

com.huawei.gauss.datasource.GSPoolingDataSource
This is a DataSource that provides pooling connections, which contain the
implementation of a connection pool. Do not use this class if the application or
middleware uses a connection pool. To use this DataSource, you must set
dataSourceName, databaseName, user, and password. Other parameters
(serverName, portNumber, initialConnections, and maxConnections) are
optional. For details about these parameters, see the description of the parent
class. The following table describes the exclusive or rewritten interfaces of this
class.

Table 2-19 Exclusive or rewritten interfaces of


com.huawei.gauss.datasource.GSPoolingDataSource

Return Value Method Thread-safe

GSPoolingDataS getDataSource(String) Yes


ource

String getDescription() Yes

void setServerName(String) Yes

void setDatabaseName(String) Yes

void setUser(String) Yes

void setPassword(String) Yes

void setPortNumber(int) Yes

int getInitialConnections() Yes

void setInitialConnections(int) Yes

int getMaxConnections() Yes

void setMaxConnections(int) Yes

String getDataSourceName() Yes

void setDataSourceName(String) Yes

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Value Method Thread-safe

void initialize() Yes

Conneciton getConnection(String, String) Yes

Connection getConnection() Yes

void close() Yes

Reference getReference() Yes

Boolean isWrapperFor(Class<?>) Yes

T unwrap(Class<T>) Yes

2.3.8 Closing a Connection


After you complete required data operations in the database, close the database
connection.
Call the close method to close the connection.
conn.close();

2.3.9 Examples
This example illustrates how to develop applications based on GaussDB 100 JDBC
interfaces.
Before performing this example, ensure that the user for connecting to the
database exists in the database. If the user does not exist, see CREATE USER and
GRANT to create the user and grant permissions to it.
If whitelist checking is enabled, you need to configure the IP address whitelist. For
details, see Database Usage > Configuring Client Access Authentication in
GaussDB 100 V300R001C00 User Guide (Standalone).

Examples
//DBtest.java
// This example illustrates the main processes of JDBC-based development, covering database connection
creation, table creation, and data insertion.

package com.huawei.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

class ExitHandler extends Thread {


private Statement cancel_stmt = null;

public ExitHandler(Statement stmt) {


super("Exit Handler");
this.cancel_stmt = stmt;
}

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

public void run() {


System.out.println("exit handle");
try {
if (this.cancel_stmt != null&&!this.cancel_stmt.isClosed())
{
this.cancel_stmt.cancel();
}
} catch (SQLException e) {
System.out.println("cancel queyr failed.");
e.printStackTrace();
}
}
}

public class OLTPConnectDemo {

// Create a database connection.


public static Connection GetConnection(String username, String passwd) {
String driver = "com.huawei.gauss.jdbc.ZenithDriver";
String sourceURL = "jdbc:zenith:@192.168.0.1:1888";
Connection conn = null;
try {
// Load the database driver.
Class.forName(driver).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}

try {
// Create a database connection.
//getConnection(String url, String user, String password)
conn = DriverManager.getConnection(sourceURL,username,passwd);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
return null;
}

return conn;
};

// Execute an ordinary SQL statement. Create a jdbc_test1 table.


public static void CreateTable(Connection conn) {
Statement stmt = null;
try {
stmt = conn.createStatement();

// add ctrl+c handler


Runtime.getRuntime().addShutdownHook(new ExitHandler(stmt));

// Run an ordinary SQL statement.


int rc = stmt
.executeUpdate("CREATE TABLE IF NOT EXISTS jdbc_test1(col1 INTEGER,col2 VARCHAR(10))");
System.out.println("CREATE TABLE succeed!");

stmt.close();
} catch (SQLException e) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

// Run the preprocessing statement to insert data in batches.


public static void BatchInsertData(Connection conn) {
PreparedStatement pst = null;

try {
// Generate a prepared statement.
pst = conn.prepareStatement("INSERT INTO jdbc_test1 VALUES (?,?)");
for (int i = 0; i < 3; i++) {
// Add parameters.
pst.setInt(1, i);
pst.setString(2, "data " + i);
pst.addBatch();
}
// Run batch processing.
pst.executeBatch();
System.out.println("INSERT INTO succeed!");
pst.close();
} catch (SQLException e) {
if (pst != null) {
try {
pst.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}

// Run the precompilation statement to update data.


public static void ExecPreparedSQL(Connection conn) {
PreparedStatement pstmt = null;
try {
pstmt = conn
.prepareStatement("UPDATE jdbc_test1 SET col2 = ? WHERE col1 = 1");
pstmt.setString(1, "new Data");
int rowcount = pstmt.executeUpdate();

System.out.println("UPDATE succeed!");
pstmt.close();
} catch (SQLException e) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}

/**
* Main process. Call static methods one by one.
* @param args
*/
public static void main(String[] args) {
String userName = "gaussdba";
String password = "gaussdb_123";
// Create a database connection.
Connection conn = GetConnection(userName, password);

// Create a table.
CreateTable(conn);

// Insert data in batches.


BatchInsertData(conn);

// Run the precompilation statement to update data.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

ExecPreparedSQL(conn);

// Close the connection to the database.


try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}

2.3.10 JDBC Interface Reference


This section describes common JDBC interfaces. For more interfaces, check JDK 1.8
(software package) and JDBC 4.0.

2.3.10.1 java.sql.Connection
This section describes the support for java.sql.Connection, the database connection
interface.

The methods in this interface are not thread safe.

Table 2-20 Support status for java.sql.Connection

Return Type Method Name

void close()

boolean isReadOnly()

boolean isClosed()

boolean isValid(int)

DatabaseMetaData getMetaData()

void clearWarnings()

void commit()

Blob createBlob()

Clob createClob()

boolean getAutoCommit()

String getCatalog()

Properties getClientInfo()

String getClientInfo(String)

int getTransactionIsolation()

Map getTypeMap()

CallableStatement prepareCall(String)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

PreparedStatement prepareStatement(String, int)

PreparedStatement prepareStatement(String)

void rollback()

void setAutoCommit(boolean)

void setCatalog(String)

void setClientInfo(Properties)

void setClientInfo(String, String)

void setSchema(String)

Statement createStatement()

void setReadOnly(boolean)

int getHoldability()

CallableStatement prepareCall(String, int, int)

CallableStatement prepareCall(String, int, int, int)

PreparedStatement prepareStatement(String, int, int)

PreparedStatement prepareStatement(String, int, int, int)

void setHoldability(int)

void setTransactionIsolation(int)

Statement createStatement(int, int)

Statement createStatement(int, int, int)

NOTICE

● 接口内部默认使用自动提交模式,若通过setAutoCommit(false)关闭自动提交,将
会导致后面执行的语句都受到显式事务(明确指定事务的开始)包裹,此时需要手
动调用commit()方法提交事务。
● Savepoints are not supported.

2.3.10.2 java.sql.DatabaseMetaData
This section describes the support for Java.sql.DatabaseMetaData, a database
object definition interface.
该接口中的方法都不是线程安全的。

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-21 Support status for java.sql.DatabaseMetaData


Return Type Method Name

String getURL()

boolean isReadOnly()

String getUserName()

int getResultSetHoldability()

Connection getConnection()

boolean dataDefinitionCausesTransactionCom-
mit()

boolean dataDefinitionIgnoredInTransactions()

boolean deletesAreDetected(int)

boolean doesMaxRowSizeIncludeBlobs()

boolean generatedKeyAlwaysReturned()

String getCatalogSeparator()

String getCatalogTerm()

ResultSet getCatalogs()

ResultSet getColumns(String, String, String,


String)

int getDatabaseMajorVersion()

int getDatabaseMinorVersion()

String getDatabaseProductName()

String getDatabaseProductVersion()

int getDefaultTransactionIsolation()

int getDriverMajorVersion()

int getDriverMinorVersion()

String getDriverName()

String getDriverVersion()

String getExtraNameCharacters()

String getIdentifierQuoteString()

ResultSet getIndexInfo(String, String, String,


boolean, boolean)

int getJDBCMajorVersion()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

int getJDBCMinorVersion()

int getMaxBinaryLiteralLength()

int getMaxCatalogNameLength()

int getMaxCharLiteralLength()

int getMaxColumnNameLength()

int getMaxColumnsInGroupBy()

int getMaxColumnsInIndex()

int getMaxColumnsInOrderBy()

int getMaxColumnsInSelect()

int getMaxColumnsInTable()

int getMaxConnections()

int getMaxCursorNameLength()

int getMaxIndexLength()

int getMaxProcedureNameLength()

int getMaxRowSize()

int getMaxSchemaNameLength()

int getMaxStatementLength()

int getMaxStatements()

int getMaxTableNameLength()

int getMaxTablesInSelect()

int getMaxUserNameLength()

String getNumericFunctions()

ResultSet getPrimaryKeys(String, String, String)

String getProcedureTerm()

RowIdLifetime getRowIdLifetime()

String getSQLKeywords()

int getSQLStateType()

String getSchemaTerm()

ResultSet getSchemas()

String getSearchStringEscape()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

String getStringFunctions()

ResultSet getTableTypes()

ResultSet getTables(String, String, String,


String[])

ResultSet getTypeInfo()

boolean insertsAreDetected(int)

boolean isCatalogAtStart()

boolean locatorsUpdateCopy()

boolean nullPlusNonNullIsNull()

boolean nullsAreSortedAtEnd()

boolean nullsAreSortedAtStart()

boolean nullsAreSortedHigh()

boolean nullsAreSortedLow()

boolean othersDeletesAreVisible(int)

boolean othersInsertsAreVisible(int)

boolean othersUpdatesAreVisible(int)

boolean ownDeletesAreVisible(int)

boolean ownInsertsAreVisible(int)

boolean ownUpdatesAreVisible(int)

boolean storesLowerCaseIdentifiers()

boolean storesLowerCaseQuotedIdentifiers()

boolean storesMixedCaseIdentifiers()

boolean storesMixedCaseQuotedIdentifiers()

boolean storesUpperCaseIdentifiers()

boolean storesUpperCaseQuotedIdentifiers()

boolean supportsANSI92EntryLevelSQL()

boolean supportsANSI92FullSQL()

boolean supportsANSI92IntermediateSQL()

boolean supportsAlterTableWithAddColumn()

boolean supportsAlterTableWithDropColumn()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

boolean supportsBatchUpdates()

boolean supportsCatalogsInDataManipulation()

boolean supportsCatalogsInIndexDefinitions()

boolean supportsCatalogsInPrivilegeDefini-
tions()

boolean supportsCatalogsInProcedureCalls()

boolean supportsCatalogsInTableDefinitions()

boolean supportsColumnAliasing()

boolean supportsConvert()

boolean supportsConvert(int, int)

boolean supportsCoreSQLGrammar()

boolean supportsCorrelatedSubqueries()

boolean supportsDataDefinitionAndDataMani-
pulationTransactions()

boolean supportsDataManipulationTransaction-
sOnly()

boolean supportsDifferentTableCorrelation-
Names()

boolean supportsExpressionsInOrderBy()

boolean supportsExtendedSQLGrammar()

boolean supportsFullOuterJoins()

boolean supportsGetGeneratedKeys()

boolean supportsGroupBy()

boolean supportsGroupByUnrelated()

boolean supportsIntegrityEnhancementFacili-
ty()

boolean supportsLikeEscapeClause()

boolean supportsLimitedOuterJoins()

boolean supportsMinimumSQLGrammar()

boolean supportsMixedCaseIdentifiers()

boolean supportsMixedCaseQuotedIdentifiers()

boolean supportsMultipleOpenResults()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

boolean supportsMultipleResultSets()

boolean supportsMultipleTransactions()

boolean supportsNamedParameters()

boolean supportsNonNullableColumns()

boolean supportsOpenCursorsAcrossCommit()

boolean supportsOpenCursorsAcrossRollback()

boolean supportsOpenStatementsAcrossCom-
mit()

boolean supportsOpenStatementsAcrossRoll-
back()

boolean supportsOrderByUnrelated()

boolean supportsOuterJoins()

boolean supportsPositionedDelete()

boolean supportsPositionedUpdate()

boolean supportsResultSetHoldability(int)

boolean supportsSavepoints()

boolean supportsSchemasInDataManipulation()

boolean supportsSchemasInIndexDefinitions()

boolean supportsSchemasInPrivilegeDefini-
tions()

boolean supportsSchemasInProcedureCalls()

boolean supportsSchemasInTableDefinitions()

boolean supportsSelectForUpdate()

boolean supportsStatementPooling()

boolean supportsStoredFunctionsUsingCallSyn-
tax()

boolean supportsStoredProcedures()

boolean supportsSubqueriesInComparisons()

boolean supportsSubqueriesInExists()

boolean supportsSubqueriesInIns()

boolean supportsSubqueriesInQuantifieds()

boolean supportsTableCorrelationNames()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 70


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

boolean supportsTransactions()

boolean supportsUnion()

boolean supportsUnionAll()

boolean updatesAreDetected(int)

boolean usesLocalFilePerTable()

boolean usesLocalFiles()

boolean supportsResultSetConcurrency(int, int)

boolean supportsResultSetType(int)

boolean supportsTransactionIsolationLevel(int)

2.3.10.3 java.sql.Driver
This section describes the support for Java.sql.Driver, the database driver interface.

The methods in this interface are thread safe.

Table 2-22 Support status for java.sql.Driver

Return Type Method Name

boolean acceptsURL(String url)

Connection connect(String url, Properties info)

boolean jdbcCompliant()

int getMajorVersion()

int getMinorVersion()

2.3.10.4 java.sql.PreparedStatement
This section describes the support for java.sql.PreparedStatement, the prepared
statement interface.

The methods in this interface are not thread safe.

Table 2-23 Support status for java.sql.PreparedStatement

Return Type Method Name

void setTimestamp(int, Timestamp,


Calendar)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 71


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

void setTimestamp(int, Timestamp)

boolean execute()

void setBoolean(int, boolean)

void setByte(int, byte)

void setDouble(int, double)

void setFloat(int, float)

void setInt(int, int)

void setLong(int, long)

void setShort(int, short)

void setTime(int, Time, Calendar)

void setTime(int, Time)

void addBatch()

void clearParameters()

ResultSet executeQuery()

int executeUpdate()

ResultSetMetaData getMetaData()

void setBigDecimal(int, BigDecimal)

void setBinaryStream(int, InputStream)

void setBinaryStream(int, InputStream, int)

void setBinaryStream(int, InputStream,


long)

void setBlob(int, InputStream)

void setBlob(int, InputStream, long)

void setBlob(int, Blob)

void setBytes(int, byte[])

void setCharacterStream(int, Reader, long)

void setCharacterStream(int, Reader, int)

void setCharacterStream(int, Reader)

void setClob(int, Reader)

void setClob(int, Reader, long)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 72


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

void setClob(int, Clob)

void setDate(int, Date)

void setDate(int, Date, Calendar)

void setNull(int, int)

void setObject(int, Object)

void setObject(int, Object, int)

void setObject(int, Object, int, int)

void setString(int, String)

boolean execute(String, int)

boolean execute(String)

boolean isClosed()

ResultSet executeQuery(String)

int executeUpdate(String, int)

int executeUpdate(String)

void cancel()

void clearBatch()

void clearWarnings()

int[] executeBatch()

int getFetchSize()

ResultSet getGeneratedKeys()

int getMaxRows()

boolean getMoreResults(int)

boolean getMoreResults()

int getQueryTimeout()

ResultSet getResultSet()

int getUpdateCount()

SQLWarning getWarnings()

void setFetchSize(int)

void setMaxRows(int)

void setQueryTimeout(int)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 73


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

Connection getConnection()

boolean execute(String, int[])

boolean execute(String, String[])

int executeUpdate(String, String[])

int executeUpdate(String, int[])

int getFetchDirection()

int getResultSetConcurrency()

int getResultSetHoldability()

int getResultSetType()

void setFetchDirection(int)

● Execute addBatch() and execute() only after running clearBatch().


● Batch is not cleared by calling executeBatch(). Clear batch by explicitly calling
clearBatch().
● After bounded variables of a batch are added, if you want to reuse these values (add a
batch again), set*() is not necessary.
● The following methods are inherited from java.sql.Statement: close, execute,
executeQuery, executeUpdate, getConnection, getResultSet, getUpdateCount, isClosed,
and setMaxRows

2.3.10.5 java.sql.ResultSet
This section describes the support for Java.sql.ResultSet, the execution result set
interface.

The methods in this interface are not thread safe.

Table 2-24 Support status for java.sql.ResultSet

Return Type Method Name

Object getObject(String)

Object getObject(int)

boolean getBoolean(int)

boolean getBoolean(String)

byte getByte(String)

byte getByte(int)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 74


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

short getShort(int)

short getShort(String)

int getInt(int)

int getInt(String)

long getLong(String)

long getLong(int)

float getFloat(String)

float getFloat(int)

double getDouble(String)

double getDouble(int)

byte[] getBytes(int)

byte[] getBytes(String)

boolean next()

void close()

int getType()

Date getDate(String)

Date getDate(int, Calendar)

Date getDate(String, Calendar)

Date getDate(int)

boolean isClosed()

String getString(String)

String getString(int)

Time getTime(int)

Time getTime(String, Calendar)

Time getTime(String)

Time getTime(int, Calendar)

Timestamp getTimestamp(String, Calendar)

Timestamp getTimestamp(int, Calendar)

Timestamp getTimestamp(String)

Timestamp getTimestamp(int)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 75


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

ResultSetMetaData getMetaData()

void clearWarnings()

int getFetchDirection()

int getFetchSize()

SQLWarning getWarnings()

void setFetchSize(int)

void afterLast()

void beforeFirst()

int findColumn(String)

BigDecimal getBigDecimal(String)

BigDecimal getBigDecimal(int)

InputStream getBinaryStream(String)

InputStream getBinaryStream(int)

Blob getBlob(String)

Blob getBlob(int)

Reader getCharacterStream(int)

Reader getCharacterStream(String)

Clob getClob(String)

Clob getClob(int)

int getConcurrency()

int getHoldability()

int getRow()

Statement getStatement()

boolean isAfterLast()

boolean isBeforeFirst()

boolean isFirst()

boolean isLast()

boolean wasNull()

void setFetchDirection(int)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 76


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● One statement cannot have multiple opened ResultSets.


● The cursor that is used for traversing the ResultSet cannot be opened after committed.

2.3.10.6 java.sql.ResultSetMetaData
This section describes the support for Java.sql.ResultSetMetaData, the ResultSet
object information interface.

The methods in this interface are not thread safe.

Table 2-25 Support status for java.sql.ResultSetMetaData

Return Type Method Name

boolean isReadOnly(int)

String getCatalogName(int)

int getColumnDisplaySize(int)

String getColumnLabel(int)

String getSchemaName(int)

String getTableName(int)

boolean isCaseSensitive(int)

boolean isCurrency(int)

boolean isDefinitelyWritable(int)

boolean isSearchable(int)

boolean isSigned(int)

boolean isWritable(int)

int getColumnCount()

String getColumnName(int)

int getPrecision(int)

int getScale(int)

int getColumnType(int)

boolean isAutoIncrement(int)

String getColumnTypeName(int)

String getColumnClassName(int)

boolean isWrapperFor(Class)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 77


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

2.3.10.7 java.sql.Statement
This section describes the support status for java.sql.Statement, the SQL statement
interface.

The methods in this interface are not thread safe.

Table 2-26 Support status for java.sql.Statement

Return Type Method Name

boolean execute(String, int)

boolean execute(String)

void close()

boolean isClosed()

ResultSet executeQuery(String)

int executeUpdate(String, int)

int executeUpdate(String)

void cancel()

void clearWarnings()

int getFetchSize()

ResultSet getGeneratedKeys()

int getMaxRows()

boolean getMoreResults(int)

boolean getMoreResults()

int getQueryTimeout()

ResultSet getResultSet()

int getUpdateCount()

SQLWarning getWarnings()

void setFetchSize(int)

void setMaxRows(int)

void setQueryTimeout(int)

Connection getConnection()

boolean execute(String, int[])

boolean execute(String, String[])

int executeUpdate(String, String[])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 78


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

int executeUpdate(String, int[])

int getFetchDirection()

int getResultSetConcurrency()

int getResultSetHoldability()

int getResultSetType()

void setFetchDirection(int)

2.3.10.8 java.sql.CallableStatement
java.sql.CallableStatement是SQL语句接口,主要用于执行存储过程,本节将介绍对此
接口的支持情况。
该接口中的方法都不是线程安全的。

Table 2-27 对 java.sql.CallableStatement 的支持情况


返回值类型 方法名

Object getObject(int)

Object getObject(String)

boolean getBoolean(String)

boolean getBoolean(int)

byte getByte(String)

byte getByte(int)

short getShort(String)

short getShort(int)

int getInt(String)

int getInt(int)

long getLong(String)

long getLong(int)

float getFloat(int)

float getFloat(String)

double getDouble(int)

double getDouble(String)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 79


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

返回值类型 方法名

byte[] getBytes(int)

byte[] getBytes(String)

String getString(String)

String getString(int)

Time getTime(int)

Time getTime(String)

Time getTime(int, Calendar)

Time getTime(String, Calendar)

Timestamp getTimestamp(String, Calendar)

Timestamp getTimestamp(int)

Timestamp getTimestamp(int, Calendar)

Timestamp getTimestamp(String)

Date getDate(String, Calendar)

Date getDate(String)

Date getDate(int, Calendar)

Date getDate(int)

BigDecimal getBigDecimal(String)

BigDecimal getBigDecimal(int)

Blob getBlob(int)

Blob getBlob(String)

Reader getCharacterStream(String)

Reader getCharacterStream(int)

Clob getClob(String)

Clob getClob(int)

boolean wasNull()

void registerOutParameter(int, int)

void setTimestamp(int, Timestamp,


Calendar)

void setTimestamp(int, Timestamp)

boolean execute()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 80


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

返回值类型 方法名

void setBoolean(int, boolean)

void setByte(int, byte)

void setDouble(int, double)

void setFloat(int, float)

void setInt(int, int)

void setLong(int, long)

void setShort(int, short)

void setTime(int, Time, Calendar)

void setTime(int, Time)

void addBatch()

void clearParameters()

ResultSet executeQuery()

int executeUpdate()

ResultSetMetaData getMetaData()

void setBigDecimal(int, BigDecimal)

void setBinaryStream(int, InputStream)

void setBinaryStream(int, InputStream, int)

void setBinaryStream(int, InputStream,


long)

void setBlob(int, InputStream)

void setBlob(int, InputStream, long)

void setBlob(int, Blob)

void setBytes(int, byte[])

void setCharacterStream(int, Reader, long)

void setCharacterStream(int, Reader, int)

void setCharacterStream(int, Reader)

void setClob(int, Reader)

void setClob(int, Reader, long)

void setClob(int, Clob)

void setDate(int, Date)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 81


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

返回值类型 方法名

void setDate(int, Date, Calendar)

void setNull(int, int)

void setObject(int, Object)

void setObject(int, Object, int)

void setObject(int, Object, int, int)

void setString(int, String)

boolean execute(String, int)

boolean execute(String)

boolean isClosed()

Connection getConnection()

ResultSet executeQuery(String)

int executeUpdate(String, int)

int executeUpdate(String)

void cancel()

void clearBatch()

void clearWarnings()

int[] executeBatch()

int getFetchSize()

ResultSet getGeneratedKeys()

int getMaxRows()

boolean getMoreResults(int)

boolean getMoreResults()

int getQueryTimeout()

ResultSet getResultSet()

int getUpdateCount()

SQLWarning getWarnings()

void setFetchSize(int)

void setMaxRows(int)

void setQueryTimeout(int)

int getFetchDirection()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 82


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

返回值类型 方法名

int getResultSetConcurrency()

int getResultSetHoldability()

int getResultSetType()

void setFetchDirection(int)

2.3.10.9 java.sql.Blob
java.sql.Blob是Blob接口,主要用于绑定或获取数据库Blob字段,本节将介绍对此接口
的支持情况。

The methods in this interface are not thread safe.

Table 2-28 Support status for java.sql.Blob

Return Type Method Name

byte[] getBytes(long, int)

long length()

OutputStream setBinaryStream(long)

int setBytes(long, byte[], int, int)

int setBytes(long, byte[])

InputStream getBinaryStream()

void free()

2.3.10.10 java.sql.Clob
This section describes the support for java.sql.Clob, a CLOB interface used for
binding or obtaining CLOB columns.

The methods in this interface are not thread safe.

Table 2-29 Support status for java.sql.Clob

Return Type Method Name

long length()

Writer setCharacterStream(long)

int setString(long, String, int, int)

int setString(long, String)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 83


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return Type Method Name

Reader getCharacterStream()

String getSubString(long, int)

void free()

2.3.11 Non-standard Interfaces Provided by Zenith


Zenith interfaces are a set of non-standard JDBC API methods provided for users.
This section describes some non-standard JDBC APIs.

2.3.11.1 com.huawei.gauss.jdbc.GaussConnection
GaussConnection is a Zenith connection interface. This section describes the non-
standard interfaces provided by this interface.
The methods in this interface are not thread safe.

Table 2-30 Support status for com.huawei.gauss.jdbc.GaussConnection


Retur Method Description
n
Value

void setSessionTZ(String) Used for querying data of the timestamp with


local time zone type through JDBC. If the
client time zone is not set before data query,
an error is reported and you are prompted to
set SessionTimezone through the interface.
Set this parameter only once for a connection,
unless the value of SessionTimezone needs
to be changed.

2.3.11.2 com.huawei.gauss.jdbc.GaussPrepareStatement
GaussPrepareStatement is a Zenith prepared statement interface. This section
describes the non-standard interfaces provided by this interface.
The methods in this interface are not thread safe.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 84


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-31 Support status for com.huawei.gauss.jdbc.GaussPrepareStatement


Retur Method Description
n
Value

void setFixedCHAR(int, Used for setting a fixed-length bind


String) parameter of the CHAR type for JDBC. When
a bind parameter set by using this interface is
compared with a value of the CHAR type, all
spaces at the end of the strings are ignored.

2.4 Development Based on Python

2.4.1 Python Driver Dynamic Library


In GaussDB 100, applications can be developed using Python interfaces.

Dynamic Library Introduction


Dynamic library: pyzenith.so
The dynamic library of Python2 is in the GAUSSDB100-V300R001C00-CLIENT-
PYTHON-EULER20SP8-64bit folder in the installation package directory. The
dynamic library of Python3 is stored in the GAUSSDB100-V300R001C00-CLIENT-
PYTHON3-EULER20SP8-64bit folder in the installation package directory. The
installation package contains libzeclient.so and __init__.pyc.

Using the Dynamic Library


GaussDB 100 uses Python 2.7.x. To use the library, configure the path of the
pyzenith.so file in LD_LIBRARY_PATH and run the import pyzenith command to
load it before connecting to the database.

2.4.2 Development Process


This section introduces the application development process based on Python.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 85


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Figure 2-3 Application development process based on Python

2.4.3 Connecting to a Database


If the Python driver is used to connect to a database, the pyzenith.connect method
will be invoked to establish the connection.
After the Connect method is used to connect to the database, a Connection-
class object will be returned. For the definition and usage of the args and kwargs
parameters, see Connect method.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 86


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Function Prototype
● SSL connections are not used.
– Parameters in args format
connect('IP','username','password','port')

– Parameters in kwargs format


connect(host='IP',user='username',passwd='password',port='port')

● An SSL connection is used.


connect('IP','username','password','port', '/gs_regress/ssl/ca.crt','/gs_regress/ssl/client-cert.crt','/
gs_regress/ssl/client-key.crt')

Alternatively,
connect('IP','username','password','port', '/gs_regress/ssl/ca.crt','/gs_regress/ssl/client-cert.crt','/
gs_regress/ssl/client-key.crt','','','P')

For details about the parameters supported by the connect method, see Table
2-33.

Examples
Connect to a database without using SSL connections.
# Load the pyzenith module.
import pyzenith
# Connect to a database.
host='192.168.0.1'
username='gaussdba'
password='gaussdb_123'
port='1888'

conn=pyzenith.connect(host,username,password,port)

2.4.4 Running SQL Statements


Before running an SQL statement, you need to invoke the cursor method of the
Connection class to obtain a cursor, and then use the cursor to invoke the
execute method to run the SQL statement.

To obtain the result set, you can use one of the fetch methods in Cursor Class.

Function Prototype
● Run an SQL statement and automatically commit it.
# Create a cursor.
c=conn.cursor()
# Set the automatic committing.
conn.autocommit(True)
# Invoke the execute method to create a table.
c.execute("create table tablename(relational_properties)")
# Invoke the execute method to insert data.
c.execute("insert into tablename values(expression [ , ... ])")
# Disable the cursor.
c.close()

● Roll back an SQL statement. Manually commit it.


conn.rollback()

● Manually submit an SQL statement.


conn.commit()

● Run an SQL statement and obtain tuples.


# Invoke the execute method to obtain the query result.
c.execute("select * from tablename")

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 87


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

# Obtain all results using the fetchall method.


row =c.fetchall()

Examples
● Run an SQL statement and automatically commit it.
# Create a cursor.
c=conn.cursor()
# Set the automatic committing.
conn.autocommit(True)
# Invoke the execute method to create a table.
c.execute("create table testexecute(a int,b char(10),c date)")
# Invoke the execute method to insert data.
c.execute("insert into testexecute values(1,'s','2012-12-13')")
# Disable the cursor.
c.close()
# Close a database connection.
conn.close()

● Run the SQL statement and roll back or manually commit it.
# Load the pyzenith module.
import pyzenith
# Connect to the database as user gaussdba. The password is gaussdb_123 and the port number is
1888.
host='192.168.0.1'
username='gaussdba'
password='gaussdb_123'
port='1888'

conn=pyzenith.connect(host,username,password,port)
# Create a cursor.
c=conn.cursor()
# Invoke the execute method to create a table.
c.execute("create table testexecute(a int,b char(10),c date)")
# Invoke the execute method to insert data.
c.execute("insert into testexecute values(1,'s','2012-12-13')")
# Roll back or commit a transaction.
conn.rollback() or conn.commit()
# Disable the cursor.
c.close()
# Close a database connection.
conn.close()

● Run an SQL statement and obtain tuples.


# Load the pyzenith module.
import pyzenith
# Connect to the database as user gaussdba. The password is gaussdb_123 and the port number is
1888.
host='192.168.0.1'
username='gaussdba'
password='gaussdb_123'
port='1888'

conn=pyzenith.connect(host,username,password,port)
# Create a cursor.
c=conn.cursor()
# Invoke the execute method to create a table.
c.execute("create table testexecute(a int,b char(10),c date)")
# Invoke the execute method to create a table.
c.execute("insert into testexecute values(1,'s','2012-12-13')")
# Invoke the execute method to obtain the query result.
c.execute("select * from testexecute")
# Obtain all results using the fetchall method.
row =c.fetchall()
# Disable the cursor.
c.close()
# Disable the cursor.
conn.close()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 88


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

2.4.5 Closing a Connection


After using a connection, you need to invoke the close() method to close it.

Function Prototype
conn.close()

2.4.6 Python Interface Reference

Global Variables

Table 2-32 Global parameters

Parameter Parameter Description Usage

apilevel DBAPI level. The current pyzenith.apilevel


value is 2.0.

threadsafety Thread security level of pyzenith.threadsafety


the interface. The current
value is 2.

paramstyle Parameter format. The pyzenith.paramstyle


current value is
pyformat.

Connect Method

Table 2-33 Connect parameters

Parameter Parameter Description Usage

host String variable, specifying the IP address of the Used in the


database server format of args
or kwargs
user String variable, specifying the username for
connecting to a database

passwd String variable, specifying the password for


logging in to a database

port String variable, specifying the listening port of a


database server

ssl_ca String variable, specifying the CA file of SSL. This


parameter is required if the server requires an
SSL connection.

ssl_cert String variable, specifying the client-cert file of


SSL. This parameter is required if the server
requires an SSL connection.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 89


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter Parameter Description Usage

ssl_key String variable, specifying the client-key file of


SSL. This parameter is required if the server
requires an SSL connection.

ssl_crl String variable, specifying the CRL file of SSL. If


the file does not exist, this parameter can be
empty.

ssl_keypwd String variable, specifying the password for


generating SSL. This parameter can be empty if
the password is not set.

ssl_mode String variable. Its value can be:


D (SSL connections are disabled.)
P (SSL connections are preferred. If the server
does not support SSL, the connection can still
succeed. This is the default value.)
R (An SSL connection must be used. If the server
does not support SSL, the connection will fail.)
V (Verify the certificate information on the
server.)

logintimeou INT variable, specifying the connection timeout -


t duration. The unit is second. If this parameter is
not set, the default value 10s is used.

sockettimeo INT variable, specifying the socket timeout -


ut duration. The unit is second. If this parameter is
not set, the default value 600s is used.

Connection Class

Table 2-34 Methods of the Connection class


Method Method Description Example Thread-
safe

__init__(self, *args, Method invoked during the - Yes


**kwargs) initialization of the
Connection class to initiate
the connection to the
database.

autocommit(self, Whether to automatically conn.autoco Yes


isautocommit) commit a transaction. mmit(True)
Isautocommit is of the BOOL
type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 90


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Method Description Example Thread-


safe

cursor(self) Returns a Cursor-class object. cursor = Yes


conn.cursor()

commit(self) Commits a transaction. It can conn.commi Yes


be invoked if manual t()
transaction committing is
enabled.

rollback(self) Rolls back a transaction. conn.rollbac Yes


k()

close(self) Closes a database connection. conn.close() Yes

Cursor Class

Table 2-35 Cursor class attributes


Attribute Attribute Description Example Thread-safe
Name

description Obtains the column description of cursor.descri Yes


a query statement. ption

rowcount Obtains the number of rows cursor.rowco Yes


generated by the operation unt
(number of rows affected by DML.
The value returned for the SELECT
statement is 0.)

lastrowid Returns the value automatically cursor.lastro Yes


generated in the wid
AUTO_INCREMENT column of the
last INSERT statement of the
current session.

Table 2-36 Methods of the Cursor class


Method Method Description Example Threa
d-safe

close(self) Closes a cursor object. cursor.close() No

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 91


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Method Description Example Threa


d-safe

execute(self, ● Runs an SQL statement. cursor.execute("select * Yes


sql[,parameter The SQL statement from table")
s]) parameter is an SQL cursor.execute("insert
statement string. into tb_1 values (:1)",
● Parameters are optional. [('1',),])
If parameters are
specified, this method is
equivalent to
executemany. Currently,
SELECT is not supported
if parameters are used.

executemany( ● Runs SQL statements for cursor.executemany("in Yes


self,sql,param batch binding. Currently, sert into tb_1 values (:
eters) SELECT is not supported. 1)",[('1',),])
● The parameter must be
a list consisting of tuples.
The value of a tuple
must be a string.
● The maximum number
of rows is 512, and the
maximum number of
rows is 1024.

fetchall(self) Obtains all tuples in the cursor.fetchall() Yes


result set.

fetchone(self) Obtains the next tuple in cursor.fetchone() Yes


the result set.

fetchmany(siz Obtains the next size tuple cursor.fetchmany() Yes


e) in the result set.

execute_ex(sel ● Runs an SQL statement. cursor.execute_ex("sele Yes


f,sql[,paramet The SQL statement ct * from table")
ers]) parameter is an SQL cursor.execute_ex("inse
statement string. rt into tb_1 values (:
● Parameters are optional. 1)",[('1',),])
If parameters are
specified, this method is
equivalent to
executemany_ex.
Currently, SELECT is not
supported if parameters
are used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 92


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Method Description Example Threa


d-safe

executemany_ ● Execute the SQL cursor.executemany_ex( Yes


ex(self,sql,par statement for batch "insert into tb_1 values
ameters) binding. Currently, (:1)",[('1',),])
SELECT is not supported.
● The parameter must be
a list of tuples. The tuple
can be a string or of a
Python data type.
● The maximum number
of rows is 512, and the
maximum number of
rows is 1024.

fetchall_ex(sel Obtains all tuples in the cursor.fetchall_ex() Yes


f) result set. The time,
numeric, and Boolean
values are returned as
values of Python data
types. Other types are
returned as strings.

fetchone_ex(s Obtains the next tuple in cursor.fetchone_ex() Yes


elf) the result set. The time,
numeric, and Boolean
values are returned as
values of Python data
types. Other types are
returned as strings.

fetchmany_e Obtains the next size tuples cursor.fetchmany_ex() Yes


x(size) in the result set. The time,
numeric, and Boolean
values are returned as
values of Python data
types. Other types are
returned as strings.

Time Objects

Table 2-37 Time methods

Method Name Method Example Thread-


Description safe

Date(year,month,d Constructs an pyzenith.Date(2018,2,29) No


ay) object that
contains a
date.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 93


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Name Method Example Thread-


Description safe

Time(hour,minute,s Constructs an pyzenith.Time(-1, 0, 0) No


econd) object that
contains time.

Timestamp(year,m Constructs an pyzenith.Timestamp(2018,1, No


onth,day,hour,minu object that 1,1,1,1,12342)
te,second,usec) contains a
timestamp.

DateFromTicks(tick Construct a pyzenith.DateFromTicks(12 No


s) date value of a 34567890)
given ticks
value.

TimeFromTicks(tick Constructs a pyzenith.TimeFromTicks(12 No


s) time value of a 34567890)
given ticks
value.

TimestampFromTic Constructs a pyzenith.TimestampFromTic No


ks(ticks) timestamp ks(1234567890)
value of a
given ticks
value.

2.5 基于 GO 开发
2.5.1 Go Driver
The Go driver is released as source code. An upper-layer application imports the
code to an application project and compiles it together with the application. The
Zenith Go driver is developed from the Zenith C driver and is encapsulated using
the cgo tool.
The Go driver has three types of files: Go API files, C drive library files, and C
header files. The lib subdirectory stores the C driver dynamic library, and the
include subdirectory stores the header file involved in the C driver cgo.

NOTICE

The Go driver version depends on GCC5.4 or later.


The Go driver version is GO1.12.1 or later.

2.5.2 Driver Installation and Use


● Obtain the Zenith Go driver package, decompress it to a proper directory, and
set the following environment variables:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 94


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

export PKG_CONFIG_PATH=Driver directory


export LD_LIBRARY_PATH=Driver directory/lib:$ LD_LIBRARY_PATH
export GOPATH=Driver directory:$GOPATH

● Change the driver path in the gsc.pc file.


prefix=Driver directory

2.5.3 Development Process


The Zenith Go driver complies with the rule of the Go language third-party library.
You only need to import the driver to the application program and save the driver
code in the directory specified by GOPATH.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 95


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Figure 2-4 Process of using the Go language to develop applications

2.5.4 Connecting to a Database


When you invoke the standard SQL interface open of the Go language to create a
database connection, a connected object is returned to transfer the driver name

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 96


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

(zenith) and description string. For details about the parameters, see the open
method.

Function Prototype
● Syntax reference
func open(driverName, dataSourceName string) (*DB, error)
● Parameter description: driverName has a fixed value zenith. To connect the
string with other parameters, use a question mark (?) to separate the string
from others. Other parameters can be separated by an ampersand (&), a
semicolon (;), or a combination of the two. The format of dataSourceName
can be:
user/passwd@ip:port?parameter=value1&;parameter=value2...

Examples
● Connect to a database using SSL.
db, err = sql.Open("zenith", "user/password@127.0.0.1:1611;ssl_ca=ca.pem;ssl_cert=client-
cert.pem;ssl_key=client-key.pem;ssl_mode=required")
if err != nil {
return err
}

2.5.5 Running SQL Statements


● Execute a SQL statement through the established connection. After the SQL
statement is executed, the transaction is automatically committed.
// Run the SQL statement to create a table.
if _, err := db.Exec("CREATE TABLE " + tbl_name + " (name_spainish VARCHAR2(100) not null,
name_chinesses VARCHAR2(100), name_russian VARCHAR2(100))"); err != nil {
return err
}
// Run the SQL statement to insert data.
if _, err = db.Exec("INSERT INTO " + tbl_name +
" (name_spainish, name_chinesses, name_russian) " +
" VALUES (" + ttst_strings + ")"")"); err != nil {
return err
}
● Execute a SQL statement through bind parameters. After the SQL statement is
executed, the transaction is automatically committed.
_,err = db.Exec("create table tst_batchbind (id real, name varchar(20))")
if err != nil {
return err
}
// Create a statement.
stmt, err = db.Prepare("insert into tst_batchbind values (:1,:2)")
if err != nil {
return err
}
// Execute the SQL statement through bind parameters.
var intput = [5][2]driver.Value {{1.2,"Golus"}, {2.3, "Bonus"}, {3.5, "Franj"}, {4.6, "Wliian"}, {5.7,
"Dous"}}
for _,value := range intput {
_, err = stmt.Exec(value[0], value[1])
if err != nil {
return err
}
}
● Execute SQL statements through a transaction block. The transactions of
these statements are batch committed after the transaction block is
committed.
// Create a transaction block.
tx, err := db.Begin()

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 97


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

if err != nil {
return err
}
// Execute the SQL statements.
if _,err := db.Exec("create table tst_autocommit (id bigint, name char(30))"); err != nil {
return err
}
if _,err := tx.Exec("insert into tst_autocommit values (3, 'Golus')"); err != nil {
return err
}
if _,err := tx.Exec("insert into tst_autocommit values (4, 'Hellen')"); err != nil {
return err
}
// Commit the transaction.
if err := tx.Commit(); err != nil {
return err
}

● Run and rollback SQL statements through a transaction block.


// Create a transaction block.
tx, err := db.Begin()
if err != nil {
return err
}
// Execute the SQL statements.
if _,err := tx.Exec("insert into tst_autocommit values (5, 'WELLROM')"); err != nil {
return err
}
if _,err := tx.Exec("insert into tst_autocommit values (6, 'Bobi')"); err != nil {
return err
}
// Roll back the transaction.
if err := tx.Rollback(); err != nil {
return err
}

● If multiple SQL statements are concatenated into a long SQL statement for
execution. The execution complies with the following restrictions:
– SQL statements are separated by semicolons (;).
– SQL statements cannot contain bound parameters.
– PL/SQL statements, such as stored procedures and anonymous blocks, are
not supported.
– The SELECT statement is not supported. If the SELECT statement is
included, the long SQL statement can be executed properly but no value
will be returned.
if _,err := db.Exec("create table tstMultisql(f1 int)"); err != nil {
return err
}
if _,err :=db.Exec("insert into tstMultisql values(1);insert into tstMultisql values(2);insert tstMultisql
values(4);select * from tstMultiSql;update tstMultisql set f1=3 where f1=2;delete from tstMultisql
where f1=4;"); err != nil {
return err
}

2.5.6 Closing a Connection


After using a connection, you need to invoke the close() method of the connected
object to close it.

Function Prototype
func (db *DB) Close() error

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 98


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

2.5.7 Go Interfaces
● The Zenith Go driver is executed based on the SQL interfaces defined in the
Go language. An application imports the Zenith Go driver and executes the
init method to register the driver. For details about the standard SQL
interfaces of the Go language, visit https://golang.org/pkg/database/sql/.

Table 2-38 Parameter description


Parameter Description

user String variable, specifying the


username for connecting to a
database

passwd String variable, specifying the


password for logging in to a database

host String variable, specifying the IP


address of the database server

port String variable, specifying the listening


port of the database server

ssl_ca String variable, specifying the CA file


of SSL. This parameter is required if
the server requires an SSL connection.

ssl_cert String variable, specifying the client-


cert file of SSL. This parameter is
required if the server requires an SSL
connection.

ssl_key String variable, specifying the client-


key file of SSL. This parameter is
required if the server requires an SSL
connection.

ssl_crl String variable, specifying the CRL file


of SSL. If the file does not exist, this
parameter can be empty.

ssl_keypwd String variable, specifying the


password for generating SSL. This
parameter can be empty if the
password is not set.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 99


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter Description

ssl_mode String variable. Its value can be:


disabled (SSL connections are
disabled.)
preferred (SSL connections are
preferred. If the server does not
support SSL, the connection can still
succeed. This is the default value.)
required (Use the SSL connection. If
the server does not support SSL, the
connection will fail.)
verify_ca (Verify the CA certificate
information on the server.)
verify_full (Use the SSL connection;
verify the server certificate; check
whether the value of the CN field in
the server certificate is the server IP
address.)

socket_timeout INT variable, specifying the socket


timeout duration. The unit is second. If
this parameter is not set, the default
value 600s is used.

exit_commit This is a reserved parameter and


cannot be used.

serveroutput This is a reserved parameter and


cannot be used.

charset_type This is a reserved parameter and


cannot be used.

ssl_cipher This is a reserved parameter and


cannot be used.

connect_timeout This is a reserved parameter and


cannot be used.

nls_characterset This is a reserved parameter and


cannot be used.

nls_comp This is a reserved parameter and


cannot be used.

nls_currency This is a reserved parameter and


cannot be used.

iso_currency This is a reserved parameter and


cannot be used.

language This is a reserved parameter and


cannot be used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 100


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter Description

length_semamtics This is a reserved parameter and


cannot be used.

nchar_characterset This is a reserved parameter and


cannot be used.

nchar_conv_excp This is a reserved parameter and


cannot be used.

numberric_characters This is a reserved parameter and


cannot be used.

rdbms_version This is a reserved parameter and


cannot be used.

sort This is a reserved parameter and


cannot be used.

territory This is a reserved parameter and


cannot be used.

prefetch_rows This is a reserved parameter and


cannot be used.

prefetch_buffer This is a reserved parameter and


cannot be used.

● Based on the methods implemented in the Zenith Go driver, the following


table describes the methods of the standard GO interfaces that can be
invoked by developers.

Table 2-39 Open


Method Description Return Value

Open(driverName, Opens the database *DB, error


dataSourceName string) based on the Zenith Go
driver name and a
description string.

Table 2-40 type DB


Method Description Return Value

(db *DB)Begin() Starts a transaction. *Tx, error

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 101


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Method Description Return Value

(db *DB)Prepare(query Creates a prepared *Stmt, error


string) statement for
subsequent queries or
execution. If the
statement is no longer
needed, the invoker must
invoke the Close method
of the statement.

(db *DB)Query(query Queries the database *Rows, error


string, args ...interface{}) and returns a row. The
type is *DB.

(db *DB)Exec(query Executes the query Result, error


string, args ...interface{}) without returning any
rows.

(db *DB)Close() Closes the database and error


releases all the opened
resources.

Table 2-41 type Rows


Method Description Return Value

(rs Copies the columns in error


*Rows)Scan(dest ...interf the current row to the
ace{}) values pointed to by
dest.

(rs *Rows) Next() Prepares the next result If there is a further result
row for the Scan method set, true is returned. If
to read. there is no further result
set or there is an error
forward, false is
returned.

(rs *Rows) Close() Closes the row to error


prevent further
enumeration.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 102


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-42 type Stmt


Method Description Return Value

(s *Stmt) Uses the given *Rows, error


Query(args ...interface{}) parameters to execute
the prepared query
statement and returns
the query result as *Row.

(s *Stmt) Uses the given Result, error


Exec(args ...interface{}) parameters to execute
the prepared statement
and returns a
summarized statement
result.

(s *Stmt) Close() Closes the row to error


prevent further
enumeration.

Table 2-43 type Tx


Method Description Return Value

(tx *Tx) Exec(query Executes the query that Result, error


string, args ...interface{}) does not return rows.

(tx *Tx) Commit() Commits a transaction. error

(tx *Tx) Rollback() Rolls back a transaction. error

Table 2-44 type Result


Method Description Return Value

(res Result) Returns the number of int64, error


RowsAffected() affected rows.

2.5.8 Examples
● Connect to a database through the Go driver, run SQL statements, and close
the connection.
package zenithdriver

import (
"database/sql"
"database/sql/driver"
"fmt"
"os"
"reflect"
"strconv"

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 103


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

"testing"
"time"
"unsafe"
)

type (
testValue struct {
direction int
data driver.Value
}
)
// Create a connection.
db, err = sql.Open("zenith", "zenithdriver/Gauss_234@127.0.0.1:1611")
if err != nil {
return err
}
// Run the SQL statement to create a table.
_,err = db.Exec("create table tst_batchbind (id real, name varchar(20))")
if err != nil {
return err
}
// Create a statement.
stmt, err = db.Prepare("insert into tst_batchbind values (:1,:2)")
if err != nil {
return err
}
// Execute the SQL statement through bind parameters.
var intput = [5][2]driver.Value {{1.2,"Golus"}, {2.3, "Bonus"}, {3.5, "Franj"}, {4.6, "Wliian"}, {5.7,
"Dous"}}
for _,value := range intput {
_, err = stmt.Exec(value[0], value[1])
if err != nil {
return err
}
}
// Close the statement.
stmt.Close()
// Close the connection.
db.Close()

2.6 Development based on ODBC


Open Database Connectivity (ODBC) is a Microsoft API for accessing databases
based on the X/OPEN CLI. The ODBC API alleviates applications from directly
operating in databases, and enhances the database portability, extensibility, and
maintainability.
GaussDB 100 supports ODBC 3.0.

2.6.1 ODBC Package and Its Dependent Libraries and Header


Files
GaussDB 100 provides the ODBC driver package (libzeodbc.so), dependent
libraries, and header files in Linux. Download unixODBC-2.3.6.tar.gz or a later
version from http://www.unixodbc.org/. Decompress the package to generate the
required library files libodbc.so and libodbcinst.so and the header files sql.h and
sqlext.h.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 104


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

2.6.2 Configuring a Data Source in the Linux OS


Scenario
To interact with GaussDB 100 through the APIs provided by ODBC in Linux, you
need to configure a data source.

Prerequisites
Use unixODBC-2.3.6 or later.

Procedure
Step 1 Obtain the unixODBC source code package from http://www.unixodbc.org/.
Step 2 Install unixODBC.
unixODBC is installed in the /usr/local directory by default. The data source file is
generated in the /usr/local/etc directory, and the library file is generated in
the /usr/local/lib directory.
tar zxvf unixODBC-2.3.6.tar.gz
cd unixODBC-2.3.6
./configure --enable-gui=no
make
make install

Step 3 Configure the ODBC driver file.


Add the following content to the end of the /usr/local/etc/odbcinst.ini file:
[GaussDB]
Driver64=/usr/local/odbc/lib/libzeodbc.so
setup=/usr/local/lib/libzeodbc.so

Configure the driver file directory as needed.


For descriptions of the parameters in the odbc.ini file, see Table 2-45.

Table 2-45 odbc.ini configuration parameters


Parameter Description Example

[DriverNam Driver name, corresponding [DRIVER_N]


e] to Driver in DSN.

Driver64 Path of the dynamic driver Driver64=/xxx/odbc/lib/


library libzeodbc.so

setup Driver installation path, which setup=/xxx/odbc/lib/libzeodbc.so


is the same as the dynamic
library path in Driver64.

Step 4 Configure the data source file.


Add the following content to the end of the /usr/local/etc/odbc.ini file:
[zenith]
Driver=DRIVER_N

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 105


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Servername=192.168.0.1 (IP address of the database server)


Port=1888 (database listening port)

For descriptions of the parameters in the odbc.ini file, see Table 2-46.

Table 2-46 odbc.ini configuration parameters


Parameter Description Example

[DSN] Data source name [zenith]

Driver Driver name, Driver=DRIVER_N


corresponding to
DriverName in
odbcinst.ini

Servername IP address of the server Servername=192.168.0.1

Port Port ID of the server Port=1888

Currently, GaussDB 100 ODBC supports two connection modes: Common TCP and SSL. SSL
modes are classified into unidirectional authentication and bidirectional authentication.
● If the SSL switch is turned on but no certificate information is configured on ODBC,
ODBC connects to the database in unidirectional authentication mode.
● If a certificate file is configured on ODBC and the SSL switch is turned on, ODBC
connects to the database through bidirectional authentication, which is more secure.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 106


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Table 2-47 SSL parameters in the odbc.ini file


Parameter Description Example

sslmode Whether to negotiate with sslmode = VERIFY_CA


the server about SSL Values and description:
connection and specifies the
priority of SSL connection. ● disabled: Try only non-SSL
connection.
● preferred: If the server
supports SSL connection,
the SSL connection is
preferred.
● required: Try only SSL
connection. If there is a CA
file, the verification is
performed in the same way
it is performed when
SSL_MODE is set to
verify_ca.
● verify_ca: Try only SSL
connection and check
whether the server
certificate is issued by a
trusted CA.
● verify_full: Try only SSL
connection, and check
whether the server
certificate is issued by a
trusted CA and whether the
host name of the server is
the same as that in the
certificate.
Default value: preferred

sslca Root certificate file for sslca = /home/xxx/cfg/ssl/


issuing ODBC certificates. The ca.pem
root certificate is used to
verify the server certificate.

sslcert ODBC certificate file, sslcert = /home/xxx/cfg/ssl/


including the client public client-cert.pem
key. The certificate proves the
legal identity of the client
and the public key is sent to
the peer end for data
encryption.

sslkey ODBC private key file used to sslkey = /home/xxx/cfg/ssl/


decrypt digital signatures and client-key.pem
data encrypted using the
public key.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 107


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Parameter Description Example

sslkeypwd Ciphertext of the private key sslkeypwd = /


password on the ODBC side. xdh0RYc41jbkzZmxg6T7LWarW
If the private key is encrypted 3RjaRvevQu76RLCVs=
for storage, set this
parameter to the ciphertext.

sslcrl CRL file for checking whether sslcrl = /home/xxx/cfg/ssl/


the server certificate is in the client-crl.pem
CRL. If it is, the certificate is
invalid.

sslcipher Encryption algorithm used for sslcipher = DHE-RSA-AES256-


SSL communication. GCM-SHA384
For details about supported
encryption algorithms, see
Table 2-48.
Default value: empty,
indicating that the peer end
can use all encryption
algorithms supported by
GaussDB 100. The algorithms
are sorted based on security
strength.

ssllocalkey Working key on the ODBC ssllocalkey =


side. UTiYlBoTC71MvTyBvWhVDodc
0VAop1GMe135ZCov8Pv4xsnlE
Hn9Bs/
pjRo7ZNM1BXq8Z4XuyRjfaNpY
/7McEQ==

sslfactorkeyfile Path of the key factor file on sslfactorkeyfile = /


the ODBC side. home/xxx/dbs/zenith_key1

Example for configuring SSL private key encryption:


-- Generate a key factor and its corresponding key factor file and working key. Set Keyfile to the value of
sslfactorkeyfile and WorkKey to the value of ssllocalkey.
$ zencrypt -G -O /home/xxx/dbs/zenith_key1
Key: dc4hoQWGQs7/Uv3AiherFw==
WorkKey: UTiYlBoTC71MvTyBvWhVDodc0VAop1GMe135ZCov8Pv4xsnlEHn9Bs/
pjRo7ZNM1BXq8Z4XuyRjfaNpY/7McEQ==
Keyfile: /home/xxx/dbs/zenith_key1
-- Use the key factor and working key to encrypt the SSL private key password. Set Cipher to the value of
sslkeypwd.
$ zencrypt -e aes256 -f dc4hoQWGQs7/Uv3AiherFw== -k
UTiYlBoTC71MvTyBvWhVDodc0VAop1GMe135ZCov8Pv4xsnlEHn9Bs/pjRo7ZNM1BXq8Z4XuyRjfaNpY/
7McEQ==
-- Enter the SSL private key password:
Please enter password to encrypt:
********
Please input password again:
********
Cipher: /xdh0RYc41jbkzZmxg6T7LWarW3RjaRvevQu76RLCVs=

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 108


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Example of the odbc.ini file:


$ cat /usr/local/etc/odbc.ini
[myzenith]
Servername = 192.168.0.1
Port = 1888
sslca = /home/xxx/cfg/ssl/ca.pem
sslcert = /home/xxx/cfg/ssl/client-cert.pem
sslkey = /home/xxx/cfg/ssl/client-key.pem
sslkeypwd = /xdh0RYc41jbkzZmxg6T7LWarW3RjaRvevQu76RLCVs=
ssllocalkey = UTiYlBoTC71MvTyBvWhVDodc0VAop1GMe135ZCov8Pv4xsnlEHn9Bs/
pjRo7ZNM1BXq8Z4XuyRjfaNpY/7McEQ==
sslfactorkeyfile = /home/xxx/dbs/zenith_key1
sslmode = VERIFY_CA

Table 2-48 Encryption algorithms

Encryption Security Encryption Algorithm Description


Strength

stronger high DHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-RSA-AES128-GCM- using the RSA
SHA256 encryption
algorithm

stronger high ECDHE-ECDSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high ECDHE-ECDSA-AES128-GCM- using the
SHA256 ECDSA
encryption
algorithm

stronger high ECDHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high ECDHE-RSA-AES128-GCM- using the RSA
SHA256 encryption
algorithm

stronger high DHE-DSS-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-DSS-AES128-GCM- using the DSA
SHA256 encryption
algorithm

stronger medium DHE-RSA-AES256-SHA256 Suitable for


certificates
stronger medium DHE-RSA-AES128-SHA256 generated by
using the RSA
encryption
algorithm

stronger medium DHE-DSS-AES256-SHA256 Suitable for


certificates

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 109


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Encryption Security Encryption Algorithm Description


Strength

stronger medium DHE-DSS-AES128-SHA256 generated by


using the DSA
encryption
algorithm

stronger high DHE-RSA-AES256-CCM Suitable for


certificates
stronger high DHE-RSA-AES128-CCM generated by
using the RSA
encryption
algorithm

----End

2.6.3 Development Process


To use ODBC to develop applications, compile the applications in the local
development environment.

Step 1 Add the following compilation and link parameters for compilation using libraries
and header files in the local environment:
-I${include_path} -lzeodbc -lodbc -lodbcinst

Step 2 Invoke required ODBC interfaces to perform database operations.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 110


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Figure 2-5 ODBC application development process

----End

Table 2-49 APIs

Function API

Allocates handles. SQLAllocHandle

Sets environment attributes. SQLSetEnvAttr

Sets connection attributes. SQLSetConnectAttr

Sets statement attributes. SQLSetStmtAttr

Connects to a data source. SQLConnect

Binds a buffer to a column in the SQLBindCol


result set.

Binds the parameter marker of an SQLBindParameter


SQL statement to a buffer.

Returns the error message of last SQLGetDiagRec


operation.

Prepares an SQL statement for SQLPrepare


execution.

Executes a prepared SQL statement. SQLExecute

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 111


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Function API

Executes an SQL statement directly. SQLExecDirect

Fetches the next row (or rows) from SQLFetch


the result set.

Gets data from a column. SQLGetData

Gets the column information from a SQLColAttribute


result set.

Disconnects from a data source. SQLDisconnect

Releases handle resources. SQLFreeHandle

2.6.4 Example
This section provides an example to illustrate how to develop applications based
on GaussDB 100.
#if WIN32
#include <windows.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include "sql.h"
#include "sqlext.h"

int main()
{
SQLHANDLE h_env = NULL;
SQLHANDLE h_conn = NULL;
SQLHANDLE h_stmt = NULL;
SQLINTEGER ret;
SQLCHAR *dsn = (SQLCHAR *)"myzenith";/*Data source name*/
SQLCHAR *username = (SQLCHAR *)"gaussdba";/*User name*/
SQLCHAR *password = (SQLCHAR *)"gaussdb_123";/*Password*/
SQLSMALLINT dsn_len = (SQLSMALLINT)strlen((const char *)dsn);
SQLSMALLINT username_len = (SQLSMALLINT)strlen((const char *)username);
SQLSMALLINT password_len = (SQLSMALLINT)strlen((const char *)password);

// Apply for handles.


ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &h_env);
if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO))
{
return SQL_ERROR;
}

// Set environment handle attributes.


if (SQL_SUCCESS != SQLSetEnvAttr(h_env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0))
{
SQLFreeHandle(SQL_HANDLE_ENV, h_env);
return SQL_ERROR;
}

// Allocate connection handles.


if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, h_env, &h_conn))
{
return SQL_ERROR;
}

// Set the automatic committing attribute of the connection handles.


if (SQL_SUCCESS != SQLSetConnectAttr(h_conn, SQL_ATTR_AUTOCOMMIT, (void *)1, 0))

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 112


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

{
SQLFreeHandle(SQL_HANDLE_DBC, h_conn);
SQLFreeHandle(SQL_HANDLE_ENV, h_env);
return SQL_ERROR;
}

// Connect to a data source.


SQLConnect(h_conn, dsn, dsn_len, username, username_len, password, password_len);

// Apply for handle execution.


if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, h_conn, &h_stmt))
{
SQLFreeHandle(SQL_HANDLE_DBC, h_conn);
SQLFreeHandle(SQL_HANDLE_ENV, h_env);
return SQL_ERROR;
}

// Create a table and insert a record.


SQLCHAR* create_table_sql = (SQLCHAR*)"create table test(col int)";
SQLExecDirect(h_stmt, create_table_sql, strlen(create_table_sql));
SQLCHAR* insert_sql = (SQLCHAR*)"insert into test (col) values(:col)";
SQLPrepare(h_stmt, insert_sql, strlen(insert_sql));
int col = 1;
SQLBindParameter(h_stmt, 1, SQL_PARAM_INPUT, SQL_C_SSHORT, SQL_INTEGER, sizeof(int), 0, &col, 0,
NULL);
SQLExecute(h_stmt);

// Query and print the results.


SQLCHAR* select_sql = (SQLCHAR*)"select col from test";
SQLPrepare(h_stmt, select_sql, strlen(select_sql));
int colvalue = 0;
SQLBindCol(h_stmt, 1, SQL_C_SSHORT, &colvalue, sizeof(colvalue), NULL);
SQLExecute(h_stmt);

do
{
ret = SQLFetch(h_stmt);
if (ret != SQL_SUCCESS && ret != SQL_NO_DATA)
{
break;
}
if (ret == SQL_SUCCESS)
{
printf("get %d from table 'test'.\n", colvalue);
}
} while (ret != SQL_NO_DATA);

SQLINTEGER row = 0;
SQLRowCount(h_stmt, &row);
printf("get %d rows table 'test'.\n", row);

// Disconnect from the database.


SQLDisconnect(h_conn);

// Release handles.
SQLFreeHandle(SQL_HANDLE_STMT, h_stmt);
SQLFreeHandle(SQL_HANDLE_DBC, h_conn);
SQLFreeHandle(SQL_HANDLE_ENV, h_env);

return SQL_SUCCESS;
}

2.6.5 ODBC Interfaces

SQLAllocHandle
Description: Allocates ODBC handles.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 113


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

API:
SQLRETURN SQL_API SQLAllocHandle(SQLSMALLINT HandleType,
SQLHANDLE InputHandle,
SQLHANDLE *OutputHandle)

Input parameter:

● HandleType: type of the handle to be allocated (SQL_HANDLE_ENV,


SQL_HANDLE_DBC, or SQL_HANDLE_STMT)
● InputHandle: dependent handle

Output parameter:

OutputHandle: allocated handle

Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed

Thread-safe: no

SQLAllocEnv
Description: Allocates ODBC environment handles.

API:
SQLRETURN SQL_API SQLAllocEnv(SQLHENV *EnvironmentHandle)

Output parameter:

EnvironmentHandle: allocated handle

Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed

Thread-safe: no

SQLAllocConnect
Description: Allocates ODBC connection handles.

API:
SQLRETURN SQL_API SQLAllocConnect(SQLHENV EnvironmentHandle,
SQLHDBC *ConnectionHandle)

Input parameter:

EnvironmentHandle: environment handle

Output parameter:

ConnectionHandle: allocated connection handle

Return value:
● SQL_SUCCESS: successful

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 114


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● !=SQL_SUCCESS: failed
Thread-safe: no

SQLAllocStmt
Description: Allocates ODBC execution handles.
API:
SQLRETURN SQL_API SQLAllocStmt(SQLHDBC ConnectionHandle,
SQLHSTMT *StatementHandle)

Input parameter:
ConnectionHandle: connection handle
Output parameter:
StatementHandle: allocated execution handle
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFreeHandle
Description: Releases ODBC handles.
API:
SQLRETURN SQL_API SQLFreeHandle(SQLSMALLINT HandleType, SQLHANDLE Handle)

Input parameter:
● HandleType: type of the handle to be released (SQL_HANDLE_ENV,
SQL_HANDLE_DBC, or SQL_HANDLE_STMT)
● Handle: handle
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFreeEnv
Description: Releases ODBC environment handles.
API:
SQLRETURN SQL_API SQLFreeEnv(SQLHENV EnvironmentHandle)

Input parameter:
EnvironmentHandle: environment handle to be released
Return value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 115


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFreeConnect
Description: Releases ODBC connection handles.
API:
SQLRETURN SQL_API SQLFreeConnect(SQLHDBC ConnectionHandle)

Input parameter:
ConnectionHandle: connection handle to be released
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFreeStmt
Description: Releases ODBC execution handles.
API:
SQLRETURN SQL_API SQLFreeStmt(SQLHSTMT StatementHandle,
SQLUSMALLINT Option)

Input parameter:
● StatementHandle: execution handle to be released
● Option: how a handle is released (SQL_DROP)
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLSetEnvAttr
Description: Sets ODBC environment handle attributes.
API:
SQLRETURN SQL_API SQLSetEnvAttr(SQLHENV EnvironmentHandle,
SQLINTEGER Attribute,
SQLPOINTER Value,
SQLINTEGER StringLength)

Input parameter:
● EnvironmentHandle: environment handle to be set
● Attribute: name of the attribute to be set (SQL_ATTR_ODBC_VERSION or
SQL_ATTR_OUTPUT_NTS)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 116


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● Value: value of the attribute to be set


● StringLength: length of an attribute value
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLSetConnectAttr
Description: Sets ODBC connection handle attributes.
API:
SQLRETURN SQL_API SQLSetConnectAttr(SQLHDBC ConnectionHandle,
SQLINTEGER Attribute,
SQLPOINTER Value,
SQLINTEGER StringLength)

Input parameter:
● ConnectionHandle: connection handle to be set
● Attribute: name of the attribute to be set (SQL_ATTR_AUTOCOMMIT,
SQL_ATTR_LOGIN_TIMEOUT, or SQL_ATTR_CONNECTION_TIMEOUT)
● Value: value of the attribute to be set
● StringLength: length of an attribute value
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLSetStmtAttr
Description: Sets ODBC execution handle attributes.
API:
SQLRETURN SQL_API SQLSetStmtAttr(SQLHSTMT StatementHandle,
SQLINTEGER Attribute,
SQLPOINTER Value,
SQLINTEGER StringLength)

Input parameter:
● StatementHandle: execution handle to be set
● Attribute: name of the attribute to be set (such as
SQL_ATTR_PARAMSET_SIZE, SQL_ATTR_ROW_ARRAY_SIZE,
SQL_ATTR_ROW_BIND_TYPE, SQL_ATTR_ROWS_FETCHED_PTR, and
SQL_ATTR_ROW_STATUS_PTR)
● Value: value of the attribute to be set
● StringLength: length of an attribute value
Return value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 117


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLConnect
Description: Uses a connection handle to connect to a data source.
API:
SQLRETURN SQL_API SQLConnect(SQLHDBC ConnectionHandle,
SQLCHAR *ServerName,
SQLSMALLINT NameLength1,
SQLCHAR *UserName,
SQLSMALLINT NameLength2,
SQLCHAR *Authentication,
SQLSMALLINT NameLength3)

Input parameter:
● ConnectionHandle: connection handle
● ServerName: name of the data source configured for ODBC
● NameLength1: length of the data source name
● UserName: username for connecting to the data source
● NameLength2: username length
● Authentication: password for connecting to the data source
● NameLength3: password length
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLDisconnect
Description: Disconnects from a data source.
API:
SQLRETURN SQL_API SQLDisconnect(SQLHDBC ConnectionHandle)

Input parameter:
ConnectionHandle: connection handle
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLDriverConnect
Description: Uses a connection handle to connect to a data source.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 118


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

API:
SQLRETURN SQL_API SQLDriverConnect(
SQLHDBC hdbc,
SQLHWND hwnd,
SQLCHAR *szConnStrIn,
SQLSMALLINT cbConnStrIn,
SQLCHAR *szConnStrOut,
SQLSMALLINT cbConnStrOutMax,
SQLSMALLINT *pcbConnStrOut,
SQLUSMALLINT fDriverCompletion)

Input parameter:

● hdbc: connection handle


● hwnd: handle used for interconnection (currently not used)
● szConnStrIn: data source connection string
● cbConnStrIn: length of the data source connection string
● cbConnStrOutMax: length of buffer storing an output connection string
● fDriverCompletion: connection option (SQL_DRIVER_PROMPT,
SQL_DRIVER_NOPROMPT, SQL_DRIVER_COMPLETE, or
SQL_DRIVER_COMPLETE_REQUIRED)

Output parameter:

● szConnStrOut: output connection string


● pcbConnStrOut: length of an output connection string

Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed

Thread-safe: no

SQLPrepare
Description: Prepares an SQL statement to be executed.

API:
SQLRETURN SQL_API SQLPrepare(SQLHSTMT StatementHandle,
SQLCHAR *StatementText,
SQLINTEGER TextLength)

Input parameter:

● StatementHandle: execution handle


● StatementText: SQL statement
● TextLength: SQL statement length

Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed

Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 119


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

SQLBindParameter
Description: Binds parameters to existing SQL execution handles.

API:
SQLRETURN SQL_API SQLBindParameter(
SQLHSTMT StatementHandle,
SQLUSMALLINT ParameterNumber,
SQLSMALLINT InputOutputType,
SQLSMALLINT ValueType,
SQLSMALLINT ParameterType,
SQLULEN ColumnSize,
SQLSMALLINT DecimalDigits,
SQLPOINTER ParameterValuePtr,
SQLLEN BufferLength,
SQLLEN * StrLen_or_IndPtr)

Input parameter:

● StatementHandle: execution handle


● ParameterNumber: sequence number of a bound parameter, starting from 1
● InputOutputType: input and output type of a parameter
● ValueType: C buffer type
● ParameterType: SQL type of the column to be bound
● ColumnSize: column width of the bound buffer
● DecimalDigits: format precision of the bound buffer
● ParameterValuePtr: buffer pointer
● BufferLength: buffer length
● StrLen_or_IndPtr: pointer to a buffer for the parameter's length

Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed

Thread-safe: no

SQLBindCol
Description: Binds to the buffer for storing result set columns.

API:
SQLRETURN SQL_API SQLBindCol(SQLHSTMT StatementHandle,
SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType,
SQLPOINTER TargetValue, SQLLEN BufferLength,
SQLLEN *StrLen_or_Ind)

Input parameter:

● StatementHandle: execution handle


● ColumnNumber: sequence number of a bound column, starting from 1
● TargetType: type of C buffer for storing results
● TargetValue: result storage buffer
● BufferLength: size of the result storage buffer

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 120


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● StrLen_or_Ind: actual result length


Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLExecute
Description: Runs an SQL statement.
API:
SQLRETURN SQL_API SQLExecute(
SQLHSTMT StatementHandle)

Input parameters: StatementHandle


Return value:
● SQL_SUCCESS: successful
● SQL_NEED_DATA: unbound parameters exist
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLExecDirect
Description: Directly runs an SQL statement.
API:
SQLRETURN SQL_API SQLExecDirect(
SQLHSTMT StatementHandle,
SQLCHAR * StatementText,
SQLINTEGER TextLength)

Input parameter:
● StatementHandle: execution handle
● StatementText: SQL statement
● TextLength: SQL statement length
Return value:
● SQL_SUCCESS: successful
● SQL_NEED_DATA: unbound parameters exist
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLColAttribute
Description: Describes column attributes.
API:
SQLRETURN SQL_API SQLColAttribute(
SQLHSTMT StatementHandle,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 121


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

SQLUSMALLINT ColumnNumber,
SQLUSMALLINT FieldIdentifier,
SQLPOINTER CharacterAttributePtr,
SQLSMALLINT BufferLength,
SQLSMALLINT * StringLengthPtr,
SQLLEN * NumericAttributePtr)

Input parameter:
● StatementHandle: execution handle
● ColumnNumber: column sequence number, starting from 1
● FieldIdentifier: description type (SQL_DESC_NAME, SQL_DESC_LENGTH,
SQL_DESC_NULLABLE, SQL_DESC_TYPE, or SQL_DESC_TYPE_NAME)
● BufferLength: length of character buffer
Output parameter:
● CharacterAttributePtr: character buffer
● StringLengthPtr: length of the obtained string
● NumericAttributePtr: digit buffer
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLGetDiagRec
Description: Diagnoses faults.
API:
SQLRETURN SQL_API SQLGetDiagRec(
SQLSMALLINT HandleType,
SQLHANDLE Handle,
SQLSMALLINT RecNumber,
SQLCHAR * SQLState,
SQLINTEGER * NativeErrorPtr,
SQLCHAR * MessageText,
SQLSMALLINT BufferLength,
SQLSMALLINT * TextLengthPtr)

Input parameter:
● HandleType: handle type
● Handle: handle
● RecNumber: sequence number of a diagnosed error. Currently, only one error
is cached.
● BufferLength: length of the error information buffer
Output parameter:
● SQLState: SQL status (currently not supported)
● NativeErrorPtr: error code on the data source side
● MessageText: error information buffer
● TextLengthPtr: error information length

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 122


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Return value:
● SQL_SUCCESS: successful
● SQL_NO_DATA: no more diagnosis information available
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFetch
Description: Obtains the next row in the results.
API:
SQLRETURN SQL_API SQLFetch(
SQLHSTMT StatementHandle)

Input parameters: StatementHandle


Return value:
● SQL_SUCCESS: successful
● SQL_NO_DATA: fetch ended
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLGetData
Description: Obtains the data of a column from result rows.
API:
SQLRETURN SQL_API SQLGetData(
SQLHSTMT StatementHandle,
SQLUSMALLINT Col_or_Param_Num,
SQLSMALLINT TargetType,
SQLPOINTER TargetValuePtr,
SQLLEN BufferLength,
SQLLEN * StrLen_or_IndPtr)

Input parameter:
● StatementHandle: execution handle
● Col_or_Param_Num: column sequence number, starting from 1
● TargetType: C target buffer type
● TargetValuePtr: target buffer
● BufferLength: buffer length
● StrLen_or_IndPtr: fetched data length
Return value:
● SQL_SUCCESS: successful
● SQL_SUCCESS_WITH_INFO: The column is truncated. Try again to obtain the
remaining data.
● SQL_NULL_DATA: The column is empty.
● !=SQL_SUCCESS: failed

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 123


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

Thread-safe: no

SQLCloseCursor
Description: Closes a cursor.
API:
SQLRETURN SQL_API SQLCloseCursor(
SQLHSTMT StatementHandle)

Input parameter:
StatementHandle: execution handle
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLRowCount
Description: Obtains the number of rows. For a query, the number of obtained
rows is returned. For a modification SQL statement, the number of modified rows
is returned.
API:
SQLRETURN SQL_API SQLRowCount(
SQLHSTMT StatementHandle,
SQLLEN * RowCountPtr)

Input parameter:
StatementHandle: execution handle
Output parameter:
RowCountPtr: number of modified rows
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLEndTran
Description: Ends a transaction.
API:
SQLRETURN SQL_API SQLEndTran(SQLSMALLINT HandleType,
SQLHANDLE Handle,
SQLSMALLINT CompletionType)

Input parameter:
● HandleType: handle type

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 124


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● Handle: handle
● CompletionType: how a transaction is ended (SQL_COMMIT or
SQL_ROLLBACK)
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLError
Description: Obtains the number of rows. For a query, the number of obtained
rows is returned. For a modification SQL statement, the number of modified rows
is returned.
API:
SQLRETURN SQL_API SQLError(SQLHENV EnvironmentHandle,
SQLHDBC ConnectionHandle,
SQLHSTMT StatementHandle,
SQLCHAR *Sqlstate,
SQLINTEGER *NativeError,
SQLCHAR *MessageText,
SQLSMALLINT BufferLength,
SQLSMALLINT *TextLength)

Input parameter:
● EnvironmentHandle: environment handle
● ConnectionHandle: connection handle
● StatementHandle: execution handle
● BufferLength: length of the error information buffer
Output parameter:
● Sqlstate: The output is empty.
● NativeError: local error code of a data source
● MessageText: error information buffer
● TextLength: error information length
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLFetchScroll
Description: Fetches specified rows.
API:
SQLRETURN SQL_API SQLFetchScroll(
SQLHSTMT StatementHandle,
SQLSMALLINT FetchOrientation,
SQLLEN FetchOffset)

Input parameter:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 125


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● StatementHandle: execution handle


● FetchOrientation: how a row is obtained (SQL_FETCH_NEXT)
● FetchOffset: obtains offset (currently not enabled)
Return value:
● SQL_SUCCESS: successful
● SQL_NO_DATA: no more rows available
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLParamData
Description: Checks parameter status.
API:
SQLRETURN SQL_API SQLParamData(
SQLHSTMT StatementHandle,
SQLPOINTER * ValuePtrPtr)

Input parameter:
StatementHandle: execution handle
Output parameter:
ValuePtrPtr: For prepared SQL statement, the parameter pointer that is not fully
bound is returned. For executed SQL statements, the result column token
(currently column ID) is returned.
Return value:
● SQL_SUCCESS: successful
● SQL_NEED_DATA: Parameters that need to be bound to more data exist.
● SQL_PARAM_DATA_AVAILABLE: Some columns are not completely obtained.
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLPutData
Description: Inputs data to be bound to execution handles. If SQLParamData
returns readable data, you do not need to perform SQLExecute again.
API:
SQLRETURN SQL_API SQLPutData(
SQLHSTMT StatementHandle,
SQLPOINTER DataPtr,
SQLLEN StrLen_or_Ind)

Input parameter:
● StatementHandle: execution handle
● DataPtr: first bound address of the input parameter
● StrLen_or_Ind: input parameter length
Return value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 126


GaussDB 100
R&D Documentation (Standalone) 2 Database Development Guide

● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

SQLNumResultCols
Description: Returns the number of columns in the result set.
Interface:
SQLRETURN SQLNumResultCols(
SQLHSTMT StatementHandle,
SQLSMALLINT * ColumnCountPtr)

Input parameter:
● StatementHandle: execution handle
Output parameter:
● ColumnCountPtr: where to return the number of columns in the result set
Return value:
● SQL_SUCCESS: successful
● !=SQL_SUCCESS: failed
Thread-safe: no

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 127


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3 SQL Syntax Reference

3.1 Conventions
Variable Naming Conventions
GaussDB 100 supports user-defined names, called identifiers, including database
names, table names, column names, view names, function names, procedure
names, variable names, and usernames.

● Identifiers start with letters or underscores (_) and can contain any characters,
such as letters, digits, and underscores (_).
● A database name can contain a maximum of 30 characters. Other identifiers
can contain a maximum of 64 characters.
● If an identifier is not enclosed in quotation marks, it will be truncated. If it
contains spaces or the following characters: !%&^(,)*+,-./. Characters before
the truncating position are used as an identifier and others are used as
another identifier or keyword.

SQL Standards
● The length of the SQL statement cannot exceed 1 MB. Otherwise, an error is
reported.
● A constant string supports a maximum of 8000 bytes.
● The maximum length of a row (total length of all column values in the row)
in a table is 64000 bytes.

Comment Conventions
The SQL scripts of GaussDB 100 support two comment formats:

● Single-line comment
Format: -- Comment
● Multi-line comment
Format: /*Comment*/

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 128


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.2 Example
A human resource (HR) database is provided for users to learn and verify GaussDB
100 For details about how to install the database, see Installation Guide.

3.2.1 示例库说明
如果通过执行示例数据库脚本安装示例库,系统会自动创建一个名为hr的用户。如果没
有安装示例数据库,可以通过本章的SQL语句手工创建示例。

3.2.2 Reference Scripts


以下示例全部以hr用户为例。
--创建用户hr。
create user hr identified by database_123;

● employment_history表。
--创建employment_history表。
create table hr.employment_history
(
staff_id NUMBER(6),
start_date DATE,
end_date DATE,
employment_id VARCHAR2(10),
section_id NUMBER(4)
);
-- Insert data.
insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)
values (102, to_date('13-01-1993', 'dd-mm-yyyy'), to_date('24-07-1998', 'dd-mm-yyyy'), 'IT_PROG',
60);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (101, to_date('21-09-1989', 'dd-mm-yyyy'), to_date('27-10-1993', 'dd-mm-yyyy'),
'AC_ACCOUNT', 110);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (101, to_date('28-10-1993', 'dd-mm-yyyy'), to_date('15-03-1997', 'dd-mm-yyyy'), 'AC_MGR',
110);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (201, to_date('17-02-1996', 'dd-mm-yyyy'), to_date('19-12-1999', 'dd-mm-yyyy'), 'MK_REP', 20);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (114, to_date('24-03-1998', 'dd-mm-yyyy'), to_date('31-12-1999', 'dd-mm-yyyy'), 'ST_CLERK',
50);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (122, to_date('01-01-1999', 'dd-mm-yyyy'), to_date('31-12-1999', 'dd-mm-yyyy'), 'ST_CLERK',
50);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (200, to_date('17-09-1987', 'dd-mm-yyyy'), to_date('17-06-1993', 'dd-mm-yyyy'), 'AD_ASST',
90);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (176, to_date('24-03-1998', 'dd-mm-yyyy'), to_date('31-12-1998', 'dd-mm-yyyy'), 'SA_REP', 80);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)


values (176, to_date('01-01-1999', 'dd-mm-yyyy'), to_date('31-12-1999', 'dd-mm-yyyy'), 'SA_MAN',
80);

insert into hr.employment_history (staff_id, start_date, end_date, employment_id, section_id)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 129


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

values (200, to_date('01-07-1994', 'dd-mm-yyyy'), to_date('31-12-1998', 'dd-mm-yyyy'),


'AC_ACCOUNT', 90);

● sections表。
--创建sections表。
create table hr.sections
(
section_id NUMBER(4) not null,
section_name VARCHAR2(30),
manager_id NUMBER(6),
place_id NUMBER(4)
);
--插入数据。
insert into hr.sections (section_id, section_name, manager_id, place_id)
values (10, 'Administration', 200, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (20, 'Marketing', 201, 1800);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (30, 'Purchasing', 114, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (40, 'Human Resources', 203, 2400);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (50, 'Shipping', 121, 1500);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (60, 'IT', 103, 1400);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (70, 'Public Relations', 204, 2700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (80, 'Sales', 145, 2500);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (90, 'Executive', 100, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (100, 'Finance', 108, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (110, 'Accounting', 205, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (120, 'Treasury', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (130, 'Corporate Tax', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (140, 'Control And Credit', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (150, 'Shareholder Services', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (160, 'Benefits', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (170, 'Manufacturing', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (180, 'Construction', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (190, 'Contracting', null, 1700);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 130


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (200, 'Operations', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (210, 'IT Support', null, 1700);

insert into sections (section_id, section_name, manager_id, place_id)


values (220, 'NOC', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (230, 'IT Helpdesk', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (240, 'Government Sales', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (250, 'Retail Sales', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (260, 'Recruiting', null, 1700);

insert into hr.sections (section_id, section_name, manager_id, place_id)


values (270, 'Payroll', null, 1700);

● places表
--创建places表。
create table hr.places
(
place_id NUMBER(4) not null,
street_address VARCHAR2(40),
postal_code VARCHAR2(12),
city VARCHAR2(30),
state_province VARCHAR2(25),
state_id CHAR(2)
);
--插入数据。
insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)
values (1000, '1297 Via Cola di Rie', '00989', 'Roma', '', 'IT');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1100, '93091 Calle della Testa', '10934', 'Venice', '', 'IT');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1200, '2017 Shinjuku-ku', '1689', 'Tokyo', 'Tokyo Prefecture', 'JP');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1300, '9450 Kamiya-cho', '6823', 'Hiroshima', '', 'JP');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1400, '2014 Jabberwocky Rd', '26192', 'Southlake', 'Texas', 'US');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1500, '2011 Interiors Blvd', '99236', 'South San Francisco', 'California', 'US');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1600, '2007 Zagora St', '50090', 'South Brunswick', 'New Jersey', 'US');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1700, '2004 Charade Rd', '98199', 'Seattle', 'Washington', 'US');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1800, '147 Spadina Ave', 'M5V 2L7', 'Toronto', 'Ontario', 'CA');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (1900, '6092 Boxwood St', 'YSW 9T2', 'Whitehorse', 'Yukon', 'CA');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2000, '40-5-12 Laogianggen', '190518', 'Beijing', '', 'CN');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 131


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

values (2100, '1298 Vileparle (E)', '490231', 'Bombay', 'Maharashtra', 'IN');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2200, '12-98 Victoria Street', '2901', 'Sydney', 'New South Wales', 'AU');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2300, '198 Clementi North', '540198', 'Singapore', '', 'SG');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2400, '8204 Arthur St', '', 'London', '', 'UK');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2500, 'Magdalen Centre, The Oxford Science Park', 'OX9 9ZB', 'Oxford', 'Oxford', 'UK');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2600, '9702 Chester Road', '09629850293', 'Stretford', 'Manchester', 'UK');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2700, 'Schwanthalerstr. 7031', '80925', 'Munich', 'Bavaria', 'DE');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2800, 'Rua Frei Caneca 1360 ', '01307-002', 'Sao Paulo', 'Sao Paulo', 'BR');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (2900, '20 Rue des Corps-Saints', '1730', 'Geneva', 'Geneve', 'CH');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (3000, 'Murtenstrasse 921', '3095', 'Bern', 'BE', 'CH');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (3100, 'Pieter Breughelstraat 837', '3029SK', 'Utrecht', 'Utrecht', 'NL');

insert into hr.places (place_id, street_address, postal_code, city, state_province, state_id)


values (3200, 'Mariano Escobedo 9991', '11932', 'Mexico City', 'Distrito Federal,', 'MX');

● areas表。
--创建areas表。
create table hr.areas
(
area_id NUMBER,
area_name VARCHAR2(25)
);
--插入数据。
insert into hr.areas (area_id, area_name)
values (1, 'Europe');

insert into hr.areas (area_id, area_name)


values (2, 'Americas');

insert into hr.areas (area_id, area_name)


values (3, 'Asia');

insert into hr.areas (area_id, area_name)


values (4, 'Middle East and Africa');

● college表。
--创建college表。
create table hr.college
(
college_id NUMBER,
college_name VARCHAR2(40)
);
-- Insert data.
insert into hr.college (college_id, college_name)values (1001, 'The University of Melbourne');

insert into hr.college (college_id, college_name)values (1002, 'Duke University');

insert into hr.college (college_id, college_name)values (1003, 'New York University');

insert into hr.college (college_id, college_name)values (1004, 'Kings College London');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 132


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.college (college_id, college_name)values (1005, 'Tsinghua University');

insert into hr.college (college_id, college_name)values (1006, 'University of Zurich');

insert into hr.college (college_id, college_name)values (1007, 'Rice University');

insert into hr.college (college_id, college_name)values (1008, 'Boston University');

insert into hr.college (college_id, college_name)values (1009, 'Peking University');

insert into hr.college (college_id, college_name)values (1010, 'Monash University');

insert into hr.college (college_id, college_name)values (1011, 'KU Leuven');

insert into hr.college (college_id, college_name)values (1012, 'University of Basel');

insert into hr.college (college_id, college_name)values (1013, 'Leiden University');

insert into hr.college (college_id, college_name)values (1014, 'Erasmus University');

insert into hr.college (college_id, college_name)values (1015, 'Ghent University');

insert into hr.college (college_id, college_name)values (1016, 'Aarhus University');

● employments表。
--创建employments表。
create table hr.employments
(
employment_id VARCHAR2(10) not null,
employment_title VARCHAR2(35),
min_salary NUMBER(6),
max_salary NUMBER(6)
);
--插入数据。
insert into hr.employments (employment_id, employment_title, min_salary, max_salary)
values ('AD_PRES', 'President', 20000, 40000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('AD_VP', 'Administration Vice President', 15000, 30000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('AD_ASST', 'Administration Assistant', 3000, 6000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('FI_MGR', 'Finance Manager', 8200, 16000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('FI_ACCOUNT', 'Accountant', 4200, 9000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('AC_MGR', 'Accounting Manager', 8200, 16000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('AC_ACCOUNT', 'Public Accountant', 4200, 9000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('SA_MAN', 'Sales Manager', 10000, 20000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('SA_REP', 'Sales Representative', 6000, 12000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('PU_MAN', 'Purchasing Manager', 8000, 15000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('PU_CLERK', 'Purchasing Clerk', 2500, 5500);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('ST_MAN', 'Stock Manager', 5500, 8500);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 133


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('ST_CLERK', 'Stock Clerk', 2000, 5000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('SH_CLERK', 'Shipping Clerk', 2500, 5500);

insert into employments (employment_id, employment_title, min_salary, max_salary)


values ('IT_PROG', 'Programmer', 4000, 10000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('MK_MAN', 'Marketing Manager', 9000, 15000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('MK_REP', 'Marketing Representative', 4000, 9000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('HR_REP', 'Human Resources Representative', 4000, 9000);

insert into hr.employments (employment_id, employment_title, min_salary, max_salary)


values ('PR_REP', 'Public Relations Representative', 4500, 10500);

● states表。
--创建states表。
create table hr.states
(
state_id CHAR(2),
state_name VARCHAR2(40),
area_id NUMBER,
constraint state_c_id_pk primary key (state_ID)
);
--插入数据。
insert into hr.states (state_id, state_name, area_id)
values ('AR', 'Argentina', 2);

insert into hr.states (state_id, state_name, area_id)


values ('AU', 'Australia', 3);

insert into hr.states (state_id, state_name, area_id)


values ('BE', 'Belgium', 1);

insert into hr.states (state_id, state_name, area_id)


values ('BR', 'Brazil', 2);

insert into hr.states (state_id, state_name, area_id)


values ('CA', 'Canada', 2);

insert into hr.states (state_id, state_name, area_id)


values ('CH', 'Switzerland', 1);

insert into hr.states (state_id, state_name, area_id)


values ('CN', 'China', 3);

insert into hr.states (state_id, state_name, area_id)


values ('DE', 'Germany', 1);

insert into hr.states (state_id, state_name, area_id)


values ('DK', 'Denmark', 1);

insert into hr.states (state_id, state_name, area_id)


values ('EG', 'Egypt', 4);

insert into hr.states (state_id, state_name, area_id)


values ('FR', 'France', 1);

insert into hr.states (state_id, state_name, area_id)


values ('HK', 'HongKong', 3);

insert into hr.states (state_id, state_name, area_id)


values ('IL', 'Israel', 4);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 134


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.states (state_id, state_name, area_id)


values ('IN', 'India', 3);

insert into hr.states (state_id, state_name, area_id)


values ('IT', 'Italy', 1);

insert into hr.states (state_id, state_name, area_id)


values ('JP', 'Japan', 3);

insert into hr.states (state_id, state_name, area_id)


values ('KW', 'Kuwait', 4);

insert into hr.states (state_id, state_name, area_id)


values ('MX', 'Mexico', 2);

insert into hr.states (state_id, state_name, area_id)


values ('NG', 'Nigeria', 4);

insert into hr.states (state_id, state_name, area_id)


values ('NL', 'Netherlands', 1);

insert into hr.states (state_id, state_name, area_id)


values ('SG', 'Singapore', 3);

insert into hr.states (state_id, state_name, area_id)


values ('UK', 'United Kingdom', 1);

insert into hr.states (state_id, state_name, area_id)


values ('US', 'United States of America', 2);

insert into hr.states (state_id, state_name, area_id)


values ('ZM', 'Zambia', 4);

insert into hr.states (state_id, state_name, area_id)


values ('ZW', 'Zimbabwe', 4);

● staffs表。
--创建staffs表。
CREATE TABLE hr.staffs
(
staff_id NUMBER(6) not null,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
);
--插入数据。
insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 135


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (201, 'Michael', 'Hartstein', 'MHARTSTE', '515.123.5555', to_date('17-02-1996', 'dd-mm-yyyy'),
'MK_MAN', 13000.00, null, 100, 20);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (202, 'Pat', 'Fay', 'PFAY', '603.123.6666', to_date('17-08-1997', 'dd-mm-yyyy'), 'MK_REP',
6000.00, null, 201, 20);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (203, 'Susan', 'Mavris', 'SMAVRIS', '515.123.7777', to_date('07-06-1994', 'dd-mm-yyyy'),
'HR_REP', 6500.00, null, 101, 40);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (204, 'Hermann', 'Baer', 'HBAER', '515.123.8888', to_date('07-06-1994', 'dd-mm-yyyy'), 'PR_REP',
10000.00, null, 101, 70);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (205, 'Shelley', 'Higgins', 'SHIGGINS', '515.123.8080', to_date('07-06-1994', 'dd-mm-yyyy'),
'AC_MGR', 12000.00, null, 101, 110);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (206, 'William', 'Gietz', 'WGIETZ', '515.123.8181', to_date('07-06-1994', 'dd-mm-yyyy'),
'AC_ACCOUNT', 8300.00, null, 205, 110);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (100, 'Steven', 'King', 'SKING', '515.123.4567', to_date('17-06-1987', 'dd-mm-yyyy'), 'AD_PRES',
24000.00, null, null, 90);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (101, 'Neena', 'Kochhar', 'NKOCHHAR', '515.123.4568', to_date('21-09-1989', 'dd-mm-yyyy'),
'AD_VP', 17000.00, null, 100, 90);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (102, 'Lex', 'De Haan', 'LDEHAAN', '515.123.4569', to_date('13-01-1993', 'dd-mm-yyyy'),
'AD_VP', 17000.00, null, 100, 90);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (103, 'Alexander', 'Hunold', 'AHUNOLD', '590.423.4567', to_date('03-01-1990', 'dd-mm-yyyy'),
'IT_PROG', 9000.00, null, 102, 60);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (104, 'Bruce', 'Ernst', 'BERNST', '590.423.4568', to_date('21-05-1991', 'dd-mm-yyyy'), 'IT_PROG',
6000.00, null, 103, 60);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (105, 'David', 'Austin', 'DAUSTIN', '590.423.4569', to_date('25-06-1997', 'dd-mm-yyyy'),
'IT_PROG', 4800.00, null, 103, 60);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (106, 'Valli', 'Pataballa', 'VPATABAL', '590.423.4560', to_date('05-02-1998', 'dd-mm-yyyy'),
'IT_PROG', 4800.00, null, 103, 60);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (107, 'Diana', 'Lorentz', 'DLORENTZ', '590.423.5567', to_date('07-02-1999', 'dd-mm-yyyy'),
'IT_PROG', 4200.00, null, 103, 60);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 136


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (108, 'Nancy', 'Greenberg', 'NGREENBE', '515.124.4569', to_date('17-08-1994', 'dd-mm-yyyy'),
'FI_MGR', 12000.00, null, 101, 100);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (109, 'Daniel', 'Faviet', 'DFAVIET', '515.124.4169', to_date('16-08-1994', 'dd-mm-yyyy'),
'FI_ACCOUNT', 9000.00, null, 108, 100);

insert into hr.staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id)
values (110, 'John', 'Chen', 'JCHEN', '515.124.4269', to_date('28-09-1997', 'dd-mm-yyyy'),
'FI_ACCOUNT', 8200.00, null, 108, 100);

3.3 Keyword
Keywords are meaningful words in SQL statements. This topic describes SQL
standard keywords and special GaussDB 100 keywords.

Keywords are classified as reserved words and non-reserved words. Standards


require that reserved keywords not be used as other identifiers. Non-reserved
keywords have special meanings only in a specific environment and can be used as
identifiers in other environments.

Table 3-1 SQL keywords

Keyword GaussDB 100 SQL:1999 SQL-92

ABORT Non-reserved - -

ABS - Non-reserved -

ABSOLUTE - Reserved Reserved

ACCESS - - -

ACCOUNT Non-reserved - -

ACTION - Reserved Reserved

ADA - Non-reserved Non-


reserved

ADD Reserved Reserved Reserved

ADMIN - Reserved -

AFTER Non-reserved Reserved -

AGGREGATE - Reserved -

ALIAS - Reserved -

ALL Reserved Reserved Reserved

ALLOCATE - Reserved Reserved

ALSO - - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 137


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

ALTER Reserved Reserved Reserved

ALWAYS - - -

ANALYSE - - -

ANALYZE Reserved - -

AND Reserved Reserved Reserved

ANY Reserved Reserved Reserved

APP - - -

ARE - Reserved Reserved

ARRAY - Reserved -

AS Reserved Reserved Reserved

ASC Reserved Reserved Reserved

ASENSITIVE - Non-reserved -

ASSERTION - Reserved Reserved

ASSIGNMENT - Non-reserved -

ASYMMETRIC - Non-reserved -

AT - Reserved Reserved

ATOMIC - Non-reserved -

ATTRIBUTE - - -

AUDIT Reserved - -

AUTHID - - -

AUTHORIZATION - Reserved Reserved

AUTOEXTEND Non-reserved - -

AUTOMAPPED - - -

AVG - Non-reserved Reserved

BACKWARD - - -

BARRIER - - -

BEFORE Non-reserved Reserved -

BEGIN Reserved Reserved Reserved

BETWEEN Reserved Non-reserved Reserved

BIGINT Non-reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 138


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

BINARY Non-reserved Reserved -

BINARY_DOUBLE Non-reserved - -

BINARY_INTEGER Non-reserved - -

BIT - Reserved Reserved

BITVAR - Non-reserved -

BIT_LENGTH - Non-reserved Reserved

BLOB Non-reserved Reserved -

BOOLEAN Non-reserved Reserved -

BOTH Non-reserved Reserved Reserved

BUCKETS - - -

BREADTH - Reserved -

BY Reserved Reserved Reserved

C - Non-reserved Non-
reserved

CACHE Non-reserved - -

CALL Non-reserved Reserved -

CALLED - Non-reserved -

CARDINALITY - Non-reserved -

CASCADE Non-reserved Reserved Reserved

CASCADED Non-reserved Reserved Reserved

CASE Reserved Reserved Reserved

CAST Non-reserved Reserved Reserved

CATALOG Non-reserved Reserved Reserved

CATALOG_NAME - Non-reserved Non-


reserved

CHAIN - Non-reserved -

CHAR Reserved Reserved Reserved

CHARACTER Non-reserved Reserved Reserved

CHARACTERISTICS - - -

CHARACTER_LENGTH - Non-reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 139


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

CHARACTER_SET_CATA - Non-reserved Non-


LOG reserved

CHARACTER_SET_NAM - Non-reserved Non-


E reserved

CHARACTER_SET_SCH - Non-reserved Non-


EMA reserved

CHAR_LENGTH - Non-reserved Reserved

CHECK Reserved Reserved Reserved

CHECKED - Non-reserved -

CHECKPOINT Non-reserved - -

CLASS - Reserved -

CLEAN - - -

CLASS_ORIGIN - Non-reserved Non-


reserved

CLOB Non-reserved Reserved -

CLOSE Non-reserved Reserved Reserved

CLUSTER - - -

COALESCE Non-reserved Non-reserved Reserved

COBOL - Non-reserved Non-


reserved

COLLATE Non-reserved Reserved Reserved

COLLATION - Reserved Reserved

COLLATION_CATALOG - Non-reserved Non-


reserved

COLLATION_NAME - Non-reserved Non-


reserved

COLLATION_SCHEMA - Non-reserved Non-


reserved

COLUMN Reserved Reserved Reserved

COLUMNS Non-reserved - -

COLUMN_NAME - Non-reserved Non-


reserved

COMMAND_FUNCTIO - Non-reserved Non-


N reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 140


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

COMMAND_FUNCTIO - Non-reserved -
N_CODE

COMMENT Non-reserved - -

COMMENTS - - -

COMMIT Non-reserved Reserved Reserved

COMMITTED - Non-reserved Non-


reserved

COMPRESS Reserved - -

COMPLETION - Reserved -

CONCURRENTLY - - -

CONDITION - - -

CONDITION_NUMBER - Non-reserved Non-


reserved

CONFIGURATION - - -

CONNECT Reserved Reserved Reserved

CONNECTION - Reserved Reserved

CONNECTION_NAME - Non-reserved Non-


reserved

CONSTRAINT Reserved Reserved Reserved

CONSTRAINTS - Reserved Reserved

CONSTRAINT_CATALO - Non-reserved Non-


G reserved

CONSTRAINT_NAME - Non-reserved Non-


reserved

CONSTRAINT_SCHEM - Non-reserved Non-


A reserved

CONSTRUCTOR - Reserved -

CONTAINS - Non-reserved -

CONTENT Non-reserved - -

CONTINUE Reserved Reserved Reserved

CONVERSION - - -

CONVERT Non-reserved Non-reserved Reserved

COORDINATOR - - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 141


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

COPY - - -

CORRESPONDING - Reserved Reserved

COST - - -

COUNT - Non-reserved Reserved

CREATE Reserved Reserved Reserved

CROSS - Reserved Reserved

CSV - - -

CUBE - Reserved -

CUMULATIVE Reserved - -

CURRENT Reserved Reserved Reserved

CURRENT_CATALOG - - -

CURRENT_DATE Non-reserved Reserved Reserved

CURRENT_PATH - Reserved -

CURRENT_ROLE - Reserved -

CURRENT_SCHEMA - - -

CURRENT_TIME - Reserved Reserved

CURRENT_TIMESTAMP Non-reserved Reserved Reserved

CURRENT_USER - Reserved Reserved

CURSOR Non-reserved Reserved Reserved

CURSOR_NAME - Non-reserved Non-


reserved

CYCLE Non-reserved Reserved -

DATA Non-reserved Reserved Non-


reserved

DATABASE Non-reserved - -

DATAFILE Non-reserved - -

DATE Reserved Reserved Reserved

DATETIME_INTERVAL_ - Non-reserved Non-


CODE reserved

DATETIME_INTERVAL_ - Non-reserved Non-


PRECISION reserved

DAY Non-reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 142


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

DBCOMPATIBILITY - - -

DEALLOCATE - Reserved Reserved

DEC - Reserved Reserved

DECIMAL Reserved Reserved Reserved

DECLARE Non-reserved Reserved Reserved

DECODE - - -

DEFAULT Reserved Reserved Reserved

DEFAULTS - - -

DEFERRABLE Non-reserved Reserved Reserved

DEFERRED - Reserved Reserved

DEFINED - Non-reserved -

DEFINER - Non-reserved -

DELETE Reserved Reserved Reserved

DELIMITER - - -

DELIMITERS - - -

DELTA - - -

DEPTH - Reserved -

DEREF - Reserved -

DESC Reserved Reserved Reserved

DESCRIBE - Reserved Reserved

DESCRIPTOR - Reserved Reserved

DESTROY - Reserved -

DESTRUCTOR - Reserved -

DETERMINISTIC - Reserved -

DIAGNOSTICS - Reserved Reserved

DICTIONARY Non-reserved Reserved -

DIRECT - - -

DISABLE Non-reserved - -

DISCARD Non-reserved - -

DISCONNECT Non-reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 143


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

DISPATCH - Non-reserved -

DISTINCT Reserved Reserved Reserved

DISTRIBUTE Non-reserved - -

DISTRIBUTION - - -

DO Non-reserved - -

DOCUMENT - - -

DOMAIN - Reserved Reserved

DOUBLE Non-reserved Reserved Reserved

DROP Reserved Reserved Reserved

DYNAMIC - Reserved -

DYNAMIC_FUNCTION - Non-reserved Non-


reserved

DYNAMIC_FUNCTION_ - Non-reserved -
CODE

EACH - Reserved -

ELSE Reserved Reserved Reserved

ENABLE Non-reserved - -

ENCODING - - -

ENCRYPTED - - -

END Non-reserved Reserved Reserved

END-EXEC - Reserved Reserved

ENFORCED - - -

ENUM - - -

EOL - - -

EQUALS - Reserved -

ESCAPE Non-reserved Reserved Reserved

ESCAPING - - -

EVERY - Reserved -

EXCEPT - Reserved Reserved

EXCEPTION Non-reserved Reserved Reserved

EXCHANGE - - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 144


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

EXCLUDE - - -

EXCLUDING - - -

EXCLUSIVE - - -

EXEC Non-reserved Reserved Reserved

EXECUTE Non-reserved Reserved Reserved

EXISTING - Non-reserved -

EXISTS Reserved Non-reserved Reserved

EXPLAIN Non-reserved - -

EXTENSION - - -

EXTERNAL - Reserved Reserved

EXTRACT - Non-reserved Reserved

FALSE Reserved Reserved Reserved

FAMILY Non-reserved - -

FETCH Non-reserved Reserved Reserved

FILEHEADER Non-reserved - -

FINAL - Non-reserved -

FINISH Reserved - -

FIRST Non-reserved Reserved Reserved

FIXED Non-reserved Reserved Reserved

FLOAT Non-reserved Reserved Reserved

FOLLOWING Non-reserved - -

FOR Reserved Reserved Reserved

FORALL Reserved - -

FORCE Non-reserved - -

FOREIGN Non-reserved Reserved Reserved

FORMATTER Non-reserved - -

FORTRAN - Non-reserved Non-


reserved

FORWARD Non-reserved - -

FOUND - Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 145


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

FREE - Reserved -

FREEZE Reserved - -

FROM Reserved Reserved Reserved

FULL Reserved Reserved Reserved

FUNCTION Reserved Reserved -

FUNCTIONS Non-reserved - -

G - Non-reserved -

GENERAL - Reserved -

GENERATED - Non-reserved -

GET - Reserved Reserved

GLOBAL Non-reserved Reserved Reserved

GO - Reserved Reserved

GOTO - Reserved Reserved

GRANT Reserved Reserved Reserved

GRANTED Non-reserved Non-reserved -

GREATEST - - -

GROUP Reserved Reserved Reserved

GROUPID Non-reserved - -

GROUPING - Reserved -

HANDLER Non-reserved - -

HAVING Reserved Reserved Reserved

HEADER Non-reserved - -

HIERARCHY - Non-reserved -

HOLD Non-reserved Non-reserved -

HOST - Reserved -

HOUR Non-reserved Reserved Reserved

IDENTIFIED Reserved - -

IDENTITY Non-reserved Reserved Reserved

IF Non-reserved - -

IGNORE - Reserved -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 146


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

ILIKE Reserved - -

IMMEDIATE Non-reserved Reserved Reserved

IMMUTABLE Non-reserved - -

IMPLEMENTATION - Non-reserved -

IMPLICIT Non-reserved - -

IN Reserved Reserved Reserved

INCLUDING Non-reserved - -

INCREMENT Reserved - -

INDEX Reserved - -

INDEXES Non-reserved - -

INDICATOR - Reserved Reserved

INFIX - Non-reserved -

INHERIT Non-reserved - -

INHERITS Non-reserved - -

INITIAL Non-reserved - -

INITIALIZE - Reserved -

INITIALLY Non-reserved Reserved Reserved

INITRANS Non-reserved - -

INLINE Non-reserved - -

INNER Reserved Reserved Reserved

INOUT - Reserved -

INPUT Non-reserved Reserved Reserved

INSENSITIVE Non-reserved Non-reserved Reserved

INSERT Reserved Reserved Reserved

INSTANCE - Non-reserved -

INSTANTIABLE - Non-reserved -

INSTEAD Non-reserved - -

INT Non-reserved Reserved Reserved

INTEGER Reserved Reserved Reserved

INTERSECT Reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 147


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

INTERVAL Non-reserved Reserved Reserved

INTO Reserved Reserved Reserved

INVOKER Non-reserved Non-reserved -

IS Reserved Reserved Reserved

ISNULL Reserved - -

ISOLATION Non-reserved Reserved Reserved

ITERATE - Reserved -

JOIN Reserved Reserved Reserved

K - Non-reserved -

KEY Non-reserved Reserved Reserved

KEY_MEMBER - Non-reserved -

KEY_TYPE - Non-reserved -

LABEL Non-reserved - -

LANGUAGE Non-reserved Reserved Reserved

LARGE Non-reserved Reserved -

LAST Non-reserved Reserved Reserved

LATERAL - Reserved -

LC_COLLATE Non-reserved - -

LC_CTYPE Non-reserved - -

LEADING Non-reserved Reserved Reserved

LEAKPROOF Non-reserved - -

LEAST - - -

LEFT Non-reserved Reserved Reserved

LENGTH - Non-reserved Non-


reserved

LESS Non-reserved Reserved -

LEVEL Reserved Reserved Reserved

LIKE Reserved Reserved Reserved

LIMIT Non-reserved Reserved -

LIST Reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 148


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

LISTEN Non-reserved - -

LOAD Non-reserved - -

LOCAL Non-reserved Reserved Reserved

LOCALTIME Reserved Reserved -

LOCALTIMESTAMP Reserved Reserved -

LOCATION Non-reserved - -

LOCATOR - Reserved -

LOCK Reserved - -

LOG Non-reserved - -

LOGGING Non-reserved - -

LOGIN Non-reserved - -

LOOP Non-reserved - -

LOWER - Non-reserved Reserved

M - Non-reserved -

MAP - Reserved -

MAPPING Non-reserved - -

MATCH Non-reserved Reserved Reserved

MATCHED - - -

MAX - Non-reserved Reserved

MAXEXTENTS Non-reserved - -

MAXSIZE Non-reserved - -

MAXTRANS Non-reserved - -

MAXVALUE Non-reserved - -

MERGE Non-reserved - -

MESSAGE_LENGTH - Non-reserved Non-


reserved

MESSAGE_OCTET_LEN - Non-reserved Non-


GTH reserved

MESSAGE_TEXT - Non-reserved Non-


reserved

METHOD - Non-reserved -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 149


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

MIN - Non-reserved Reserved

MINEXTENTS Non-reserved - -

MINUS Reserved - -

MINUTE Non-reserved Reserved Reserved

MINVALUE Non-reserved - -

MOD - Non-reserved -

MODE Non-reserved - -

MODIFIES - Reserved -

MODIFY Reserved Reserved -

MODULE - Reserved Reserved

MONTH Non-reserved Reserved Reserved

MORE - Non-reserved Non-


reserved

MOVE Non-reserved - -

MOVEMENT Non-reserved - -

MUMPS - Non-reserved Non-


reserved

NAME Non-reserved Non-reserved Non-


reserved

NAMES Non-reserved Reserved Reserved

NATIONAL - Reserved Reserved

NATURAL Reserved Reserved Reserved

NCHAR Reserved - -

NCLOB - Reserved -

NEW - Reserved -

NEXT Non-reserved Reserved Reserved

NLSSORT Non-reserved - -

NO Non-reserved Reserved Reserved

NOCOMPRESS Non-reserved - -

NOCYCLE Non-reserved - -

NODE Non-reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 150


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

NOLOGGING Non-reserved - -

NOLOGIN Non-reserved - -

NOMAXVALUE Non-reserved - -

NOMINVALUE Non-reserved - -

NONE - Reserved -

NOT Reserved Reserved Reserved

NOTHING Non-reserved - -

NOTIFY Non-reserved - -

NOTNULL Reserved - -

NOWAIT Reserved - -

NULL Reserved Reserved Reserved

NULLABLE - Non-reserved Non-


reserved

NULLIF - Non-reserved Reserved

NULLS Non-reserved - -

NUMBER Reserved Non-reserved Non-


reserved

NUMERIC Non-reserved Reserved Reserved

NUMSTR Non-reserved - -

NVARCHAR2 Non-reserved - -

NVL - - -

OBJECT Non-reserved Reserved -

OCTET_LENGTH - Non-reserved Reserved

OF Reserved Reserved Reserved

OFF Non-reserved Reserved -

OFFLINE Reserved - -

OFFSET Non-reserved - -

OIDS Non-reserved - -

OLD - Reserved -

ON Reserved Reserved Reserved

ONLINE Reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 151


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

ONLY Reserved Reserved Reserved

OPEN - Reserved Reserved

OPERATION - Reserved -

OPERATOR Non-reserved - -

OPTIMIZATION Non-reserved - -

OPTION Non-reserved Reserved Reserved

OPTIONS Non-reserved Non-reserved -

OR Reserved Reserved Reserved

ORDER Reserved Reserved Reserved

ORDINALITY - Reserved -

OUT - Reserved -

OUTER Non-reserved Reserved Reserved

OUTPUT - Reserved Reserved

OVER - - -

OVERLAPS - Non-reserved Reserved

OVERLAY - Non-reserved -

OVERRIDING - Non-reserved -

OWNED Non-reserved - -

OWNER Non-reserved - -

PAD - Reserved Reserved

PARAMETER - Reserved -

PARAMETERS - Reserved -

PARAMETER_MODE - Non-reserved -

PARAMETER_NAME - Non-reserved -

PARAMETER_ORDINAL - Non-reserved -
_POSITION

PARAMETER_SPECIFIC_ - Non-reserved -
CATALOG

PARAMETER_SPECIFIC_ - Non-reserved -
NAME

PARAMETER_SPECIFIC_ - Non-reserved -
SCHEMA

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 152


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

PARSER Non-reserved - -

PARTIAL Non-reserved Reserved Reserved

PARTITION Non-reserved - -

PARTITIONS Non-reserved - -

PASCAL - Non-reserved Non-


reserved

PASSING Non-reserved - -

PASSWORD Non-reserved - -

PATH - Reserved -

PCTFREE Non-reserved - -

PER Non-reserved - -

PERCENT Non-reserved - -

PERFORMANCE Non-reserved - -

PLACING Non-reserved - -

PLANS Non-reserved - -

PLI - Non-reserved Non-


reserved

POOL Non-reserved - -

POSITION - Non-reserved Reserved

POSTFIX - Reserved -

PRECEDING Non-reserved - -

PRECISION - Reserved Reserved

PREFERRED Non-reserved - -

PREFIX Non-reserved Reserved -

PREORDER - Reserved -

PREPARE Non-reserved Reserved Reserved

PREPARED Non-reserved - -

PRESERVE Non-reserved Reserved Reserved

PRIMARY Reserved Reserved Reserved

PRIVILEGE Non-reserved - -

PRIVILEGES Reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 153


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

PROCEDURAL Non-reserved - -

PROCEDURE Reserved Reserved Reserved

PROFILE Non-reserved - -

PUBLIC Reserved Reserved Reserved

QUERY Non-reserved - -

QUOTE Non-reserved - -

RANGE Non-reserved - -

RAW Reserved - -

READ Non-reserved Reserved Reserved

READS - Reserved -

REAL Non-reserved Reserved Reserved

REASSIGN Non-reserved - -

REBUILD Non-reserved - -

RECHECK Non-reserved - -

RECURSIVE Non-reserved Reserved -

REF Non-reserved Reserved -

REFERENCES Non-reserved Reserved Reserved

REFERENCING - Reserved -

REINDEX Non-reserved - -

REJECT Non-reserved - -

RELATIVE Non-reserved Reserved Reserved

RELEASE Non-reserved - -

RELOPTIONS Non-reserved - -

REMOTE Non-reserved - -

RENAME Reserved - -

REPEATABLE Non-reserved Non-reserved Non-


reserved

REPLACE Non-reserved - -

REPLICA Non-reserved - -

REPLICATION Non-reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 154


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

RESET Non-reserved - -

RESIZE Reserved - -

RESOURCE Non-reserved - -

RESTART Non-reserved - -

RESTRICT Non-reserved Reserved Reserved

RESULT - Reserved -

RETURN Non-reserved Reserved -

RETURNED_LENGTH - Non-reserved Non-


reserved

RETURNED_OCTET_LE - Non-reserved Non-


NGTH reserved

RETURNED_SQLSTATE - Non-reserved Non-


reserved

RETURNING Non-reserved - -

RETURNS Non-reserved Reserved -

REUSE Non-reserved - -

REVOKE Non-reserved Reserved Reserved

RIGHT Non-reserved Reserved Reserved

ROLE Non-reserved Reserved -

ROLLBACK Non-reserved Reserved Reserved

ROLLUP - Reserved -

ROUTINE - Reserved -

ROUTINE_CATALOG - Non-reserved -

ROUTINE_NAME - Non-reserved -

ROUTINE_SCHEMA - Non-reserved -

ROW - Reserved -

ROWID Reserved - -

ROWNUM Reserved - -

ROWS Reserved Reserved Reserved

ROWSCN Reserved - -

ROW_COUNT - Non-reserved Non-


reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 155


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

RULE Non-reserved - -

SAVEPOINT Non-reserved Reserved -

SCALE - Non-reserved Non-


reserved

SCHEMA Non-reserved Reserved Reserved

SCHEMA_NAME - Non-reserved Non-


reserved

SCOPE - Reserved -

SCROLL Non-reserved Reserved Reserved

SEARCH Non-reserved Reserved -

SECOND Non-reserved Reserved Reserved

SECTION - Reserved Reserved

SECURITY Non-reserved Non-reserved -

SELECT Reserved Reserved Reserved

SELF - Non-reserved -

SENSITIVE - Non-reserved -

SEQUENCE Non-reserved Reserved -

SEQUENCES Non-reserved - -

SERIALIZABLE Non-reserved Non-reserved Non-


reserved

SERVER Non-reserved - -

SERVER_NAME - Non-reserved Non-


reserved

SESSION Reserved Reserved Reserved

SESSIONTIMEZONE Non-reserved - -

SESSION_USER Non-reserved Reserved Reserved

SET Reserved Reserved Reserved

SETOF - - -

SETS - Reserved -

SHARE Non-reserved - -

SHOW Non-reserved - -

SIMILAR - Non-reserved -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 156


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

SIMPLE Non-reserved Non-reserved -

SIZE Non-reserved Reserved Reserved

SMALLDATETIME - - -

SMALLINT Non-reserved Reserved Reserved

SNAPSHOT Non-reserved - -

SOME Non-reserved Reserved Reserved

SOURCE - Non-reserved -

SPACE - Reserved Reserved

SPECIFIC - Reserved -

SPECIFICTYPE - Reserved -

SPECIFIC_NAME - Non-reserved -

SPLIT Non-reserved - -

SQL - Reserved Reserved

SQLCODE - - Reserved

SQLERROR - - Reserved

SQLEXCEPTION - Reserved -

SQL_MAP Reserved - -

SQLSTATE - Reserved Reserved

SQLWARNING - Reserved -

STABLE Non-reserved - -

STANDALONE Non-reserved - -

START Reserved Reserved -

STATE - Reserved -

STATEMENT Non-reserved Reserved -

STATIC - Reserved -

STATISTICS Non-reserved - -

STDIN Non-reserved - -

STDOUT Non-reserved - -

STORAGE Non-reserved - -

STORE Non-reserved - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 157


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

STRICT Non-reserved - -

STRIP Non-reserved - -

STRUCTURE - Reserved -

STYLE - Non-reserved -

SUBCLASS_ORIGIN - Non-reserved Non-


reserved

SUBLIST - Non-reserved -

SUBSTRING - Non-reserved Reserved

SUM - Non-reserved Reserved

SUPERUSER Non-reserved - -

SYMMETRIC Non-reserved Non-reserved -

SYNONYM Reserved - -

SYS_REFCURSOR Non-reserved - -

SYSDATE Reserved - -

SYSID Non-reserved - -

SYSTEM Non-reserved Non-reserved -

SYSTEM_USER - Reserved Reserved

TABLE Reserved Reserved Reserved

TABLES Non-reserved - -

TABLESPACE Non-reserved - -

TABLE_NAME - Non-reserved Non-


reserved

TEMP Non-reserved - -

TEMPLATE Non-reserved - -

TEMPORARY Non-reserved Reserved Reserved

TERMINATE - Reserved -

TEXT Non-reserved - -

THAN Non-reserved Reserved -

THEN Reserved Reserved Reserved

TIME - Reserved Reserved

TIMESTAMP Non-reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 158


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

TIMEZONE_HOUR - Reserved Reserved

TIMEZONE_MINUTE - Reserved Reserved

TINYINT Non-reserved - -

TO Reserved Reserved Reserved

TRAILING Non-reserved Reserved Reserved

TRANSACTION Non-reserved Reserved Reserved

TRANSACTIONS_COM - Non-reserved -
MITTED

TRANSACTIONS_ROLL - Non-reserved -
ED_BACK

TRANSACTION_ACTIVE - Non-reserved -

TRANSFORM - Non-reserved -

TRANSFORMS - Non-reserved -

TRANSLATE - Non-reserved Reserved

TRANSLATION - Reserved Reserved

TREAT - Reserved -

TRIGGER Reserved Reserved -

TRIGGER_CATALOG - Non-reserved -

TRIGGER_NAME - Non-reserved -

TRIGGER_SCHEMA - Non-reserved -

TRIM - Non-reserved Reserved

TRUE Reserved Reserved Reserved

TRUNCATE Non-reserved - -

TRUSTED Non-reserved - -

TYPE Non-reserved Non-reserved Non-


reserved

TYPES Non-reserved - -

UESCAPE - - -

UNBOUNDED Non-reserved - -

UNCOMMITTED Non-reserved Non-reserved Non-


reserved

UNDER - Reserved -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 159


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

UNENCRYPTED Non-reserved - -

UNION Reserved Reserved Reserved

UNIQUE Reserved Reserved Reserved

UNKNOWN Non-reserved Reserved Reserved

UNLIMITED Non-reserved - -

UNLISTEN Non-reserved - -

UNLOCK Non-reserved - -

UNLOGGED Non-reserved - -

UNNAMED - Non-reserved Non-


reserved

UNNEST - Reserved -

UNTIL Reserved - -

UNUSABLE Non-reserved - -

UPDATE Reserved Reserved Reserved

UPPER - Non-reserved Reserved

USAGE - Reserved Reserved

USER Reserved Reserved Reserved

USER_DEFINED_TYPE_ - Non-reserved -
CATALOG

USER_DEFINED_TYPE_ - Non-reserved -
NAME

USER_DEFINED_TYPE_ - Non-reserved -
SCHEMA

USING Non-reserved Reserved Reserved

VACUUM Non-reserved - -

VALID Non-reserved - -

VALIDATE Non-reserved - -

VALIDATION Non-reserved - -

VALIDATOR Non-reserved - -

VALUE Non-reserved Reserved Reserved

VALUES Reserved Reserved Reserved

VARCHAR Reserved Reserved Reserved

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 160


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

VARCHAR2 Reserved - -

VARIABLE - Reserved -

VARIADIC Non-reserved - -

VARYING Non-reserved Reserved Reserved

VERBOSE - - -

VERSION Non-reserved - -

VIEW Reserved Reserved Reserved

VOLATILE Non-reserved - -

WHEN Non-reserved Reserved Reserved

WHENEVER - Reserved Reserved

WHERE Reserved Reserved Reserved

WHILE Reserved - Reserved

WHITESPACE Non-reserved - -

WINDOW Non-reserved - -

WITH Reserved Reserved Reserved

WITHOUT Non-reserved Reserved -

WORK Non-reserved Reserved Reserved

WORKLOAD Non-reserved - -

WRAPPER Non-reserved - -

WRITE Non-reserved Reserved Reserved

XML Non-reserved - -

XMLATTRIBUTES - - -

XMLCONCAT - - -

XMLELEMENT - - -

XMLEXISTS - - -

XMLFOREST - - -

XMLPARSE - - -

XMLPI - - -

XMLROOT - - -

XMLSERIALIZE - - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 161


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword GaussDB 100 SQL:1999 SQL-92

YEAR Non-reserved Reserved Reserved

YES Non-reserved - -

ZONE Non-reserved Reserved Reserved

3.4 Data Types


A data type is a basic data attribute. Occupied storage space and allowed
operations vary according to data types. In a database, data is stored in tables, in
which a data type is specified for each column. Data in the column must be of its
allowed data type.

3.4.1 Numeric Data Types


Numeric data types in GaussDB 100 include integer, floating-point, and high-
precision types.

3.4.1.1 Integer
GaussDB 100 supports basic (native) 32-bit integers and 64-bit integers.

3.4.1.1.1 32-Bit Signed Integer

BINARY_INTEGER
Syntax:
BINARY_INTEGER

Purpose: Stores a 32-bit signed integer.

Value range: -2^31 to 2^31 -1

Occupied space: 4 bytes

INTEGER
Syntax:
INTEGER

Purpose:

● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_INTEGER type.


● USE_NATIVE_DATATYPE=FALSE maps to the NUMBER(38) type.

Keywords:

● INT

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 162


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● INT SIGNED
● INTEGER SIGNED
● SHORT
● SMALLINT
● TINYINT

● USE_NATIVE_DATATYPE is a data type control parameter. It maps some confused


keywords of numeric data types. GaussDB 100 provides this parameter to meet the
compatibility requirements of different databases and enrich the data types in
databases. Table 3-2 lists mapping relationships between data types when
USE_NATIVE_DATATYPE is set to TRUE or FALSE. The default value of
USE_NATIVE_DATATYPE is TRUE.
● If data of the INTEGER type is calculated (added, subtracted, or multiplied), it will be
converted to the BIGINT type, avoiding overflow.

In principle, some keywords are not affected by the USE_NATIVE_DATATYPE


parameter, including BINARY_BIGINT, BINARY_INTEGER, and BINARY_DOUBLE.

Table 3-2 Data type mapping


Data Type Keyword Data Type After Data Type After Conversion
Conversion for Value for Value TRUE
FALSE

BIGINT NUMBER(38) BINARY_BIGINT

DOUBLE NUMBER BINARY_DOUBLE

FLOAT NUMBER BINARY_DOUBLE

INT/INTEGER NUMBER(38) BINARY_INTEGER

UINT/INTEGER NUMBER(38) BINARY_UINT32


UNSIGNED

REAL NUMBER BINARY_DOUBLE

SMALLINT NUMBER(38) BINARY_INTEGER

TINYINT NUMBER(38) BINARY_INTEGER

3.4.1.1.2 32-Bit Unsigned Integer

BINARY_UINT32
Syntax:
BINARY_UINT32

Purpose: Stores a 32-bit unsigned integer.

Value range: [0, 232 – 1]


Occupied space: 4 bytes

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 163


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

INTEGER UNSIGNED
Syntax:
INTEGER UNSIGNED

Purpose:

● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_UINT32 type.


● USE_NATIVE_DATATYPE=FALSE maps to the NUMBER(38) type.

Keywords:

● UINT
● BINARY_UINT32
● INTEGER UNSIGNED

For the INTEGER UNSIGNED data type, the error message "GS-00659 %s out of range" is
displayed if overflow occurs.

3.4.1.1.3 64-Bit Signed Integers

BINARY_BIGINT
Syntax:
BINARY_BIGINT

Purpose: Stores a 64-bit signed integer.

Value range: -2^63 to 2^63 -1

Occupied space: 8 bytes

Keywords:

● BINARY_BIGINT
● BIGINT SIGNED

BIGINT
Syntax:
BIGINT

Purpose:

● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_BIGINT type.


● USE_NATIVE_DATATYPE = FALSE maps to the NUMBER(38) type.

Keywords:

● BIGINT
● BINARY_BIGINT

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 164


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

For the BIGINT data type, error GS-00659 "%s out of range" will be displayed if there is
overflow.

3.4.1.2 Floating-Point Numbers


GaussDB 100 supports a basic double-precision floating-point data type, DOUBLE.
This type complies with the standard binary floating-point implementation of IEEE
754, and it is supported by lower-layer processors, operating systems, and
compilers.
The data type is imprecise and variable. If the data type is inaccurate, some values
cannot be accurately converted to internal formats and will be stored as
approximate values. Therefore, data that is printed after being stored may differ
from the original data. Therefore, pay attention to the following points when
using this data type:
● If accurate calculation (for example, financial services) is required, the
Number/Decimal type must be used.
● When two floating-point values are compared, the expected result may not be
obtained.
● In parallel query, data rows are not read in sequence. Therefore, different
results may be obtained each time a column with a floating point number,
(sum), or an average value is (avg).
● Note that when a smaller floating point number is added to or subtracted
from a large floating point number, the result may be inconsistent due to
insufficient precision.

BINARY_DOUBLE
Syntax:
BINARY_DOUBLE

Purpose: Stores 64-bit double-precision floating point numbers.


Occupied space: 8 bytes
Value range: [-1.79E+308, +1.79E+308]

DOUBLE
Syntax:
DOUBLE

Purpose:
● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_DOUBLE type.
● USE_NATIVE_DATATYPE = FALSE maps to the NUMBER type.
Keywords:
● REAL
● DOUBLE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 165


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● FLOAT
● BINARY_DOUBLE

FLOAT
Syntax:
FLOAT

Purpose:
● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_DOUBLE type.
● USE_NATIVE_DATATYPE = FALSE maps to the NUMBER type.
Keywords:
● REAL
● DOUBLE
● FLOAT
● BINARY_DOUBLE

REAL
Syntax:
REAL

Purpose:
● USE_NATIVE_DATATYPE=TRUE maps to the BINARY_DOUBLE type.
● USE_NATIVE_DATATYPE = FALSE maps to the NUMBER type.
Occupied space: 8 bytes
Keywords:
● REAL
● DOUBLE
● FLOAT
● BINARY_DOUBLE

● Floating point number are not accurate, and their upper and lower boundaries are not
exact values. Note this point when testing the bounds. select cast(1E308 as real) + 1
from SYS_DUMMY; cannot be directly used for tests. This is because of floating-point
number definitions at the bottom layer of computers, and is irrelevant to the specific
implementation of GaussDB 100.
● For the DOUBLE data type, error GS-00659 "%s out of range" will be displayed if there
is overflow.

3.4.1.3 High-Precision Numbers


● DECIMAL and NUMBER data types can store very large numbers with high
precision and can be accurately calculated. In the current implementation,
NUMBER and DECIMAL are combined into the same type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 166


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The DECIMAL or NUMBER data type can store a maximum of 40 valid digits.
● For the DECIMAL or NUMBER data type, error GS-00659 "%s out of range"
will be displayed if there is overflow.

DECIMAL/NUMBER
Syntax:
NUMBER/DECIMAL
NUMBER/DECIMAL(p)
NUMBER/DECIMAL(p,s)

Purpose: Stores high-precision floating point numbers.

Value range: (-1.0E128, 1.0E128)

● The value range of p is [1, 38], indicating the maximum storage precision.
● The value range of s is [–84, 127], indicating the number of valid digits after
the decimal point.
● If p and s are not specified, the value after the decimal point is not limited. A
maximum of 40 valid digits can be stored.
● If you do not specify s or s=0, the NUMBER type has no decimal part.

Occupied space: 4-24 bytes

Keywords:

● DECIMAL
● NUMBER
● NUMERIC

You can define a DECIMAL or NUMBER column in the following ways:


● column_name NUMBER
In this case, the column directly stores the input value and stores the value by
a maximum of 40 digits.
● column_name NUMBER(precision, scale)
In GaussDB 100, the precision (precision) and number of decimal places
(scale) can be set for values of the NUMBER type. The syntax is as follows:
column_name NUMBER(precision, scale)

– precision indicates the number of valid digits, and its value range is [1,
38]. scale indicates the number of digits to the right of the decimal point,
and its value range is [–84, 127]. If the value of scale is a negative
number, the number of digits on the left of the decimal point is reduced.
– If precision is specified but scale is not specified, the default value of
scale is 0. That is, in column_name NUMBER(precision), the default
value of scale is 0, indicating that there is no decimal part.
The following table lists how the settings of precision and scale affect
the storage of the Number type.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 167


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Table 3-3 Impact of precision and scale on Number storage

Input Data NUMBER Definition Storage Result

1234567.89 NUMBER 1234567.89

1234567.89 NUMBER(12,1) 1234567.9 (The 9 at


the end is rounded
off.)

1234567.61 NUMBER(12,1) 1234567.6

1234567.61 NUMBER(12) 1234568

1234567.61 NUMBER(12,3) 1234567.61

1234567.61 NUMBER(12,6) Error. The precision


overflows.

1234567.61 NUMBER(12,-2) 1234600

DECIMAL and NUMBER types use variable-length storage, and its length depends on the
number of valid digits.

3.4.2 Character Data Types


Character data types are used to store characters (including text and digits) in
string (STRING).
● If the field is set to a character, for example, varchar(N char), the maximum
space that can be occupied is 8000 characters.
● Currently, GaussDB 100 supports only the UTF-8 character set. Therefore, in
VARCHAR, a Chinese character or full-width character can occupy 2 to 6
bytes, and a digit or English character can occupy only 1 byte.
● The EMPTY_STRING_AS_NULL parameter can be used to specify whether to
convert an empty string to NULL for the VARCHAR2 and VARCHAR types. If
EMPTY_STRING_AS_NULL is set to TRUE, an empty string is processed as
NULL. If this parameter is set to FALSE, an empty string is processed as it is.

3.4.2.1 Fixed-Length String

CHAR
Syntax:
CHAR(size [BYTE | CHAR])

Purpose: Stores fixed-length bytes or strings.


● BYTE indicates bytes.
● CHAR indicates strings.
The default value is BYTE.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 168


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Occupied space: 1 to 8000 bytes


Keywords: CHAR

● For a fixed-length string, size BYTE or size CHAR indicates the maximum number of
bytes or characters that can be contained.
● If neither CHAR nor BYTE is specified, BYTE is used by default.
● If the input length is less than the value specified by size, spaces are used to right-pad
the value.

NCHAR
Syntax:
NCHAR(size)

Purpose: It is equivalent to CHAR(size CHAR) and is used to store fixed-length


strings.
Occupied space: 1 to 8000 bytes
Keywords: NCHAR

3.4.2.2 Variable-Length String

CLOB
Syntax:
CLOB

Purpose: Stores the variable-length strings of large objects.


Occupied space: 0 to 4 GB
Keywords:
● CLOB
● TEXT
● LONGTEXT
● LONG

VARCHAR
Syntax:
VARCHAR(size [BYTE | CHAR])

Purpose: Stores variable-length bytes or strings.


● size indicates the maximum number of bytes or characters that can be
contained.
● BYTE indicates bytes.
● CHAR indicates strings.
The default value is BYTE.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 169


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Occupied space: 1 to 8000 bytes


Keywords: VARCHAR

NVARCHAR
Syntax:
NVARCHAR(size)

Purpose: It is equivalent to VARCHAR(size CHAR) and is used to store variable-


length strings.
Occupied space: 1 to 8000 bytes
Keywords: NVARCHAR

3.4.3 Binary Data Types


GaussDB 100 supports binary types BINARY, VARBINARY, IMAGE, and BLOB.
A binary string is a byte sequence. The difference between a binary string and a
common string sequence is that a binary string can store a value of 0, and can
store characters other than letters and numbers. In short, binary strings are used
to store byte data and strings are used to store text.

BINARY
Syntax:
BINARY(size)

Purpose: Stores fixed-length binary data.


If the input length is less than size, the input is right padded with 0.
Occupied space: 1 to 8000 bytes
Keywords: BINARY

VARBINARY
Syntax:
VARBINARY(size)

Purpose: Stores variable-length binary data.


Occupied space: 1 to 8000 bytes
Keywords: VARBINARY

IMAGE
Syntax:
IMAGE

Purpose: Stores large object data. It is the large object type of VARBINARY.
Occupied space: 0 to 4 GB

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 170


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keywords:

● IMAGE
● LONGBLOB
● MEDIUMBLOB

BLOB
Syntax:
BLOB

Purpose: Stores binary data of variable-length objects. It is the large object type of
RAW.

The input is a hexadecimal string.

Occupied space: 0 to 4 GB

Keywords:

● BLOB
● BYTEA

3.4.4 Datetime Data Types


GaussDB 100 supports the following date/time types: DATE, TIMESTAMP WITH/
WITHOUT TIME ZONE, and INTERVAL.

DATETIME/DATE
Syntax:
DATETIME

Purpose: Stores data of the date type that does not contain the time zone.

The value includes year, month, day, hour, minute, and second.

Value range: [0001-01-01 00:00:00, 9999-12-31 23:59:59]

Occupied space: 8 bytes

Keywords:

● DATE
● DATETIME

TIMESTAMP
Syntax:
TIMESTAMP[(n)]

Purpose: Stores the data of the timestamp type without the time zone.

● The value includes year, month, day, hour, minute, second, and microsecond.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 171


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The value range of n is [0, 6], indicating the precision after second.
TIMESTAMP(n) can also be set to TIMESTAMP without any parameters. In this
case, the number of decimal digits after the second is 6 by default.
Value range: [0001-01-01 00:00:00.000000, 9999-12-31 23:59:59.999999]
Occupied space: 8 bytes
Keywords: TIMESTAMP

TIMESTAMP(n) WITH TIME ZONE


Syntax:
TIMESTAMP(n) WITH TIME ZONE

Purpose: Stores the data of the timestamp type with the time zone.
● The value includes year, month, day, hour, minute, second, and microsecond.
● The value range of n is [0, 6], indicating the precision after second.
TIMESTAMP(n) can also be set to TIMESTAMP without any parameters. In this
case, the number of decimal digits after the second is 6 by default.
Value range: [0001-01-01 00:00:00.000000, 9999-12-31 23:59:59.999999]
Occupied space: 12 bytes
Keywords: TIMESTAMP(n) WITH TIME ZONE

TIMESTAMP(n) WITH LOCAL TIME ZONE


Syntax:
TIMESTAMP(n) WITH LOCAL TIME ZONE

Purpose: Stores data of the time stamp type with the time zone. Time zone is not
stored. When data is stored, its timestamp is converted to the timestamp of the
database time zone. When users check the data, the timestamp is converted to
the timestamp of the time zone where the current session is located.
TIMESTAMP(n) can also be set to TIMESTAMP without any parameters. In this
case, the number of decimal digits after the second is 6 by default.
Occupied space: 8 bytes
Keywords: TIMESTAMP(n) WITH LOCAL TIME ZONE

Format Control Characters of the Date Type


For details about the format control characters of the date type, see Table 3-4.
Not all formatted strings can be converted. Only those marked as "Conversion
Reversible" in the following table can be converted.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 172


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Table 3-4 Format control characters of the date type


Symbol Description Conversion Example
Reversible

" " (space), "-" Delimiter Yes -- Use the delimiter "X" to
separate seconds and
(hyphen), milliseconds in data of the date
"\", "/", ":", type.
select
"," (comma), "." to_timestamp('2017-09-11
(period), ";" 23:45:59.44', 'YYYY-MM-DD
HH24:MI:SSXFF6') from
(semicolon), X SYS_DUMMY;
-- Use the delimiters "-"
(hyphen), "/", ":",
and "." to separate data of the
date type.
select to_char(systimestamp,
'YYYY-MM/DD HH24.MI:SS.FF')
from SYS_DUMMY;
-- Use the delimiters "
" (space), "\", ",",
and ";" to separate data of the
date type.
select to_char(systimestamp,
'YYYY MM\DD HH24.MI;SS,FF')
from SYS_DUMMY;

"text" Text type Yes Text type. If it is used as


an output parameter, the
content enclosed in the
quotation marks is
displayed. If it is used as
an input parameter, the
content in the quotation
marks is skipped and
spaces are ignored.
select to_char(sysdate, '"Hello
world!"') from SYS_DUMMY;

AM and PM Meridiem No select to_char(systimestamp,


'HH12:MI:SS AM') from
indicator SYS_DUMMY;

CC Century No select to_char(systimestamp,


'CC') from SYS_DUMMY;

DAY Full weekday No select to_char(systimestamp,


'DAY') from SYS_DUMMY;
name

DY Abbreviated No select to_char(systimestamp,


'DY') from SYS_DUMMY;
weekday
name

DDD Day number No select


to_char(to_date('2018-01-07',
of year 'YYYY-MM-DD'), 'DDD') from
SYS_DUMMY;

DD Day number Yes select


to_char(to_date('2018-01-07',
of month 'YYYY-MM-DD'), 'DD') from
SYS_DUMMY;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 173


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Symbol Description Conversion Example


Reversible

D Day number No select


to_char(to_date('2018-01-07',
of week 'YYYY-MM-DD'), 'D') from
SYS_DUMMY;

FF3, Decimal part Yes select to_char(systimestamp,


'FF3') from SYS_DUMMY;
FF6, of the
SECOND
FF (FF6 by field
default)

HH12, 12- or 24- Yes select to_char(systimestamp,


'HH,HH12,HH24') from
HH24, hour format. SYS_DUMMY;

HH (HH12 by
default)

MI Minute (0 to Yes -
59)

MM Month Yes -
number (1 to
12) of a date

MONTH Full name of Yes select to_char(systimestamp,


'MONTH, MON') from
the month in SYS_DUMMY;
a date

MON Abbreviated Yes -


name of the
month in a
date

Q Quarter (1 to No -
4) of a date

SSSSS Seconds past No -


midnight (0
to 86400 –
1)

SS Second (0 to Yes -
59)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 174


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Symbol Description Conversion Example


Reversible

WW Week of a No -
year that the
current date
is in. The first
week starts
from the first
day of the
current year
and 7 days
are regarded
as a week.

W Week of a No -
month that
the current
date is in.
The first
week starts
from the first
day of the
current
month and 7
days are
regarded as
a week.

YYYY Four-digit Yes -


year

YYY 3-digit year No -


(for example,
2018 can be
written as
018)

YY 2-digit year No -
(for example,
2018 can be
written as
18)

Y single-digit No select to_char(systimestamp,


'Y') from SYS_DUMMY;
year (for
example,
2018 can be
written as 8)

TZH Hours in Yes select


time zone to_char(current_timesta
information mp , 'TZH') from
SYS_DUMMY;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 175


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Symbol Description Conversion Example


Reversible

TZM Minutes in Yes select


time zone to_char(current_timesta
information mp , 'TZM') from
SYS_DUMMY;

The system also provides the default output format for the date type, as shown in
Table 3-5.

Table 3-5 Default output format of the date type

Date Type Default Output Format

DATETIME YYYY-MM-DD HH24:MI:SS

TIMESTAMP YYYY-MM-DD HH24:MI:SS.FF

TIMESTAMP WITH TIME ZONE YYYY-MM-DD HH24:MI:SS.FF TZH:TZM

TIMESTAMP WITH LOCAL TIME ZONE YYYY-MM-DD HH24:MI:SS.FF

Examples
● Based on the description about format control characters, you can use the
TO_CHAR function to specify the output format of the date type. For
example:
SELECT to_char(sysdate, 'MON-YY-DD') FROM SYS_DUMMY;

TO_CHAR(SYSDATE, 'MON-YY-DD')
-----------------------------
JAN-18-07
1 rows fetched.

SELECT to_char(sysdate, 'MON-YY-DD HH:MI:SS AM') FROM SYS_DUMMY;

TO_CHAR(SYSDATE, 'MON-YY-DD HH
-------------------------------
JAN-18-07 05:01:15 AM
1 rows fetched.

● The default output format of the date type is as follows:


SELECT sysdate, systimestamp FROM SYS_DUMMY;

SYSDATE SYSTIMESTAMP
---------------------- ----------------------------------------
2018-01-07 17:18:18 2018-01-07 17:18:18.230000 +08:00
1 rows fetched.

● Use format control characters to convert a string to the date type.


SELECT to_date('07-JAN-2018', 'DD-MON-YYYY') FROM SYS_DUMMY;

TO_DATE('07-JAN-2018', 'DD-MON-YYYY')
-------------------------------------
2018-01-07 00:00:00
1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 176


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.4.5 Boolean Data Type


GaussDB 100 supports the Boolean type. The value of the Boolean type can only
be TRUE or FALSE, corresponding to the numbers 1 and 0, respectively, for
internal storage.

BOOLEAN
Syntax:
BOOLEAN

Function: Stores Boolean data.


Valid value: TRUE, FALSE
● In SQL statements, the following Boolean inputs are supported:
– Reserved word: TRUE and FALSE (case insensitive)
– String:

▪ Common string: TRUE and FALSE (case insensitive)

▪ Single character: T and F (case insensitive)

▪ Number string: 1 and 0.


– NULL: processed same as other NULL values
● Boolean output
When the Boolean type is displayed (for example, in the SELECT statement)
or converted to a string, GaussDB 100 outputs the value 1 as a string TRUE
and value 0 as FALSE.
Occupied space: 4 bytes
Keywords:
● BOOL
● BOOLEAN

Conversion Between Boolean and Other Types


GaussDB 100 defines the following conversion rules:
● Integer types (INT and BIGINT): The Boolean type can be regarded as
numbers 0 and 1. Therefore, a Boolean value can be converted to the integer
0 or 1, and an integer can be converted to the Boolean type. Integer 0
corresponds to the Boolean value FALSE and other integers correspond to the
Boolean value TRUE.
● DOUBLE and DECIMAL: The Boolean type cannot be converted to or from any
of the two data types.
● The Boolean type cannot be converted to or from the binary or datetime type.

Comparison Rules of the Boolean Type


● Comparison is performed mainly in the WHERE clause for condition
judgment. For example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 177


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SELECT * from TEST_TABLE WHERE c_bool = TRUE;


● In GaussDB 100, the general principle for Boolean comparison is to compare
the values (0 or 1). The specific rules are as follows:
– Comparison with reserved words: The system has two built-in Boolean
reserved words TRUE and FALSE, corresponding to values 1 and 0,
respectively. When Boolean variables are compared with reserved words,
they are compared by value.
– Comparison with strings: Before a Boolean value is compared with a
string, the string is converted to a Boolean variable according to the
string input rule in section 5.1. If the conversion fails, an error is reported.
– Comparison with the numeric type:

▪ Comparison with integers: Convert the Boolean type to integers 0


and 1, and then compare the values.

▪ Comparison with floating-point numbers and high-precision


DECIMAL types: The system does not support comparison and
reports an error.
– Comparison between the date or binary type is not supported.
[NOT] IN (expr_list) and [NOT] BETWEEN (expr) AND (expr): If
Boolean variables appear in one of these statements, convert the strings
in the IN and BETWEEN clause to Boolean values, and then compare the
values. If the conversion fails, an error is reported. If an integer exists, the
system compares the Boolean type with the integer based on the said
rule.

Arithmetic Operations of the Boolean Type


● The Boolean type does not support arithmetic operations or bit operations.
● The Boolean type supports the concatenation operation (operator: ||). Boolean
values are converted to strings according to the rules in Conversion Between
Boolean and Other Types and then concatenated.

3.4.6 Interval Data Types


A time interval refers to the difference between two time points, for example, how
many years and months do employees work from being hired to now, and how
many days, hours, minutes, and seconds have elapsed since the last transaction.
GaussDB 100 supports two INTERVAL data types: INTERVAL YEAR TO MONTH and
INTERVAL DAY TO SECOND, which can be abbreviated to YMINTERVAL and
DSINTERVAL, respectively.

INTERVAL YEAR TO MONTH


Syntax:
INTERVAL YEAR[(n)] TO MONTH

Purpose: Stores an interval in the unit of years and months.


Value range: [-9999-11, +9999-11]
● The value range of n is [0,4], which indicates the precision of the year. The
default value is 2.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 178


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The minimum value of INTERVAL YEAR TO MONTH is -9999-11, indicating


that the time difference is negative 9999 years and 11 months. Similarly, the
maximum value +9999-11 indicates that the time difference is 9999 years
and 11 months.

Occupied space: 4 bytes

Examples:

Specify the definition of an INTERVAL YEAR TO MONTH column.


ymitvl_col_name INTERVAL YEAR [(year_precision)] TO MONTH

● year_precision indicates the precision of the YEAR field, that is, the maximum
number of valid digits in the YEAR column.
● If year_precision is set to 2, the maximum value of the YEAR field is 99. If the
value specified by the user exceeds 99, an error is reported.
● The minimum value of year_precision is 0, and the maximum value is 4. The
default value is 2. If the input exceeds the specified precision, an error is
reported.

INTERVAL DAY TO SECOND


Syntax:
INTERVAL DAY[(n1)] TO SECOND [(n2)]

Purpose: Stores an interval in the unit of days, hours, minutes, seconds, and
microseconds.

Value range: [-9999999 23:59:59.999999,+9999999 23:59:59.999999]

● The value range of n1 is [0,7], which indicates the precision of the day. The
default value is 2.
● The value range of n2 is [0,6], which indicates the precision after the second.
If the value is not specified, the default value 6 is used.
● The minimum value of INTERVAL DAY TO SECOND is -9999999
23:59:59.999999, indicating that the time difference is negative 999999 days
23 hours 59 minutes 59.999999 seconds.

Occupied space: 8 bytes

Examples:

Specify the definition of an INTERVAL DAY TO SECOND column.


dsitvl_col_name INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]

● day_precision indicates the precision of the DAY field. Its effect is the same
as that of year_precision.
● The minimum value is 0, the maximum value is 7, and the default value is 2.
● fractional_seconds_precision indicates the precision after the decimal point
in the specified SECOND field. The minimum value is 0, the maximum value is
6, and the default value is 6.
● The decimal part of the SECOND field can exceed the specified precision.
However, the excessive part will be rounded off so that the result meets the
specified precision requirement.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 179


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

For example, if fractional_seconds_precision is set to 6, the value 1


12:12:12.666666666666 is truncated to 1 12:12:12.666667.

Comparison of INTERVAL Types


● Two INTERVAL values can be compared. An INTERVAL YEAR TO MONTH
cannot be compared with an INTERVAL DAY TO SECOND value.
● An INTERVAL value can be compared with strings and texts. Before
comparison, the string must be converted to the corresponding type. If the
conversion fails, an error is reported.
● An INTERVAL value cannot be compared with values of any other types.

Examples
CREATE TABLE PFA_dsitvl(id int, dsval interval day(7) to second);
INSERT INTO PFA_dsitvl VALUES(1, '1231 12:3:4.1234');insert into PFA_dsitvl values(2,
'P1231DT16H3.3333333S');
INSERT INTO PFA_dsitvl VALUES(3, 'PT12H');
INSERT INTO PFA_dsitvl VALUES(4, '-P99DT655M999.99999S');
INSERT INTO PFA_dsitvl VALUES(5, '-0 00:19:7.7777777777');
INSERT INTO PFA_dsitvl VALUES(6, '-1234 0:0:0.0004');

Do ORDER BY to the dsval column.


SELECT * FROM PFA_dsitvl ORDER BY dsval;

ID DSVAL
--------------------------------------
6 -0001234 00:00:00.000400
4 -0000099 11:11:39.999990
5 -0000000 00:19:07.777778
3 +0000000 12:00:00.000000
1 +0001231 12:03:04.123400
2 +0001231 16:00:03.333333
6 rows fetched.

Compare whether two dsval values are equivalent. In the following SQL
statement, the right operand used for comparison is a string. Before comparison,
the system converts the string to the INTERVAL DAY TO SECOND type.
SELECT * FROM PFA_dsitvl WHERE dsval = '0000 12:0000:0.000000';
ID DSVAL
--------------------------------------
3 +0000000 12:00:00.000000
1 rows fetched.

Compare dsval values. For example:


SELECT * FROM PFA_dsitvl WHERE dsval > 'P0000DT00000012H0000M0.0000S';

ID DSVAL
--------------------------------------
1 +0001231 12:03:04.123400
2 +0001231 16:00:03.333333
2 rows fetched.

Calculate the maximum and minimum values of dsval.


SELECT MIN(DSVAL), MAX(DSVAL) FROM PFA_dsitvl;

MIN(DSVAL) MAX(DSVAL)
----------------------------------------------------
-0001234 00:00:00.000400 +0001231 16:00:03.333333
1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 180


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Expressions of the INTERVAL Type


● Calculations between INTERVAL values
Addition and subtraction can be performed between INTERVAL values, but
cannot be performed between DSINTERVAL or YMINTERVAL values.
DSINTERVAL+DSINTERVAL=DSINTERVAL
YMINTERVAL+YMINTERVAL=YMINTERVAL
DSINTERVAL-DSINTERVAL=DSINTERVAL
YMINTERVAL-YMINTERVAL=YMINTERVAL
SELECT numtodsinterval(22, 'HOUR') + numtodsinterval(9999999, 'DAY') FROM SYS_DUMMY;
NUMTODSINTERVAL(22, 'HOUR') +
------------------------------
+9999999 22:00:00.000000
1 rows fetched.

SELECT numtoyminterval(24, 'month') - numtoyminterval(9, 'month') FROM SYS_DUMMY;

NUMTOYMINTERVAL(24, 'MONTH') - NUMTOYMINTERVAL(9, 'MONTH')


----------------------------------------------------------
+0001-03
1 rows fetched.
SELECT numtoyminterval(24, 'month') + numtoyminterval(9998, 'year') FROM SYS_DUMMY;
GS-00659, INTERVAL YEAR TO MONTH out of range
● Calculations between INTERVAL and numeric values
Multiplication can be performed between INTERVAL and numeric values,
indicating a multiple of the INTERVAL value. The operation result is of the
corresponding INTERVAL type.
DSINTERVAL*NUMERIC=DSINTERVAL
YMINTERVAL*NUMERIC=YMINTERVAL
NUMERIC*DSINTERVAL=DSINTERVAL
NUMERIC*YMINTERVAL=YMINTERVAL
DSINTERVAL/NUMERIC=DSINTERVAL
YMINTERVAL/NUMERIC=YMINTERVAL
SELECT NUMTODSINTERVAL(1, 'day') / 2::integer FROM SYS_DUMMY;
NUMTODSINTERVAL(1, 'DAY') / 2::INTEGER
----------------------------------------
+0000000 12:00:00.000000
1 rows fetched.

SELECT NUMTODSINTERVAL(1, 'day') / 1.33::real FROM SYS_DUMMY;


NUMTODSINTERVAL(1, 'DAY') / 1.33::REAL
--------------------------------------
+0000000 18:02:42.406015
1 rows fetched.

SELECT NUMTOYMINTERVAL(1, 'year') / 2::integer FROM SYS_DUMMY;


NUMTOYMINTERVAL(1, 'YEAR') / 2::INTEGER
----------------------------------------
+0000-06
1 rows fetched.
SELECT NUMTOYMINTERVAL(1, 'year') / 5::bigint FROM SYS_DUMMY;
NUMTOYMINTERVAL(1, 'YEAR') / 5::BIGINT
---------------------------------------
+0000-02
1 rows fetched.

SELECT NUMTODSINTERVAL(1, 'day') * 2::integer FROM SYS_DUMMY;


NUMTODSINTERVAL(1, 'DAY') * 2::INTEGER
--------------------------------------

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 181


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

+0000002 00:00:00.000000
1 rows fetched.

SELECT NUMTODSINTERVAL(1, 'day') * 1.33::number FROM SYS_DUMMY;

NUMTODSINTERVAL(1, 'DAY') * 1.33::NUMBER


-----------------------------------------
+0000001 07:55:12.000000
1 rows fetched.

SELECT 0.3 * NUMTODSINTERVAL(1, 'day') FROM SYS_DUMMY;

0.3 * NUMTODSINTERVAL(1, 'DAY')


-------------------------------
+0000000 07:12:00.000000
1 rows fetched.
● Calculation between DSINTERVAL and time values
Addition and subtraction can be performed between DSINTERVAL and time
values, indicating that a DSINTERVAL value is added or subtracted from the
current time. The DATETIME type can be DATE, TIMESTAMP, TIMESTAMP_TZ,
or TIMESTAMP_LTZ.
DSINTERVAL+DATETIME=DATETIME
DATETIME+DSINTERVAL=DATETIME
DATETIME-DSINTERVAL=DATETIME
SELECT NUMTODSINTERVAL(1, 'day') + TO_DATE('2016-02-29', 'YYYY-MM-DD') FROM SYS_DUMMY;

NUMTODSINTERVAL(1, 'DAY') + TO_DATE('2016-02-29', 'YYYY-MM-DD')


---------------------------------------------------------------
2016-03-01 00:00:00

1 rows fetched.

SELECT TO_DATE('2018-08-02', 'YYYY-MM-DD') + NUMTODSINTERVAL(10, 'day') FROM SYS_DUMMY;

TO_DATE('2018-08-02', 'YYYY-MM-DD') + NUMTODSINTERVAL(10, 'DAY')


----------------------------------------------------------------
2018-08-12 00:00:00

1 rows fetched.

SELECT TO_DATE('2019-06-29', 'YYYY-MM-DD') - NUMTODSINTERVAL(10, 'HOUR') FROM


SYS_DUMMY;

TO_DATE('2019-06-29', 'YYYY-MM-DD') - NUMTODSINTERVAL(10, 'HOUR')


----------------------------------------------------------------
2019-06-28 14:00:00

1 rows fetched.

● Calculation between YMINTERVAL and time values


Addition and subtraction can be performed between INTERVAL YEAR TO
MONTH and time values. The calculation rule is implemented on the YEAR
and MONTH fields of the time type.
YMINTERVAL+DATETIME=DATETIME
DATETIME+YMINTERVAL=DATETIME
DATETIME-YMINTERVAL=DATETIME
Note that if the value of the DAY field is incompatible with those of YEAR
and MONTH, an error is reported. For example, the following SQL statement
will report an error because the date after addition is 2018-09-31, but the
maximum number of days in September is 30.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 182


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SELECT TO_DATE('2018-08-31', 'YYYY-MM-DD') + NUMTOYMINTERVAL(1, 'month') FROM


SYS_DUMMY;

GS-00674, DATETIME with illegal month field

Similar situations may occur in a leap year. February 2016 has 29 days. After
one year is added, the result is 2017, which is not a leap year and has only 28
days in February. In this case, an error occurs.
SELECT TO_DATE('2016-02-29', 'YYYY-MM-DD') + TO_YMINTERVAL('P1Y') FROM SYS_DUMMY;

GS-00674, DATETIME with illegal month field

Another example:
SELECT TO_DATE('2018-01-31', 'YYYY-MM-DD') + NUMTOYMINTERVAL(1, 'year') FROM SYS_DUMMY;

TO_DATE('2018-01-31', 'YYYY-MM-DD') + NUMTOYMINTERVAL(1, 'YEAR')


------------------------------------------------------------------
2019-01-31 00:00:00
1 rows fetched.

● Subtraction between time values


Subtraction can be performed between time values. The subtraction result of
two DATE values is of the numeric type, and the subtraction result of a DATE
and a TIMESTAMP value is of the DSINTERVAL type.
DATETIME-TIMESTAMP=DSINTERVAL
TIMESTAMP-DATETIME=DSINTERVAL
DATE-DATE=DECIMAL
SELECT TO_CHAR(TO_DATE('9999-05-23 11', 'YYYY-MM-DD HH24') - TO_DATE('2018-01-01 00',
'YYYY-MM-DD HH24')) FROM SYS_DUMMY;
TO_CHAR(TO_DATE('9999-05-23 11
----------------------------------------------------
2915142.45833333333333333333333333333333
1 rows fetched.

SELECT TO_DATE('9999-05-23 11', 'YYYY-MM-DD HH24') - TO_TIMESTAMP('2018-01-01 00', 'YYYY-


MM-DD HH24') FROM SYS_DUMMY;

TO_DATE('9999-05-23 11', 'YYYY-MM-DD HH24') - TO_TIMESTAMP('2018


----------------------------------------------------------------
+2915142 11:00:00.000000
1 rows fetched.

SELECT * FROM SYS_DUMMYWHERE SYSTIMESTAMP - SYSTIMESTAMP < '0 0:0:30';


DUMMY
-----
X
1 rows fetched.

SELECT TO_TIMESTAMP('9999-05-23 11', 'YYYY-MM-DD HH24') - TO_TIMESTAMP('2018-01-01 00',


'YYYY-MM-DD HH24') FROM SYS_DUMMY;

TO_TIMESTAMP('9999-05-23 11',
------------------------------
+2915142 11:00:00.000000
1 rows fetched.

3.5 Functions
Functions encapsulate service logic to implement specific functionalities. After a
function is executed, the result is returned. Users can modify system functions in
GaussDB 100. However, after the modification, the meaning of the functions may
change, which results in disorder in system control.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 183


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.5.1 Numeric Functions


ABS
Syntax:
ABS(exp)

Purpose: Returns the absolute value of exp.


● The input parameter exp can be a numeric type or any non-numeric type that
can be implicitly converted to a numeric type.
● The return value type of the function is the same as that of the exp data type.
Note: exp must be an expression that can be converted to a numeric value. The
absolute value of exp (including the INT, BIGINT, REAL, NUMBER, and DECIMAL
types) is returned.
Example:
Return the absolute value of –100.
SELECT ABS(-100) AS "Absolute" from SYS_DUMMY;

Absolute
----------------------------------------
100

1 rows fetched.

ACOS
Syntax:
ACOS(n)

Purpose: Returns the arc cosine value of the expression n.


The input parameter n is an expression that can be converted into a numeric
value. The value range is [-1, 1]. The return type is NUMBER.
Example:
Return the arc cosine of -1.
SELECT ACOS(-1) AS "ACOS" from SYS_DUMMY;

ACOS
----------------------------------------
3.1415926535897932384626433832795028842

1 rows fetched.

ASIN
Syntax:
ASIN(n)

Purpose: Returns the arc sine value of the expression.


The input parameter n is an expression that can be converted into a numeric
value. The value range is [-1, 1]. The return type is NUMBER.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 184


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example:
Return the arc sine of 0.5.
SELECT ASIN(0.5) AS "ASIN" from SYS_DUMMY;

ASIN
----------------------------------------
.523598775598298873077107230546583814033

1 rows fetched.

BITAND
Syntax:
BITAND(exp1,exp2)

Purpose: Computes a bitwise AND operation on two numeric values.


The input parameter is an expression that can be converted to a numeric value.
The value range is [–9223372036854775808, 9223372036854775807].
Example:
Perform the AND operation on digit 7 (binary 111) and 1 (binary 001).
SELECT BITAND(7,1) AS "BITAND" FROM SYS_DUMMY;

BITAND
--------------------
1

1 rows fetched.

BITOR
Syntax:
BITOR(exp1,exp2)

Purpose: Computes a bitwise inclusive OR operation on two numeric values.


The input parameter is an expression that can be converted to a numeric value.
The value range is [–9223372036854775808, 9223372036854775807].
Example:
Return the result of a bitwise inclusive OR operation performed on 29 and 15.
SELECT BITOR(29,15) AS "BITOR" from SYS_DUMMY;

BITOR
--------------------
31

1 rows fetched.

BITXOR
Syntax:
BITXOR(exp1,exp2)

Purpose: Computes a bitwise exclusive OR operation on two numeric values.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 185


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The input parameter is an expression that can be converted to a numeric value.


The value range is [–9223372036854775808, 9223372036854775807].

Example:

Return the results of the bitwise exclusive OR operations performed on the


following three pairs of numeric values:

● Example 1:
SELECT BITXOR (1,1) AS "BITXOR" from SYS_DUMMY;

BITXOR
--------------------
0

1 rows fetched.

● Example 2
SELECT BITXOR (1,0)AS "BITXOR" from SYS_DUMMY;

BITXOR
--------------------
1

1 rows fetched.

● Example 3
SELECT BITXOR (11,3) AS "BITXOR" from SYS_DUMMY;

BITXOR
--------------------
8

1 rows fetched.

CEIL
Syntax:
CEIL(n)

Purpose: Returns the smallest integer greater than or equal to n.

The input parameter is an expression that can be converted to a numeric value.


The return type is INTEGER.

Example:

Return the smallest integer greater than or equal to 15.3.


SELECT CEIL(15.3) AS "CEIL" from SYS_DUMMY;

CEIL
----------------------------------------
16
1 rows fetched.

COS
Syntax:
COS(n)

Purpose: Returns the cosine value of the expression.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 186


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Input parameter: an expression that can be converted to a numeric value. The


return type is NUMBER.
Example:
Return a cosine (120).
SELECT COS(120 * 3.14159265359/180) AS "COS" from SYS_DUMMY;

COS
----------------------------------------
-.50000000000011937382925089877706420632

1 rows fetched.

EXP
Syntax:
EXP(n)

Purpose: Returns the nth power of e (the base number of the natural logarithm).
● The return type is NUMBER.
● The input parameter n is a numeric data type or any non-numeric data type
that can be implicitly converted into a numeric data type.
Example:
Return the value for the third power of e.
SELECT EXP(3);

EXP(3)
----------------------------------------
20.085536923187667740928529654581717897

FLOOR
Syntax:
FLOOR(exp)

Purpose: Calculates the largest integer equal to or less than exp.


The input parameter is an expression that can be converted to a numeric value.
The return type is NUMBER.
Example:
Return the largest integer equal to or less than 12.8.
SELECT FLOOR(12.8) AS "FLOOR" from SYS_DUMMY;

FLOOR
----------------------------------------
12

1 rows fetched.

INET_NTOA
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 187


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

INET_NTOA(exp)

Purpose: Converts a numeric value to an IP address.

The input parameter is a numeric expression.

Example:

Convert 4294967295 to an IP address.


SELECT INET_NTOA(4294967295) FROM SYS_DUMMY;

INET_NTOA(4294967295)
---------------------
255.255.255.255

1 rows fetched.

LN
Syntax:
LN(exp)

Purpose: Returns the natural logarithm of exp. e is the base number.

The input parameter is an expression that can be converted to a NUMBER value.


The return type is NUMBER.

Note: The exp parameter can be set only to a NUMBER value greater than 0.

Example:

Return the natural logarithm of 70.


SELECT LN(70) AS "LN" from SYS_DUMMY;

LN
----------------------------------------
4.24849524204935898912334419812754393724

1 rows fetched.

LOG
Syntax:
log(exp1[,exp2])

Purpose: Returns the logarithm, base exp2, of exp1.

The input parameter is an expression that can be converted to a NUMBER value.


The return type is NUMBER.

Note:

● Currently, exp1 and exp2 support only the NUMBER type.


● If exp2 is not transferred, the default value e is used, that is,
log(exp1)=ln(exp1).

Example:

Return the logarithm of 81, with 3 as the bottom.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 188


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SELECT LOG(3,81) AS "LOG" from SYS_DUMMY;

LOG
----------------------------------------
4

1 rows fetched.

MOD
Syntax:
MOD(exp1,exp2)

Purpose: Returns the remainder of exp1 divided by exp2.


Input parameter: an expression that can be converted to a NUMBER value. The
return type is NUMBER.
Example:
Return the remainder of 29 divided by 3.
SELECT MOD(29,3) AS "MOD" from SYS_DUMMY;

MOD
----------------------------------------
2

1 rows fetched.

POWER
Syntax:
POWER(base,expn)

Purpose: Returns number raised to the power power.


The input parameter is base as the base number and expn as the exponent. The
return type is NUMBER.
Note:
● If the value of expn is a decimal, radication will be performed.
● If the value of base is less than 0 and that of expn is a decimal, the POWER
function will return an error indicating that the values are beyond the
supported range.
Example:
Return the value for the third power of 5.
SELECT POWER(5,3) AS "POWER" from SYS_DUMMY;

POWER
----------------------------------------
125

1 rows fetched.

RAWTOHEX
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 189


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

RAWTOHEX(exp)

Purpose: Converts exp of the RAW class to a hexadecimal string.


The input parameter is a RAW class value. The return value is a string.
Example:
Convert '0123456789abcdef' to a hexadecimal string.
SELECT RAWTOHEX ('0123456789abcdef') FROM SYS_DUMMY;
RAWTOHEX('0123456789ABCDEF')
-----------------------------------
30313233343536373839616263646566

1 rows fetched.

ROUND
Syntax:
ROUND (number[, decimals])

Purpose: Truncates number forward or after the decimal point as required by


decimals and returns the value.
● The input parameter number is a number.
● decimals specifies the number of digits after the decimal point. This
parameter is optional. If it is ignored, all decimal parts are truncated and
rounded off. The value ranges from -2147483648 to 2147483647.
● If decimals is negative, it indicates the number of digits from the left of the
decimal point to be truncated. In this case, the corresponding integer number
is filled with 0 and rounded off, and the decimals are removed.
Example:
● Truncate 1234.5678 backward by 1.
SELECT ROUND(1234.5678, 1) FROM SYS_DUMMY;
ROUND(1234.5678, 1)
----------------------------------------
1234.6

1 rows fetched.

● Truncate all decimal parts of 1234.5678.


SELECT ROUND(1234.5678) FROM SYS_DUMMY;
ROUND(1234.5678)
----------------------------------------
1235

1 rows fetched.

● Truncate 1234.5678 forward by 1.


SELECT ROUND(1234.5678, -1) FROM SYS_DUMMY;
ROUND(1234.5678, -1)
----------------------------------------
1230

1 rows fetched.

SIGN
Syntax:
SIGN (exp)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 190


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Obtains the signal of the exp result. If the value is greater than 0, 1 is
returned. If the value is less than 0, -1 is returned. If the value is 0, 0 is returned.
The input parameter exp is a numeric value.
Example:
Obtain the signal of 5-6.
SELECT SIGN(5-6) FROM SYS_DUMMY;

SIGN(5-6)
----------------------------------------
-1

1 rows fetched.

SIN
Syntax:
SIN(n)

Purpose: Returns the sine value of the expression.


Input parameter: an expression that can be converted to a numeric value. The
return type is NUMBER.
Example:
Return the sine of 45 degrees.
SELECT SIN(45 * 3.14159265359/180) AS "SIN" from SYS_DUMMY;

SIN
----------------------------------------
.707106781186584075022132715997995378626

1 rows fetched.

SQRT
Syntax:
SQRT(n)

Purpose: Returns the square root of a non-negative real number.


Input parameter: an expression that can be converted to a non-negative numeric
value. The return type is DECIMAL.
Example:
Return the square root of 49.
SELECT SQRT(49) AS "SQRT" from SYS_DUMMY;

SQRT
----------------------------------------
7

1 rows fetched.

TRUNC
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 191


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

TRUNC(number,scale)

Purpose: Truncates the entered value in the specified format.


Input parameter: number as the data to be truncated and scale as the truncation
precision. The return type is NUMBER.
Example:
Truncate the following numbers:
SELECT TRUNC(15.79,1) AS "TRUNC" from SYS_DUMMY;

TRUNC
----------------------------------------
15.7

1 rows fetched.
SELECT TRUNC(15.79,-1)AS "TRUNC" from SYS_DUMMY;

TRUNC
----------------------------------------
10

1 rows fetched.

3.5.2 Character Processing Functions

● Expressions that can be converted to STRING values are those whose results are of the
numeric, date, Boolean, BINARY, CHAR, VARCHAR, or VARCHAR2 type.
● Expressions that can be converted to INT values are those whose results are of the
numeric, Boolean, BINARY, CHAR, VARCHAR, or VARCHAR2 type.
● The function supports CLOB and BLOB data. A maximum of 65534 bytes are supported
(Data length of the CLOB and BLOB types is not restricted by the LENGTH and
LENGTHB functions.).

CONCAT
Syntax:
CONCAT(str[,...])

Purpose: Concatenates strings. It can be used to concatenate the data obtained


from different fields and output them together.
● This function can be used to concatenate one or more strings. Multiple strings
are separated by commas (,). The return value is the string generated by
combining parameters.
● If a parameter is NULL, the CONCAT function ignores this parameter.
However, if NULL is enclosed in single quotes, the CONCAT function will
process NULL as a string. This function can be nested.
● The input parameter is a string or an expression that can be converted to a
string. The return value is a string.
Note: The return value supports a maximum of 8000 bytes. If the value exceeds
8000 bytes, an error is reported.
Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 192


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Concatenate three strings. If one parameter is NULL, it is ignored.


SELECT CONCAT('11',NULL,'22');

CONCAT('11',NULL,'22')
----------------------
1122

1 rows fetched.
● Concatenate three strings. If one string is NULL, it is ignored.
SELECT CONCAT('11','NULL','22');

CONCAT('11','NULL','22')
------------------------
11NULL22

1 rows fetched.

CONCAT_WS
Syntax:
CONCAT_WS(separator, str1, str2,...)

Purpose: Concatenates one or more strings, which are separated by commas (,).
The return value is the concatenation of each parameter value.
● If a parameter is NULL, the CONCAT_WS function ignores this parameter.
However, if NULL is enclosed in single quotes, the CONCAT_WS function will
process NULL as a string.
● This function can be nested.
● The input parameter is a string or an expression that can be converted to a
string. The return value is a string.
Note: The return value supports a maximum of 8000 bytes. If the value exceeds
8000 bytes, an error is reported.
Example:
Concatenate three strings. If one parameter is NULL, it is ignored.
SELECT CONCAT_WS('-','11',NULL,'22');

CONCAT_WS('-','11',NULL,'22')
------------------------------
11-22

1 rows fetched.

DBMS_LOB.SUBSTR
Syntax:
DBMS_LOB.SUBSTR(str[,len[,start]])

Purpose: Truncates a string. This function is used to truncate and return the
substring of len bytes starting from |start| in str.
● The start parameter indicates the index position. The value is a positive
integer, indicating the position of the |start| byte from left to right.
● len indicates the number of bytes truncated from the index position to the
right. When len is less than or equal to 0, the return value of the
DBMS_LOB.SUBSTR function is empty.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 193


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The input parameter str must be an expression that can be converted to a


STRING value. The start and len parameters must be expressions that can be
converted to INT values. The return type is STRING.
Example:
Truncate and return four bytes starting from the first byte.
select DBMS_LOB.SUBSTR('123456',4,1) FROM SYS_DUMMY;
DBMS_LOB.SUBSTR('123456',4,1)
---------------------------
1234

1 rows fetched.

FIND_IN_SET
Syntax:
FIND_IN_SET(sub,src)

Purpose: Returns the index position of sub in src.


● sub is an element string, and src is a set string. Elements are separated by
commas (,).
● The input parameter is an expression that can be converted to a string. The
return type is INTEGER.
● If the element string fails to be found in the collection string, 0 is returned.
Otherwise, the element position (starting from 1) is returned.
● A space is regarded as an element string.
Note:
Currently, the CLOB and BLOB data types cannot be processed.
Example:
Return the index position of string b in the string a,b,c,d.
SELECT FIND_IN_SET('b','a,b,c,d');

FIND_IN_SET('B','A,B,C,D')
--------------------------
2

1 rows fetched.

HEX
Syntax:
HEX(p1)

Purpose: Returns the hexadecimal string of a value.


The input parameter p1 can be a numeric or STRING value. The return type is
String.
Example:
Return the hexadecimal strings of the abc string and the number 255.
SELECT HEX('abc'), HEX(255) FROM SYS_DUMMY;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 194


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

HEX('ABC') HEX(255)
---------- --------
616263 FF

1 rows fetched.

HEX2BIN
Syntax:
HEX2BIN(str)

Purpose: Returns the byte string represented by a hexadecimal string.

The return type is BINARY.

Note: The entered hexadecimal string must be prefixed with 0x.

Example:

Return the byte string represented by the hexadecimal string 0x39.


SELECT HEX2BIN('0x39') FROM SYS_DUMMY;

HEX2BIN('0X39')
----------------------------------------------------------------
9

1 rows fetched.

HEXTORAW
Syntax:
HEXTORAW(str)

Purpose: Returns the byte string represented by a hexadecimal string.

The return type is RAW.

Example:

Return the byte string represented by the hexadecimal string abcdef.


SELECT HEXTORAW('abcdef') FROM SYS_DUMMY;

HEXTORAW('ABCDEF')
----------------------------------------------------------------
ABCDEF

1 rows fetched.

INSERT
Syntax:
INSERT(str,pos,len,newstr)

Purpose: Returns the string str and replaces the string starting from the pos
position with length of len with newstr.

● If pos is not within the length of the string str, the original string is returned.
● If the value of len is greater than the lengths of the other string starting from
pos, replace all starting from pos with newstr.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 195


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The input parameters str and newstr are expressions that can be converted
to STRING values. The input parameters pos and len are expressions that can
be converted to INTEGER values. The return type is STRING.
Note:
This function processes characters. The return value supports a maximum of 8000
bytes.
Example:
● Return the string Quadratic and replace the four characters starting from the
third character with the new string What.
SELECT INSERT('Quadratic', 3, 4, 'What');

INSERT('QUADRATIC', 3, 4, 'WHAT')
---------------------------------
QuWhattic

1 rows fetched.
● Return the string Quadratic and replace the four characters starting from the
tenth character with the new string What. In this example, the start position
pos is not within the length of the string Quadratic, so the original string is
returned.
SELECT INSERT('Quadratic', 10, 4, 'What');

INSERT('QUADRATIC', 10, 4, 'WHAT')


----------------------------------
Quadratic

1 rows fetched.
● Return the string Quadratic and replace the 100 characters starting from the
third character with the new string What. In this example, the value of the
parameter len is greater than the length of the remaining string following the
start position pos. Therefore, all characters following the start position pos
are replaced with the string newstr.
SELECT INSERT('Quadratic', 3, 100, 'What');

INSERT('QUADRATIC', 3, 100, 'WHAT')


-----------------------------------
QuWhat

1 rows fetched.

INSTR
Syntax:
INSTR(str1,str2[,pos[,n]])

Purpose: Searches for a string. This function returns the position of the string to
be searched for in the source string and computes the position by character.
● str1 is the source string. str2 is the string to be searched for. pos is the index
position, indicating the starting position in str1 for searching for str2. pos is
optional and the value is an integer that is not 0. If this parameter is omitted,
the default value is 1. n indicates the number of times that str2 occurs and is
optional. The value is a positive integer. If the parameter is omitted, the
default value is 1.
● In the source string str1, the INSTR function searches for the string str2 from
the |pos| position according to the sequence from left to right (pos is a

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 196


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

positive integer) or from right to left (pos is a negative integer). When str2
occurs for the nth time, the system returns the position of the first character
of str2 in the source string str1. If no str2 is found for the nth time of its
occurrence, the system returns 0. Regardless of whether the search sequence
is from left to right or from right to left, the position of the string to be
searched for in the source string is calculated from left to right.
● The input parameters str1 and str2 are expressions that can be converted to
STRING values. The input parameters pos and n are expressions that can be
converted to INT values. The return type is INT.

Example:

● Search a string gaussdb for a string au from the first character from left to
right to determine the first occurrence of au.
SELECT INSTR('gaussdb','au', 1, 1) POSITION FROM SYS_DUMMY;

POSITION
------------
2

1 rows fetched.

● Search a string gaussdb for a string db from the last character to determine
the first occurrence of db from right to left.
SELECT INSTR('gaussdb','db', -1, 1) POSITION FROM SYS_DUMMY;

POSITION
------------
6

1 rows fetched.

INSTRB
Syntax:
INSTRB(str1,str2[,pos[,n]])

Purpose: Searches for a string. This function returns the position of the string to
be searched for in the source string and computes the position by byte.

● str1 is the source string, in which the target string is searched for.
● str2 is the string to be searched for in str1.
● The input parameters str1 and str2 are expressions that can be converted to
STRING values. The input parameters pos and n are expressions that can be
converted to INT values. The return type is INT.
● pos is the index position, indicating the starting position in str1 for searching
for str2. pos is optional and the value is an integer that is not 0. If this
parameter is omitted, the default value is 1.
● n indicates the number of times that str2 occurs and is optional. The value is
a positive integer. If the parameter is omitted, the default value is 1.

Note:

● In the source string str1, the INSTRB function searches for the string str2
from the |pos| position according to the sequence from left to right (pos is a
positive integer) or from right to left (pos is a negative integer). When str2
occurs for the nth time, the system returns the position of the first character

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 197


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

of str2 in the source string str1. If no str2 is found for the nth time of its
occurrence, the system returns 0.
● Regardless of whether the search sequence is from left to right or from right
to left, the position of the string to be searched for in the source string is
calculated from left to right.
Example:
● Search for the position of or starting from the third byte in oracleor from left
to right when or occurs for the first time. The first search specifies n, and the
second search does not.
SELECT INSTRB('oracleor','or', 3, 1) POSITION_WITH_n, INSTRB('oracleor','or', 3)
POSITION_WITHOUT_n FROM SYS_DUMMY;

POSITION_WITH_N POSITION_WITHOUT_N
--------------- ------------------
7 7

1 rows fetched.

● Search for the position of the 我A string when it occurs for the first time
following the first byte in the A string from left ro right by byte and character.
SELECT INSTRB('我A','A',1,1)AS BYTE_POSITION,INSTR('我A','A',1,1) AS WORD_POSITION FROM
SYS_DUMMY;

BYTE_POSITION WORD_POSITION
------------- -------------
4 2

1 rows fetched.

INET_ATON
Syntax:
INET_ATON(str)

Purpose: Converts an IP address to a numeric value.


The input parameter is a string in dotted decimal notation.
Example:
Convert 192.168.1.1 to a numeric value.
SELECT INET_ATON('192.168.1.1') FROM SYS_DUMMY;

INET_ATON('192.168.1.1')
------------------------
3232235777

1 rows fetched.

LEFT
Syntax:
LEFT(str,length)

Purpose: Returns a certain number of characters from the left of a given string.
● str is a string from which substrings are extracted. Strings of the CLOB type
are not supported.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 198


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● length is a positive integer that specifies the number of characters returned


from the left.
Note:
● If length is 0 or negative, the LEFT function returns an empty string.
● If length is greater than the length of str, the LEFT function returns the entire
str string.
● Currently, the client supports a string of up to 32767 bytes. Therefore, the
function returns a maximum of 32767 bytes.
Example:
Return the three characters from the left of the abcdefg string.
select left('abcdefg', 3) from SYS_DUMMY;

LEFT('ABCDEFG', 3)
------------------
abc

1 rows fetched.

LENGTH
Syntax:
LENGTH(str)

Purpose: Obtains the length of a string. This function returns the number of str.
The input parameter is an expression that can be converted to a STRING value.
The return type is INT.
Note: If the input parameter is of the UTF-8 type and the error "Nls internal error,
invalid utf-8 buffer" is reported, use the LENGTHB function.
Example:
Determine the character length of the 我的成绩是90分 string.
SELECT LENGTH('my score is 90') AS BYTE_LENGTH FROM SYS_DUMMY;

BYTE_LENGTH
------------
14

1 rows fetched.

LENGTHB
Syntax:
LENGTHB(str)

Purpose: Obtains the length of a string. This function returns the number of bytes
of str.
The input parameter is an expression that can be converted to a STRING value.
The return type is INT.
Note: If the input parameter is of the CHAR type, this function equals the LENGTH
function.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 199


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example:

Determine the byte length of the 我的成绩是90分 string.


SELECT LENGTHB('我的成绩是90分') AS WORD_LENGTH FROM SYS_DUMMY;

WORD_LENGTH
------------
20

1 rows fetched.

LOCATE
Syntax:
LOCATE(substr,str[,pos])

Purpose: Returns the position of the substr substring upon its first occurrence in
the str string. The start position is pos. When the pos parameter is omitted, the
start position is the first character. If substr is not in str after the start position
pos, 0 is returned.

The input parameters substr and str are expressions that can be converted to
STRING values. The input parameter pos is an expression that can be converted to
an INTEGER value. The return type is INTEGER.

Note:

This function processes characters.

Example:

● Return the position of the bar substring upon its first occurrence in the
foobarbar string. The start position is the fifth character.
SELECT LOCATE('bar', 'foobarbar', 5);

LOCATE('BAR', 'FOOBARBAR', 5)
-----------------------------
7

1 rows fetched.

● If xbar is not in foobar, 0 is returned.


SELECT LOCATE('xbar', 'foobar');

LOCATE('XBAR', 'FOOBAR')
------------------------
0

1 rows fetched.

LOWER
Syntax:
LOWER(str)

Purpose: Converts a string to lowercase. Global languages are supported.

The input parameter is an expression that can be converted to a STRING value.


The return type is STRING.

Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 200


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Convert all characters in the Greek string "Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ


Σ Τ Υ Φ Χ Ψ Ω" to lowercase.
select lower('Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω ') lower;
LOWER
----------------------------------------------------------------
αβγδεζηθικλμνξοπρστυφχψω
1 rows fetched.

● Convert all the characters in the string ABCDEFG to lowercase.


SELECT LOWER('ABCDEFG') "Lower" FROM SYS_DUMMY;

Lower
------------------
abcdefg

1 rows fetched.

LPAD
Syntax:
LPAD(str,pad_len[,pad_str])

Purpose: Returns an expression, left-padded to a specified length with the


specified characters. This function can be used to format the output of a query.
● The input parameter str indicates a source string, the string to be padded. It is
an expression that can be converted to a STRING value.
● The input parameter pad_len indicates the length of a returned string, that is,
the length of the string after padding. If the value of pad_len is less than or
equal to the length of str, str will be truncated from left to right to leave
pad_len bytes.
● The input parameter pad_str indicates a string for padding. If this parameter
is not specified, the value will be null characters. The return type is STRING.
Note:
The return value supports a maximum of 8000 bytes.
Example:
Print the employee IDs and employee names and pad 20 characters to the left of
the employee names.
--Delete the employee_2017 table.
DROP TABLE IF EXISTS employee_2017;

--Create the employee_2017 table.


CREATE TABLE employee_2017(employee_id INT NOT NULL,first_name VARCHAR(10),last_name
VARCHAR(10), hire_date DATETIME);
-- Insert record 1.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(1001,'Alice','BROWN','2017-06-20 12:00:00');
-- Insert record 2.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(102,'BOB','Smith','2017-10-20 12:00:00');
-- Insert record 3.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(13,'ALAN','Jones','2017-05-10 12:00:00');
-- Commit the transaction.
COMMIT;
-- Pad 20 characters to the left of the employee names.
SELECT employee_id, LPAD (last_name, 20, '.') LAST_NAME FROM employee_2017 ORDER BY last_name;

EMPLOYEE_ID LAST_NAME

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 201


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

------------ ----------------------------------------------------------------
1001 ...............BROWN
13 ...............Jones
102 ...............Smith

3 rows fetched.

LTRIM(str)
Syntax:
LTRIM(str[,set])

Purpose: Deletes spaces or other predefined characters on the left of a string. This
function can be used to format the output of a query.
● This function deletes all characters in set from the left of str. If set is not
specified, spaces are deleted by default.
● If str is a character data, it must be enclosed in single quotation marks. The
LTRIM function checks whether the leftmost character of str is contained in
set. If the leftmost character of str is contained in set, the function deletes
the character until the leftmost character of str is not included in set.
● The input parameter is an expression that can be converted to a STRING
value. The return type is STRING.
Note:
Currently, the CLOB and BLOB data cannot be processed.
Example:
● Delete the less than sign (<), greater than sign (>), and equal to sign (=) from
the leftmost of the <=====>GAUSSDB <=====> string.
SELECT LTRIM('<=====>GAUSSDB <=====>', '<>=') "LTRIM Example" FROM SYS_DUMMY;

LTRIM Example
------------------
GAUSSDB <=====>

1 rows fetched.

● If set is not specified, spaces are deleted from the leftmost part of the
GAUSSDB string.
SELECT LTRIM(' GAUSSDB') "LTRIM Example" FROM SYS_DUMMY;

LTRIM Example
-------------
GAUSSDB

1 rows fetched.

● Delete the L and M letters from the leftmost of the GAUSSDB string.
SELECT LTRIM('GAUSSDB', 'GA') "LTRIM Example" FROM SYS_DUMMY;

LTRIM Example
---------------
USSDB

1 rows fetched.

REGEXP_INSTR
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 202


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

REGEXP_INSTR(str,pattern[,position[,occurrence[,return_opt[,match_param[,subexpr]]]]])

Purpose: Returns the start or end position of the string that complies with the
regular expression.
● The input parameter str is a string that requires regular processing. It
supports the STRING and NUMBER types.
● The input parameter pattern is the regular expression for matching.
● The input parameter position indicates the start position of the string where
the matching will start. The default value is 1.
● The input parameter occurrence indicates the sequence time of the
occurrence of the group matching the regular expression. The default value is
1.
● The input parameter return_opt indicates the return mode, in which 0
indicates the start position is returned, and 1 indicates the end position is
returned.
● The input parameter match_param indicates the search mode (i indicates
case-insensitive search, and c indicates case-sensitive search. The default
value is c).
● The input parameter subexpr indicates that for pattern with subexpressions,
the function returns the string matching the subexprth subexpression (the
default value is 0).
● The return type is INTEGER.
Note: Currently, the CLOB and BLOB data cannot be processed.
Example 1:
Return the start position of the string complying with the regular expression [^,]+
in the 17,20,23 string. The start position is the first character, and the group
appears for the third time. The search is case-insensitive.
SELECT REGEXP_INSTR('17,20,23','[^,]+',1,3,0,'i') AS STR FROM SYS_DUMMY;

STR
---
7

1 rows fetched.

Example 2:
Return the end position of the string complying with the regular expression [^,]+
in the 17,20,23 string. The start position is the first character, and the group
appears for the third time. The search is case-insensitive.
SELECT REGEXP_INSTR('17,20,23','[^,]+',1,3,1,'i') AS STR FROM SYS_DUMMY;

STR
---
9

1 rows fetched.

REGEXP_SUBSTR
Syntax:
REGEXP_SUBSTR(str,pattern[,position[,occurrence[,match_param[,subexpr]]]])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 203


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Returns a string that complies with the regular expression.


● The input parameter str is a string that requires regular processing. It
supports the STRING and NUMBER types.
● The input parameter pattern is the regular expression for matching.
● The input parameter position indicates the start position of the string where
the matching will start. The default value is 1.
● The input parameter occurrence indicates the sequence time of the
occurrence of the group matching the regular expression. The default value is
1.
● The input parameter match_param indicates the search mode (i indicates
case-insensitive search, and c indicates case-sensitive search. The default
value is c).
● The input parameter subexpr indicates that for pattern with subexpressions,
the function returns the string matching the subexprth subexpression (the
default value is 0).
● The return type is STRING.
Note:
Currently, the CLOB and BLOB data types cannot be processed.
Example:
Return the string complying with the regular expression [^,]+ in the 17,20,23
string. The start position is the first character, and the group appears for the third
time. The search is case-insensitive.
SELECT REGEXP_SUBSTR('17,20,23','[^,]+',1,3,'i') AS STR FROM SYS_DUMMY;

STR
---
23

1 rows fetched.

REPLACE
Syntax:
REPLACE(str,src,dst)

Purpose: Replaces the src substring in the str string with the dst substring.
The input parameter str indicates the original string; src indicates the string to be
replaced, and dst indicates string to be replaced with. The return type is STRING.
Note:
● Currently, the CLOB and BLOB data cannot be processed.
● The returned value supports a maximum of 8000 bytes. If the value exceeds
8000 bytes, an error is reported.
Example:
Replace sg in the fgsgswsgs string with eeerrrttt.
SELECT REPLACE('fgsgswsgs', 'sg' ,'eeerrrttt') FROM SYS_DUMMY;

REPLACE('FGSGSWSGS', 'SG' ,'EEERRRTTT')

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 204


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

---------------------------------------
fgeeerrrtttsweeerrrttts

1 rows fetched.

REVERSE
Syntax:
REVERSE(str)

Purpose: Returns a string in a reverse order.


Only the STRING type is supported.
Example:
Return the ABCD string in a reverse order.
SELECT REVERSE('ABCD') AS STR FROM SYS_DUMMY;

STR
---
DCBA

1 rows fetched.

RIGHT
Syntax:
RIGHT(str,length)

Purpose: Returns a certain number of characters from the right of a given string.
● str is a string from which substrings are extracted. Strings of the CLOB type
are not supported.
● length is a positive integer that specifies the number of characters returned
from the right.
Note:
● If length is 0 or negative, the RIGHT function returns an empty string.
● If length is greater than the length of str, the RIGHT function returns the
entire str string.
● Currently, the client supports a string of up to 32767 bytes. Therefore, the
function returns a maximum of 32767 bytes.
Example:
Return the three characters from the right of the abcdefg string.
select right('abcdefg', 3) from SYS_DUMMY;

RIGHT('ABCDEFG', 3)
-------------------
efg

1 rows fetched.

RPAD
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 205


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

RPAD(str,pad_len[,pad_str])

Purpose: Returns an expression, right-padded to a specified length with the


specified characters. This function can be used to format the output of a query.
● The input parameter str indicates a source string, the string to be padded. It is
an expression that can be converted to a STRING value.
● The input parameter pad_len indicates the length of a returned string, that is,
the length of the string after padding. If the value of pad_len is less than or
equal to the length of str, str will be truncated from left to right to leave
pad_len bytes.
● The input parameter pad_str indicates a string for padding. If this parameter
is not specified, the value will be null characters.
● The return type is STRING.
Note:
The return value supports a maximum of 8000 bytes.
Example:
Concatenate first_name and last_name and pad the result with spaces until it is
12 characters long.
--Delete the employee_2017 table.
DROP TABLE IF EXISTS employee_2017;

--Create the employee_2017 table.


CREATE TABLE employee_2017(employee_id INT NOT NULL,first_name VARCHAR(10),last_name
VARCHAR(10), hire_date DATETIME);
--Insert record 1.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(1001,'Alice','BROWN','2017-06-20 12:00:00');
--Insert record 2.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(102,'BOB','Smith','2017-10-20 12:00:00');
--Insert record 3.
INSERT INTO employee_2017(employee_id,first_name,last_name,hire_date)
VALUES(13,'ALAN','Jones','2017-05-10 12:00:00');
-- Commit the transaction.
COMMIT;
-- Concatenate first_name and last_name and pad the result with spaces until it is 12 characters long.
SELECT CONCAT(RPAD (first_name,12), RPAD (last_name,12)) FROM employee_2017 ORDER BY
first_name, last_name;

CONCAT(RPAD (FIRST_NAME,12), RPAD (LAST_NAME,12))


----------------------------------------------------------------
ALAN Jones
Alice BROWN
BOB Smith

3 rows fetched.

RTRIM
Syntax:
RTRIM(str[,set])

Purpose: Deletes spaces or other predefined characters on the right of a string.


This function can be used to format the output of a query.
● This function deletes all characters in set from the right of str. If set is not
specified, spaces are deleted by default.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 206


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● If str is a character data, it must be enclosed in single quotation marks. The


RTRIM function checks whether the rightmost character of str is contained in
set. If the rightmost character of str is contained in set, the function deletes
the character until the rightmost character of str is not included in set.
● The input parameter is an expression that can be converted to a STRING
value. The return type is STRING.
Note:
Currently, the CLOB and BLOB data cannot be processed.
Example:
● Delete the less than sign (<), greater than sign (>), and equal to sign (=) from
the rightmost of the <=====>GAUSSDB<=====> string.
SELECT RTRIM('<=====>GAUSSDB<=====>', '<>=') "RTRIM Example" FROM SYS_DUMMY;

RTRIM Example
---------------
<=====>GAUSSDB

1 rows fetched.
● If set is not specified, spaces are deleted from the rightmost part of the
GAUSSDB string.
SELECT RTRIM(' GAUSSDB ') "RTRIM Example" FROM SYS_DUMMY;

RTRIM Example
-------------
GAUSSDB

1 rows fetched.
● Delete the D and B letters from the rightmost of the GAUSSDB string.
SELECT RTRIM('GAUSSDB', 'DB') "RTRIM Example" FROM SYS_DUMMY;

RTRIM Example
---------------
GAUSS

1 rows fetched.

SPACE
Syntax:
SPACE(n)

Purpose: Generates n spaces. The value range of n is [0, 4000].


Examples:
Insert a space between strings.
SELECT CONCAT('total number:',SPACE(1),'59');

CONCAT('TOTAL NUMBER:',SPACE(1),'59')
----------------------------------------------------------------
total number: 59

1 rows fetched.

SUBSTR
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 207


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SUBSTR(str, start[,len])
SUBSTR(str FROM start [FOR len])

Purpose: Truncates a string. This function is used to truncate and return the
substring of len characters starting from |start| in str.

● The start parameter indicates the index position. The value is positive,
indicating the position of the |start| character from left to right. The value is
negative indicating the position of the |start| character from right to left.
● When start is 0, the index position is the first character from left to right.
● len indicates the number of characters truncated from the index position to
the right. When len is less than or equal to 0, the return value of the SUBSTR
function is empty. len is an optional parameter. If this parameter is omitted,
all characters starting from the index position to the end of str are returned.
● The input parameter str must be an expression that can be converted to a
STRING value. The start and len parameters must be expressions that can be
converted to INT values.
● The return type is STRING.

Example:

● Truncate a string of 6 characters starting from the fifth character from left to
right.
SELECT SUBSTR('Quadratically',5,6) EXMAPLE1, SUBSTR('Quadratically' FROM 5 FOR 6) EXAMPLE2
FROM SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------
ratica ratica

1 rows fetched.

● Truncate a string of 0 characters from left to right starting from the fifth
character. The return value is empty.
SELECT SUBSTR('Quadratically',5,0) EXMAPLE1, SUBSTR('Quadratically' FROM 5 FOR 0) EXAMPLE2
FROM SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------

1 rows fetched.

● Truncates a string from right to left starting from the fifth character. len is
omitted. All characters starting from the index position to the end of str are
returned.
SELECT SUBSTR('Quadratically',-5) EXMAPLE1, SUBSTR('Quadratically' FROM -5) EXAMPLE2 FROM
SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------
cally cally

1 rows fetched.

SUBSTRB
Syntax:
SUBSTRB(str, start[,len])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 208


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Truncates a string. This function is used to truncate and return the
substring of len bytes starting from |start| in str.
● The start parameter indicates the index position. The value is positive,
indicating the position of the |start| byte from left to right. The value is
negative indicating the position of the |start| byte from right to left.
● When start is 0, the index position is the first byte from left to right.
● len indicates the number of bytes truncated from the index position to the
right. When len is less than or equal to 0, the return value of the SUBSTR
function is empty. len is an optional parameter. If this parameter is omitted,
all bytes starting from the index position to the end of str are returned.
● The input parameter str must be an expression that can be converted to a
STRING value. The start and len parameters must be expressions that can be
converted to INT values. The return type is STRING.
Example:
● Truncate a string of 6 bytes starting from the fifth byte from left to right.
SELECT SUBSTRB('Quadratically',5,6) EXMAPLE FROM SYS_DUMMY;

EXMAPLE
--------
ratica

1 rows fetched.

● Truncate a string of 0 bytes from left to right starting from the fifth byte. The
return value is empty.
SELECT SUBSTRB('Quadratically',5,0) EXMAPLE FROM SYS_DUMMY;

EXMAPLE
-------

1 rows fetched.

● Truncates a string from right to left starting from the fifth byte. len is
omitted. All bytes starting from the index position to the end of str are
returned.
SELECT SUBSTRB('Quadratically',-5) EXMAPLE FROM SYS_DUMMY;

EXMAPLE
-------
cally

1 rows fetched.

SUBSTRING
Syntax:
SUBSTRING(str, start[,len])
SUBSTRING(str FROM start [FOR len])

Purpose: Truncates a string. SUBSTRING has the same function as SUBSTR and is
used to truncate and return the substring of len characters starting from |start| in
str.
● The start parameter indicates the index position. The value is positive,
indicating the position of the |start| byte from left to right. The value is
negative indicating the position of the |start| byte from right to left.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 209


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● When start is 0, the index position is the first byte from left to right.
● len indicates the number of bytes truncated from the index position to the
right. When len is less than or equal to 0, the return value of the SUBSTR
function is empty. len is an optional parameter. If this parameter is omitted,
all bytes starting from the index position to the end of str are returned.
● The input parameter str must be an expression that can be converted to a
STRING value. The start and len parameters must be expressions that can be
converted to INT values. The return type is STRING.

Example:

● Truncate a string of 6 characters starting from the fifth character from left to
right.
SELECT SUBSTRING('Quadratically',5,6) EXMAPLE1, SUBSTRING('Quadratically' FROM 5 FOR 6)
EXAMPLE2 FROM SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------
ratica ratica

1 rows fetched.

● Truncate a string of 0 characters from left to right starting from the fifth
character. The return value is empty.
SELECT SUBSTRING('Quadratically',5,0) EXMAPLE1, SUBSTRING('Quadratically' FROM 5 FOR 0)
EXAMPLE2 FROM SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------

1 rows fetched.

● Truncates a string from right to left starting from the fifth character. len is
omitted. All characters starting from the index position to the end of str are
returned.
SELECT SUBSTRING('Quadratically',-5) EXMAPLE1, SUBSTRING('Quadratically' FROM -5) EXAMPLE2
FROM SYS_DUMMY;

EXMAPLE1 EXAMPLE2
-------- --------
cally cally

1 rows fetched.

SUBSTRING_INDEX
Syntax:
SUBSTRING_INDEX(str,delim,count)

Purpose: Truncates a string.

● If count is a positive number, all characters before count delim will be


returned.
● If count is a negative number, all characters after |count| delim (counted
down) will be returned.
● If count is 0, the return value will be empty.
● The input parameters str and delim must be expressions that can be
converted to STRING and cannot exceed 8000 characters.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 210


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The input parameter count must be an expression that can be converted to


NUMBER. The value range is [-2147483648,2147483647].
Example:
Obtain the first digit of an IP address.
SELECT SUBSTRING_INDEX('192.168.0.1','.',1);

SUBSTRING_INDEX('192.168.0.1','.',1)
----------------------------------
192

1 rows fetched.

TO_NCHAR
Syntax:
TO_NCHAR(text_exp)
TO_NCHAR(datetime_exp, [datetime_fmt])

Purpose: Converts text expressions, date expressions, and numbers to NCHAR


formats, which can be used to format output results.
Example:
Convert the date in the specified format to NCHAR.
SELECT TO_NCHAR(TO_DATE('2018-06-06 10:18:36', 'yyyy-mm-dd hh24:mi:ss'), 'mm-yyyy-dd') FROM
SYS_DUMMY;

TO_NCHAR(TO_DATE('2018-06-06 10:18:36', 'YYYY-MM-DD HH24:MI:SS')


----------------------------------------------------------------
06-2018-06
1 rows fetched.

TRIM
Syntax:
TRIM ( [ LEADING | TRAILING | BOTH ] [ set ] [ FROM ] str )

Purpose: Deletes spaces or other predefined characters from the input string in
the specified direction. This function can be used to format the output of a query.
● TRIM has the following values:
– LEADING: Data is deleted from the beginning of a string.
– TRAILING: Data is deleted from the end of a string.
– BOTH: Data is deleted from both ends. If LEADING, TRAILING, and
BOTH are not specified, characters are deleted from both ends by default.
● The set parameter indicates a character set. If any character in the character
set is contained in the beginning or end of str, the trim operation is
performed. If set is not specified, spaces are deleted by default.
● The input parameter str is an expression that can be converted to a STRING
value, and set is a character of the SQL syntax. The return type is STRING.
Note:
● This function can also be invoked in the form of a common function
parameter. The invoking method is TRIM( str [, set]). When this method is

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 211


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

invoked, the TRIM direction cannot be specified. By default, characters are


deleted from both ends. If set is not specified, spaces are deleted from both
ends of str.
● Currently, the CLOB and BLOB data cannot be processed.

Example:

Delete digit 1 from the two ends of the 123sfd111 string.


SELECT TRIM(BOTH '1' FROM '123sfd111') FROM SYS_DUMMY;

TRIM(BOTH '1' FROM '123SFD111')


-------------------------------
23sfd

1 rows fetched.

UPPER
Syntax:
UPPER(str)

Purpose: Converts a string to uppercase. Global languages are supported.

The input parameter is an expression that can be converted to a string. The return
type is STRING.

Example:

● Convert all characters in the Greek string "α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ σ τ


υ φ χ ψ ω" to uppercase.
SELECT UPPER('α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ σ τ υ φ χ ψ ω ') upper;

UPPER
----------------------------------------------------------------
ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ

1 rows fetched.

● Convert all the characters in the abcdefg string to uppercase.


SELECT UPPER('abcdefg') "Upper" FROM SYS_DUMMY;

Upper
------------------
ABCDEFG

1 rows fetched.

3.5.3 Time/Date Functions

● Year range: 1 to 9999


● Oct 5th-14th, 1582: invalid dates

ADD_MONTHS
Syntax:
ADD_MONTHS(date, n)
ADD_MONTHS(datetime_string, n)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 212


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Returns the value of date or datetime_string plus (n>0) or minus (n<0)
n months.

● The first parameter can be the DATE or TIMESTAMP type or a date string that
complies with NLS_DATE_FORMAT.
● The second parameter is an integer of the Int32 type. The accepted input
value is of the numeric type or can be converted to a numeric string. If the
input value is a floating point number, the value will be converted to Int32
integer by discarding the decimal part; if the value is out of the range
specified by Int32, an error is reported.

Note:

● If date is the last day of the month, then the result is the last day of the
resulting month. Example:
SELECT ADD_MONTHS(to_date('2016-02-29','yyyy-mm-dd'),1) from SYS_DUMMY;

ADD_MONTHS(TO_DATE('2016-02-29','YYYY-MM-DD'),1)
------------------------------------------------
2016-03-31 00:00:00

1 rows fetched.

● If the resulting month has fewer days than the day component of date, the
validity period will be adjusted based on the current date. Example:
SELECT ADD_MONTHS(to_date('2016-01-30','yyyy-mm-dd'),1) from SYS_DUMMY;

ADD_MONTHS(TO_DATE('2016-01-30','YYYY-MM-DD'),1)
------------------------------------------------
2016-02-29 00:00:00

1 rows fetched.

Example:

Return the date one month after March 2, 2018.


SELECT ADD_MONTHS(to_date('2018-03-02','yyyy-mm-dd'),1) from SYS_DUMMY;

ADD_MONTHS(TO_DATE('2018-03-02','YYYY-MM-DD'),1)
------------------------------------------------
2018-04-02 00:00:00

1 rows fetched.

CURRENT_TIMESTAMP
Syntax:
CURRENT_TIMESTAMP(fractional_second_precision)

Purpose: Obtains the current system time and time zone. The return value type is
timestamp with time zone, which is the same as sessiontimezone.

Note: CURRENT_TIMESTAMP is a system reserved word, which indicates the


obtained current system timestamp and the time zone of the client.
CURRENT_TIMESTAMP(prec) is a function, and prec indicates the precision of the
decimal digits after the second. The value range is 0 to 6, and the value must be
an integer constant. current_timestamp(prec) can be set to current_timestamp()
without any specified parameter value. In this case, the default value of prec is 6.

Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 213


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Return the current system time and time zone.


-- Obtain the current system time and time zone.
SELECT CURRENT_TIMESTAMP() FROM SYS_DUMMY;

CURRENT_TIMESTAMP()
----------------------------------------
2019-04-12 16:53:37.160018 +08:00

1 rows fetched.
-- Obtain the current system time, with the precision of the decimal digits after the second set to 4.
SELECT CURRENT_TIMESTAMP(4) FROM SYS_DUMMY;

CURRENT_TIMESTAMP(4)
----------------------------------------
2019-04-12 17:18:37.3949 +08:00

1 rows fetched.
-- Modify the current time zone.
ALTER SESSION SET TIME_ZONE = '+6:00';

Succeed.
-- Obtain the current time and time zone.
SELECT CURRENT_TIMESTAMP () FROM SYS_DUMMY;

CURRENT_TIMESTAMP ()
----------------------------------------
2019-04-12 15:45:26.050131 +06:00

1 rows fetched.
-- Obtain the current time and time zone, with the precision of the decimal digits after the second set to 4.
SELECT CURRENT_TIMESTAMP(4) FROM SYS_DUMMY;

CURRENT_TIMESTAMP(4)
----------------------------------------
2019-04-12 16:47:22.9578 +06:00

1 rows fetched.

EXTRACT
Syntax:
EXTRACT(field FROM datetime)

Purpose: Extracts the value of a specified time field (field) from the specified date
(datetime).
field can be YEAR, MONTH, DAY, HOUR, MINUTE, or SECOND. The return type
is NUMBER.
Note:
● If field is SECOND, the return value is a floating point number, in which the
integer part is second and the decimal part is microsecond.
● Any numeric data type or any non-numeric data type that can be implicitly
converted to a numeric data type are used as a parameter. This function
returns the data type same as that of the parameter.
Example:
Extract a month from a specified date.
SELECT EXTRACT (MONTH from date '2018-10-04');

EXTRACT (MONTH FROM DATE '2018-10-04')

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 214


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

--------------------------------------
10

1 rows fetched.

FROM_UNIXTIME
Syntax:
FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)

Purpose: Returns the datetime based on the Unix timestamp in GaussDB 100.
Note:
● FROM_UNIXTIME(unix_timestamp)
Input parameter is a BIGINT number. Numeric strings are supported. Without
format strings, the default format is YYYY-MM-DD HH:MM:SS. There are 6
decimal places behind SS.
● FROM_UNIXTIME(unix_timestamp,format)
Input parameter is date in the specified format, which is case insensitive. The
supported formats are as follows:
– %Y: four-digit year.
– %D: a date in a month. The English suffix is not supported.
– %M: English name of a month.
– %h: hour, in 24-hour format.
– %i: minute.
– %s: second.
– %x: four-digit year (Monday is the first day of each week.).
Example:
Return the date corresponding to the time stamp 1111885200.
SELECT FROM_UNIXTIME(1111885200);

FROM_UNIXTIME(1111885200)
--------------------------------
2005-03-27 09:00:00.000000

1 rows fetched.

GETUTCDATE
Syntax:
GETUTCDATE()

Purpose: Returns the value of date or datetime_string plus (n>0) or minus (n<0)
n months.
Note:
● By default, the return format is as follows: YYYY-MM-DD HH:MM:SS
TIMEZONE. There are six decimals after the second SS, and the value of
TIMEZONE is in the TZH:TZM format.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 215


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● If the GETUTCDATE() function has no input parameter, the return value type
is timestamp with time zone, which contains the time zone information.
Example:
Assume that the current Beijing time (GMT+8) is 2019-04-09 17:11:01. Query for
the current UTC time.
SELECT GETUTCDATE();

GETUTCDATE()
----------------------------------------
2019-04-09 09:11:01.838655 +00:00

1 rows fetched.

MONTHS_BETWEEN
Syntax:
MONTHS_BETWEEN(date1,date2)

Purpose: Enables GaussDB 100 to calculate the month differences between two
dates (date1 and date2).
Note:
● If date1 and date2 are the same days or last days of two months, the return
value is an integer. Otherwise, the return value contains the decimal part,
which is equal to the number of days between two dates divided by 31.
● If date1 is greater than date2, the return value is a positive number. If date1
is smaller than date2, the return value is a negative number.
● The input parameter is of the DATE or TIMESTAMP type. The return value is
of the NUMBER type.
Example:
Calculate the months between two dates.
SELECT MONTHS_BETWEEN
(TO_DATE('10-12-2018','MM-DD-YYYY'),
TO_DATE('07-25-2018','MM-DD-YYYY') ) "Months"
FROM SYS_DUMMY;

Months
----------------------------------------
2.58064516129032258064516129032258064516

1 rows fetched.

NOW
Syntax:
now(fractional_second_precision)

Purpose: Obtains the current system time and time zone.


Note: now is a system reserved word, which indicates the obtained current system
timestamp and the time zone of the client. now(prec) is a function, and prec
indicates the precision of the decimal digits after the second. The value range is 0

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 216


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

to 6, and the value must be an integer constant. Parameters are optional for
now(prec). That is, you can use now(). In this case, the default parameter value 6
is used.

Example:

Return the current system time. The value is accurate to six digits after the second.
SELECT NOW() FROM SYS_DUMMY;

NOW()
----------------------------------------
2019-04-12 18:49:33.060337 +08:00

1 rows fetched.

SLEEP
Syntax:
SLEEP(n_second)

Purpose: Sets the inactivity period after which the system enters sleep mode. The
unit is second.

Note: The input parameter n_second must be an expression generating a value of


the NUMBER type. The value range is [1,999999999999].

Examples:

Set the inactivity period to be 3 seconds after which the system enters sleep mode.

Example 1:
SELECT SLEEP(3) FROM SYS_DUMMY;

SLEEP(3)
--------
1 rows fetched.

----------------------------------------
2019-04-23 14:49:20.187932 +08:00

----------------------------------------
2019-04-23 14:49:23.187932 +08:00

SYSTIMESTAMP
Syntax:
SYSTIMESTAMP

Purpose: Returns the current timestamp. The return value type is timestamp with
time zone, and the return format is the same as that of
NLS_TIMESTAMP_TZ_FORMAT.

Note:

● You can run SELECT * FROM NLS_SESSION_PARAMETERS to query for the


values of NLS parameters.
● You can run ALTER SESSION SET nls_param = 'nls_param_value'; to change
the values of NLS parameters.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 217


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples:

Return the current timestamp


SELECT SYSTIMESTAMP FROM SYS_DUMMY;

SYSTIMESTAMP
----------------------------------------
2019-04-23 14:50:35.175553 +08:00
1 rows fetched.

TIMESTAMPADD
Syntax:
TIMESTAMPADD(unit, interval,datetime)

Purpose: Adds the interval of a specified unit to a datetime.

unit can be MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,


QUARTER, YEAR, SQL_TSI_DAY, SQL_TSI_FRAC_SECOND, SQL_TSI_HOUR,
SQL_TSI_MINUTE, SQL_TSI_MONTH, SQL_TSI_QUARTER, SQL_TSI_SECOND,
SQL_TSI_WEEK, or SQL_TSI_YEAR. The return type is DATE.

Note:

● interval must be an expression generating a value of the NUMBER type.


● The value of the input parameter datetime must comply with the time
format. The value range is [0001-01-01 00:00:00, 9999-12-31 23:59:59].
● The return value should also be within the range [0001-01-01 00:00:00,
9999-12-31 23:59:59].

Example:

Return the time that is added two weeks after the specified date.
SELECT TIMESTAMPADD(WEEK,2,'2018-10-04');

TIMESTAMPADD(WEEK,2,'2018-10-04')
---------------------------------
2018-10-18 00:00:00.000000

1 rows fetched.

TIMESTAMPDIFF
Syntax:
TIMESTAMPDIFF(unit,begin,end)

Purpose: Returns the interval between the dates specified by begin and end. The
unit of the interval is specified by unit. The return value type is NUMBER.

Note:

● The data type of begin and end can be DATE or TIMESTAMP, that is, a date or
time expression. Value range: [0001-01-01 00:00:00, 9999-12-31 23:59:59]
● unit specifies the time interval. The value can be YEAR, QUARTER, MONTH,
WEEK, DAY, HOUR, MINUTE, SECOND, MICROSECOND, SQL_TSI_DAY,
SQL_TSI_FRAC_SECOND, SQL_TSI_HOUR, SQL_TSI_MINUTE,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 218


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SQL_TSI_MONTH, SQL_TSI_QUARTER, SQL_TSI_SECOND, SQL_TSI_WEEK,


and SQL_TSI_YEAR.
Example:
Return the number of days between two specified dates.
SELECT TIMESTAMPDIFF(DAY, '2018-03-20 23:59:00', '2017-03-22 00:00:00');

TIMESTAMPDIFF(DAY, '2018-03-20 23:59:00', '2017-03-22 00:00:00')


----------------------------------------------------------------
-363

1 rows fetched.

TRUNC
Syntax:
TRUNC(date[,fmt])

Purpose: Truncates the entered date data in a specified format.


The input parameter date is the data to be truncate, and fmt is the truncating
format. The return type is DATE.
Note: The default value of fmt is DD. Currently, fmt can be CC/SCC, D/DAY/DY,
WW, W, DD/DDD, MM/RM/MON/MONTH, Q, Y/YY/YYY/YYYY, HH/HH12/
HH24, MI, or SS.
Example:
Truncate the first day of a year.
SELECT TRUNC(sysdate,'yy') from SYS_DUMMY;

TRUNC(SYSDATE,'YY')
----------------------
2018-01-01 00:00:00

1 rows fetched.

UNIX_TIMESTAMP
Syntax:
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(datetime)
UNIX_TIMESTAMP(datetime_string)

Purpose: Obtains the Unix timestamp in GaussDB 100, that is, the number of
seconds since the current time to 1970-01-01 00:00:00 UTC.
The syntax format of this function is as follows:
● unix_timestamp(): If the input parameter is not specified, the Unix timestamp
of the current time is obtained.
● unix_timestamp(datetime): If the input parameter is the Datetime type, the
Unix time stamp of the time is obtained.
● unix_timestamp(datetime_string): If the input parameter is the time type
string, the Unix time stamp of the time is obtained. The string must comply
with the common time format. The default format is YYYY-MM-DD

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 219


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

HH:MI:SS.FF, which can be controlled by the nls_timestamp_format


parameter (nls_timestamp_format is not completed yet).
● This function does not support nested calling.
Note: In GaussDB 100, unix_timestamp may return a BIGINT or a floating point
number.
Example:
Return the timestamp of 10:20:19 on November 13, 2015.
SELECT UNIX_TIMESTAMP('2015-11-13 10:20:19');

UNIX_TIMESTAMP('2015-11-13 10:20:19')
-------------------------------------
1447381219

1 rows fetched.

3.5.4 Interval Functions


NUMTODSINTERVAL
Syntax:
NUMTODSINTERVAL(num, 'interval_unit')

Purpose: Enters a value and the interval description field and outputs the
INTERVAL DAY TO SECOND type.
The num parameter can be:
● A value type, such as integer, large integer, floating point number, or high-
precision NUMBER
● An expression that can be implicitly converted to a numeric value
For details about the input and output relationships, see Table 1.

Table 3-6 NUMTODSINTERVAL input and output


Input Example Output Description

numtodsinterval(3.14259 +0000003 -
26535897932384626, 03:25:20.005270
'DAY')

numtodsinterval(3.14259 +0000000 -
26535897932384626, 00:03:08.555559
'MINUTE')

numtodsinterval(999999 +0011574 -
999.99999, 'second') 01:46:39.999990

numtodsinterval(199.999 Error The field indicator is


99, 'year') incorrect.

Note: The interval_unit parameter is a string that indicates the INTERVAL field
corresponding to num. For the NUMTODSINTERVAL function, interval_unit can be

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 220


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DAY, HOUR, MINUTE, or SECOND. Note that interval_unit is case-insensitive and


that spaces at its beginning and end are ignored.
Example:
Return the time one hour later than the current time.
SELECT SYSDATE + NUMTODSINTERVAL(1, 'HOUR') from SYS_DUMMY;

SYSDATE + NUMTODSINTERVAL(1, 'HOUR')


------------------------------------
2018-12-05 10:42:39

1 rows fetched.

NUMTOYMINTERVAL
Syntax:
NUMTOYMINTERVAL(num, 'interval_unit')

Purpose: Enters a value and the interval description field and outputs the
INTERVAL YEAR TO MONTH type.
Note:
● The interval_unit parameter is a string that indicates the INTERVAL field
corresponding to num. For the NUMTOYMINTERVAL function, interval_unit
can be YEAR or MONTH. Note that interval_unit is case-insensitive and that
spaces at its beginning and end are ignored.
● The num parameter can be:
– A value type, such as integer, large integer, floating point number, or
high-precision NUMBER
– An expression that can be implicitly converted to a numeric value
For details about the input and output relationships, see Table 2.

Table 3-7 NUMTOYMINTERVAL input and output

Input Example Output Description

numtoyminterval(9999.9, +9999-11 -
'year')

numtoyminterval(9999.9 Error The value is rounded up


9, 'year') and exceeds the
maximum.

numtoyminterval(9999.9 Error The value is rounded up


999999999999, 'year') and exceeds the
maximum.

numtoyminterval(99999. +8333-04 -
9, 'month')

numtoyminterval('123', +0010-03 The string can be


'month') converted to a numeric
value.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 221


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Input Example Output Description

numtoyminterval('123XX' Error Failed to convert the


, 'month') string to a numeric type.

numtoyminterval(+3.142 +0003-02 -
5926535897932384626,
'year')

Example:

Return the time that is one month later than the current time.
SELECT SYSDATE + NUMTOYMINTERVAL(1, 'MONTH') from SYS_DUMMY;

SYSDATE + NUMTOYMINTERVAL(1, 'MONTH')


-------------------------------------
2019-01-05 09:33:28

1 rows fetched.

TO_DSINTERVAL
Syntax:
TO_DSINTERVAL(str_exp)

Purpose: Enters an INTERVAL string and outputs the value of INTERVAL DAY TO
SECOND type.

It indicates the day (DAY) and time (including hour, minute, second, and
microsecond) in the interval. This parameter is used to accurately describe time.

TO_DSINTERVAL supports two text formats:


● SQL time interval format, compatible with the SQL standard (ISO/IEC
9075:2003)
● ISO time interval format, compatible with the ISO 8601:2004 standard

Note:

● The ISO format of TO_DSINTERVAL must start from DAY, and YEAR or
MONTH cannot be specified. Otherwise, a syntax error is reported.
● Spaces between format elements are allowed in the SQL interval format, but
not allowed in the ISO interval format.
● The ISO format of TO_DSINTERVAL must comply with the ISO format of the
TO_YMINTERVAL function.
The value of each field is shown in Table 3.

Table 3-8 Value ranges

Domain Name Value Range in SQL Value Range in ISO


Format Format

years [0, 9999] [0, 9999]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 222


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Domain Name Value Range in SQL Value Range in ISO


Format Format

months [0, 11] [0, 99999]

days [0, 9999999] [0, 9999999]

hours [0, 23] [0, 999999999]

minutes [0, 59] [0, 999999999]

seconds [0, 59] [0, 999999999]

frac_secs >=0. A maximum of six >=0. A maximum of six


valid digits are allowed. valid digits are allowed.

The output result of each format element is shown in Table 4.

Table 3-9 Output

Input Output Description

'-PT23H23M23S' -00 23:23:23.000000 -

'- -00 23:23:23.003334 The value is rounded to


PT23H23M23.00333399 a maximum of six
9S' decimal places.

'PT999999M' +694 10:39:00.000000 -

'- Error The DSINTERVAL type


P012M28DT21H213.00 must start from DAY.
S'

'PT123123M123H' Error The MINUTE field


cannot be followed by
HOUR.

'-P100DT' Error If T is specified, there


should be at least one
time field following it.

'-P12DT.00123S' Error The value of the


SECOND field is not
specified.

'PT12.3H312.99999999 Error The HOUR field must


9999S' be an integer.

'P12H' Error The time field must


follow T.

'PT12H12H' Error Do not assign multiple


values to the same
field.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 223


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Input Output Description

'PT12H12.S' Error If the value of SECOND


contains a decimal
point, the value of
FRAC_SEC must be
specified.

'12 12:12:12' +12 12:12:12.000000 -

'-0 0:0:0' +00 00:00:00.000000 -

'9999999 +9999999 -
23:59:59.999999' 23:59:59.999999

' - 00012 0012 : 00012 : -12 12:12:12.000000 Spaces are allowed at


000000000000012 ' the beginning and end
of a field or between
fields.

'+00 0:0:0. 0' Error Spaces are not allowed


between SECOND and
FRAC_SEC.

'+00 24:0:0.0' Error The maximum value of


the HOUR field in SQL
format is 23.

'+00 11:80:0.0' Error The maximum value of


the MINUTE field in
SQL format is 59.

'+00 11:11' Error Incorrect format.

Example:

Return the IDs and names of employees who have worked for the company for
180 days by December 31, 2018.
--Delete the employee table.
DROP TABLE IF EXISTS employee;

--Create the employee table.


CREATE TABLE employee(employee_id INT NOT NULL,first_name VARCHAR(10),last_name VARCHAR(10),
hire_date DATETIME);
-- Insert several data records.
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1001,'Alice','BROWN','2017-06-20 12:00:00');
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1002,'BOB','Smith','2017-10-20 12:00:00');
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1003,'ALAN','Jones','2017-05-10 12:00:00');
-- Commit the transaction.
COMMIT;
-- Query for the employees who have worked for the company for 180 days by December 31, 2018.
SELECT * FROM employee WHERE hire_date + TO_DSINTERVAL('180 00:00:00') <= DATE '2018-12-31'
ORDER BY employee_id;

EMPLOYEE_ID FIRST_NAME LAST_NAME HIRE_DATE


------------ ---------- ---------- ----------------------
1001 Alice BROWN 2017-06-20 12:00:00

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 224


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

1002 BOB Smith 2017-10-20 12:00:00


1003 ALAN Jones 2017-05-10 12:00:00

3 rows fetched.

TO_YMINTERVAL
Syntax:
TO_YMINTERVAL(str_exp)

Purpose: Enters an INTERVAL string and outputs the value of INTERVAL YEAR TO
MONTH type.
Indicates the year (YEAR) and month (MONTH) in the interval. This function
calculates how many years and months are in the interval.
TO_YMINTERVAL supports two text formats:
● SQL time interval format, compatible with the SQL standard (ISO/IEC
9075:2003)
● ISO time interval format, compatible with the ISO 8601:2004 standard
For details about the value ranges of different domains in the two standards,
see Table 5.

Table 3-10 Value ranges

Domain Name Value Range in SQL Value Range in ISO


Format Format

years [0, 9999] [0, 9999]

months [0, 11] [0, 99999]

days [0, 9999999] [0, 9999999]

hours [0, 23] [0, 999999999]

minutes [0, 59] [0, 999999999]

seconds [0, 59] [0, 999999999]

frac_secs >=0. A maximum of six >=0. A maximum of six


valid digits are allowed. valid digits are allowed.

Table 6 lists the output results of each ISO format element.

Table 3-11 Output

Input Output Description

'P01Y02M' +01-02 -

'P24M' +02-00 -

'-P0Y123M' -10-03 -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 225


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Input Output Description

'-P9999Y999999M' Error The MONTH field is


out of range (<=
99,999).

'P9999DT2000H' +00-00 The values of the YEAR


and MONTH fields are
not specified, and the
values of other fields
are ignored.

'-P012.3M23D' Error Each field must be an


integer.

'-P 12M' Error Spaces are not allowed


in ISO format.

' -P12M ' -01-00 Spaces are allowed at


the beginning and end.

'-P12M33Y' Error The YEAR field cannot


follow the MONTH
field.

'1233-0' +1233-00 -

'- 1233 - 2' -1233-02 Spaces are allowed in


SQL format.

' +00-000003' +00-03 Spaces at the


beginning and end of a
field are allowed. The
field can start with
multiple 0s.

'12332-1' Error The YEAR field is out of


range (<= 9999).

'12-12' Error The MONTH field in


the SQL format is out
of range (<= 11).

'223' Error The format


requirements are not
met.

Note:
● The values of a field should be a non-negative integer.
● In the TO_YMINTERVAL function, even if the values of fields such as DAY,
HOUR, and MINUTE are specified, they are still ignored. The
TO_YMINTERVAL function focuses only on the values specified in the YEAR
and MONTH fields.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 226


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The values of the fields in ISO format must be specified in the required
sequence. For example, the YEAR field cannot follow the MONTH field.
● If the time field indicator T is specified, it should be followed by at least one
time field.
● If the FRAC_SEC field is specified, the SECOND field must be specified, and no
spaces are allowed between the fields.

Example 1:

Return the time two years and five months later than the current time.
SELECT (SYSDATE) + TO_YMINTERVAL('02-05') from SYS_DUMMY;

(SYSDATE) + TO_YMINTERVAL('02-05')
----------------------------------
2021-08-13 15:45:53

1 rows fetched.

Example 2:

Return the IDs and names of employees who have worked for the company for
one year and three months by December 31, 2018.
--Create the employee table.
CREATE TABLE employee(employee_id INT NOT NULL,first_name VARCHAR(10),last_name VARCHAR(10),
hire_date DATETIME);
-- Insert several data records.
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1001,'Alice','BROWN','2017-06-20 12:00:00');
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1002,'BOB','Smith','2017-10-20 12:00:00');
INSERT INTO employee(employee_id,first_name,last_name,hire_date)
VALUES(1003,'ALAN','Jones','2017-05-10 12:00:00');
-- Commit the transaction.
COMMIT;
-- Query for the employees who have worked for the company for one year and three months by December
31, 2018.
SELECT employee_id, first_name, last_name FROM employee WHERE hire_date + TO_YMINTERVAL('01-03')
<= DATE '2018-12-31' ORDER BY employee_id;

EMPLOYEE_ID FIRST_NAME LAST_NAME


------------ ---------- ----------
1001 Alice BROWN
1003 ALAN Jones

2 rows fetched.

3.5.5 Type Conversion Functions

ASCII
Syntax:
ASCII(str)

Purpose: Returns the ASCII code corresponding to the first character of str.

The input parameter is a string or a single character, which must be enclosed in


single quotation marks ('). The return value is an ASCII code.

Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 227


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Return the ASCII code corresponding to the first character (h) of the string
helloword.
SELECT ASCII('helloword') FROM SYS_DUMMY;

ASCII('HELLOWORD')
--------------------
104

1 rows fetched.

CAST
Syntax:
CAST(expr as datatype)

Purpose: Converts the column name/value to the specified data type datatype.
The expression can be converted to the same type as itself.
The CAST function can be used to convert data types in the following scenarios. In
other scenarios, an error is reported.
● Two expressions can be implicitly converted.
● The data type must be explicitly converted.
Example:
Convert the string '10' to the int type.
SELECT CAST('10' AS INT) FROM SYS_DUMMY;

CAST('10' AS INT)
-----------------
10

1 rows fetched.

CHAR
Syntax:
CHAR(n)

Purpose: Returns the character whose ASCII code is n. The value range of n is
[0,127].
The input parameter is an expression that can be converted to a numeric value.
The character whose ASCII code is n is returned.
Example:
Return the character whose ASCII code is 67.
SELECT CHAR(67) FROM SYS_DUMMY;

CHAR(67)
--------
C

1 rows fetched.

CHR
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 228


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

CHR(n)

Purpose: Returns the character whose ASCII code is n. The value range of n is
[0,127].
The input parameter is an expression that can be converted to a numeric value.
The character whose ASCII code is n is returned.
Example:
Return the character whose ASCII code is 97.
SELECT CHR(97) FROM SYS_DUMMY;

CHR(97)
-------
a

1 rows fetched.

CONVERT
Syntax:
CONVERT(expr,data_type)

Purpose: Converts expr to data_type.


The value range of data_type is all data types except CLOB, BLOB, and IMAGE. For
details, see Data Types.
Example:
Convert a string to the time type.
SELECT CONVERT('2018-06-28 13:14:15', timestamp) as datetime FROM SYS_DUMMY;

DATETIME
---------------------------------------------------------------
2018-06-28 13:14:15.000000

1 rows fetched.

DECODE
Syntax:
DECODE(expr,{search,result} [,...] [default])

Purpose:
● Compares expr with each search one by one. If expr is equal to a search, the
corresponding result is returned.
● If no match is found, default is returned.
● If default is omitted, NULL is returned.
● Multiple pairs of search and result are separated with commas (,).
● The input parameters support the following data types: INTEGER UNSIGNED,
INT, BIGINT, REAL, STRING, NUMBER, DATE, TIMESTAMP, and BINARY.
● The return type is STRING.
Example:
Decode the value of staff_ID in the staffS_xian table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 229


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete tables named staffS_xian.


DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 2 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 3 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',
4400.00, 101, 10);
-- Decode values of staff_ID. If staff_ID is 198, the function returns Group A. If staff_ID is 199, the
function returns Group B. If staff_ID is not 198 or 199, the function returns unknown.
SELECT staff_ID, DECODE (staff_ID, 198, 'Group A', 199, 'Group B', 'unknown') "GROUP" FROM staffS_xian
WHERE staff_ID < 201 ORDER BY staff_ID;

STAFF_ID GROUP
---------------------------------------- -------
198 Group A
199 Group B
200 unknown

3 rows fetched.

IF
Syntax:
IF(cond,exp1,exp2)

Purpose: Calculates based on the condition cond. If the condition is true, exp1 is
returned. Otherwise, exp2 is returned.
Example:
Return the employee ID and salary list. If the salary is NULL, return secret.
-- Delete tables named staffS_xian.
DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 230


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
Values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', NULL, 124, 50);
-- Insert record 2 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 3 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',
4400.00, 101, 10);
-- Insert record 4 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
Values (206, 'Li Ruiyun', 'liruiyun03@126.com', '18095565892', to_date('17-09-1988', 'dd-mm-yyyy'),
'AD_ASST', 3900.00, 101, 10);
-- Return the employee ID and salary list. If the salary is NULL, return secret.
SELECT staff_ID, IF(SALARY < 4000, SALARY, 'secret') "SALARY" FROM staffS_xian WHERE staff_ID IS NOT
NULL ORDER BY staff_ID;

STAFF_ID SALARY
---------------------------------------- ----------------------------------------------------
198 secret
199 2600
200 secret
206 3900

4 rows fetched.

IFNULL
Syntax:
IFNULL(expr1, expr2)

Purpose:
● If expr1 is not NULL, expr1 is returned.
● If expr1 is NULL, expr2 is returned.
Example:
Return the employee ID and salary list. If the salary is NULL, unknown is
returned.
-- Delete tables named staffS_xian.
DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 231


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

MANAGER_ID, section_ID)
Values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', NULL, 124, 50);
-- Insert record 2 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 3 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',
4400.00, 101, 10);
-- Return the employee ID and salary list. If the salary is NULL, unknown is returned.
SELECT staff_ID, IFNULL(SALARY, 'unknown') "SALARY" FROM staffS_xian WHERE staff_ID IS NOT NULL
ORDER BY staff_ID;

STAFF_ID SALARY
---------------------------------------- ----------------------------------------------------
198 unknown
199 2600
200 4400

3 rows fetched.

NULLIF
Syntax:
NULLIF(expr1, expr2)

Purpose:
● If expr1 equals expr2, NULL is returned.
● If expr1 does not equal expr2, expr1 is returned.
Note:
● expr1 cannot be NULL. Otherwise, an error is reported during verification.
● expr1 and expr2 must be of the same data type. Otherwise, an error will be
reported during verification.
● expr1 and expr2 cannot be of the CLOB or BLOB type at the same time.
Example:
Return a list containing employee IDs and salaries. Display salaries not equal to
2600.00 as they are and the salary equal to 2600.00 as NULL.
-- Delete tables named staffS_xian.
DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 232


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),


'SH_CLERK', 1000.15, 124, 50);
-- Insert record 2 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 3 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',
4400.00, 101, 10);
-- Return a list containing employee IDs and salaries. Display salaries not equivalent to 2600.00 as they are
and those equivalent to 2600.00 as NULL.
SELECT staff_ID, NULLIF(SALARY, 2600.00) "SALARY" FROM staffS_xian WHERE staff_ID IS NOT NULL
ORDER BY staff_ID;

STAFF_ID SALARY
---------------------------------------- ----------------------------------------
198 1000.15
199
200 4400

3 rows fetched.

NVL
Syntax:
NVL(expr1, expr2)

Purpose:

● If expr1 is not NULL, expr1 is returned.


● If expr1 is NULL, expr2 is returned.

Example:

Return the employee ID and salary list. If the salary is NULL, 0 is returned.
-- Delete tables named staffS_xian.
DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
Values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', NULL, 124, 50);
-- Insert record 2 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);
-- Insert record 3 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 233


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',


4400.00, 101, 10);
-- Return the employee ID and salary list. If the salary is NULL, 0 is returned.
SELECT staff_ID, NVL(SALARY,0) "SALARY" FROM staffS_xian WHERE staff_ID IS NOT NULL ORDER BY
staff_ID;

STAFF_ID SALARY
---------------------------------------- ----------------------------------------
198 0
199 2600
200 4400

3 rows fetched.

NVL2
Syntax:
NVL2(expr1,expr2,expr3)

Purpose:
● If expr1 is not NULL, expr2 is returned.
● If expr1 is NULL, expr3 is returned.
Example:
Return the employee ID and salary list. If the salary is NULL, 0 is returned. If the
salary is not NULL, 1 is returned.
-- Delete tables named staffS_xian.
DROP TABLE IF EXISTS staffS_xian;
-- Create the staffS_xian table.
CREATE TABLE staffS_xian
(
staff_ID NUMBER(6) not null,
NAME VARCHAR2(20),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert record 1 to the staffS_xian table.
INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
Values (198, 'Wang Ying', 'wangying@126.com', '18095605632', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', NULL, 124, 50);

-- Insert record 2 to the staffS_xian table.


INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (199, 'He Kaiping', 'hekaipng02@126.com', '18095605532', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, 124, 50);

-- Insert record 3 to the staffS_xian table.


INSERT INTO staffS_xian (staff_ID, NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, employment_ID, SALARY,
MANAGER_ID, section_ID)
values (200, 'Li Rui', 'lirui03@126.com', '18095565632', to_date('17-09-1987', 'dd-mm-yyyy'), 'AD_ASST',
4400.00, 101, 10);
-- Return the employee ID and salary list. If the salary is NULL, 0 is returned. If the salary is not NULL, 1 is
returned.
SELECT staff_ID, NVL2(SALARY,1,0) "SALARY" FROM staffS_xian WHERE staff_ID IS NOT NULL ORDER BY
staff_ID;

STAFF_ID SALARY

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 234


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

---------------------------------------- ------------
198 0
199 1
200 1

3 rows fetched.

TO_CHAR
Syntax:
TO_CHAR(expr[,fmt])

Purpose: Converts expr to a string.


● The input parameter is an expression that can be converted to a STRING
value.
● The return type is STRING.
● fmt specifies the value format of the DATE type, for example,
yyyy/mm/dd/hh/hh12/hh24/mi/ss/ff3. (For details, see Datetime Data
Types.) If format is not specified, the current session time format is used by
default.
You can run the following command to set the time format of the current session:
-- Set the time format of the DATE type through NLS_DATE_FORMATDATE.
ALTER SESSION SET NLS_DATE_FORMAT='format';

-- Set the time format of the TIMESTAMP type through NLS_TIMESTAMP_FORMAT.


ALTER SESSION SET NLS_TIMESTAMP_FORMAT='format';

Note:
Currently, the function supports only the format control character of the date type
(date, timestamp).
Example:
● Specify the format control character and return the current system time.
SELECT to_char(sysdate, 'MON-YY-DD HH:MM:SS AM') FROM SYS_DUMMY;

TO_CHAR(SYSDATE, 'MON-YY-DD HH
-------------------------------
JAN-18-07 05:01:15 AM

1 rows fetched.

● Set the time format of the current session and return the current system time.
-- Set the time format through NLS_DATE_FORMATDATE.
ALTER SESSION SET NLS_DATE_FORMAT='YYYYMMDD HH24:MI:SS';
-- Query the system time.
SELECT TO_CHAR(sysdate) FROM SYS_DUMMY;

TO_CHAR(SYSDATE)
------------------------------------------------
20181207 15:12:24

1 rows fetched.

● Convert 56698 to a string.


SELECT TO_CHAR('56698') FROM SYS_DUMMY;

TO_CHAR('56698')

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 235


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

----------------
56698

1 rows fetched.

TO_CLOB
Syntax:
TO_CLOB(str)

Purpose: Converts data specified by str to the CLOB type.

Example:

Convert the data of the comment column to the CLOB type.


--Delete tables named employee.
DROP TABLE IF EXISTS employee_branch_nanjing;

--Create the employee table.


CREATE TABLE employee_branch_nanjing(employee_id INT NOT NULL,first_name VARCHAR(10),last_name
VARCHAR(10), hire_date DATETIME,comment VARCHAR(1012));
--Insert record 1.
INSERT INTO employee_branch_nanjing(employee_id,first_name,last_name,hire_date,comment)
VALUES(1001,'Alice','BROWN','2017-06-20 12:00:00','excellent staff of 2018,bonus 5000¥');
--Insert record 2.
INSERT INTO employee_branch_nanjing(employee_id,first_name,last_name,hire_date,comment)
VALUES(1002,'BOB','Smith','2017-10-20 12:00:00','excellent manager of 2018,bonus 2000¥');
--Insert record 3
INSERT INTO employee_branch_nanjing(employee_id,first_name,last_name,hire_date,comment)
VALUES(1003,'ALAN','Jones','2017-05-10 12:00:00','');
-- Commit the transaction.
COMMIT;
-- Convert the data of the comment column to the CLOB type.
UPDATE employee_branch_nanjing SET comment=TO_CLOB(comment);

3 rows affected.

TO_DATE
Syntax:
TO_DATE(expr[,fmt])

Purpose: Convert expr to the date type.

● fmt specifies the target format, for example, yyyy/mm/dd/hh/hh12/


hh24/mi/ss/ff3.
● The input parameter is a string expression or a value type that can be
implicitly converted to a DATE type.
● The return type is DATE.

Example:

Convert a string to the date type.


SELECT TO_DATE('2018-06-28 13:14:15', 'YYYY-MM-DD HH24:MI:SS:FF') FROM SYS_DUMMY;

TO_DATE('2018-06-28 13:14:15', 'YYYY-MM-DD HH24:MI:SS:FF')


----------------------------------------------------------
2018-06-28 13:14:15

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 236


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

TO_NUMBER
Syntax:
TO_NUMBER(n[, fmt])

Purpose: Converts n to the number type.

The input parameter n is an expression or string that can be converted to the


number type. The fmt parameter is optional, indicating the target format of n. If
this parameter is not set, the value is converted to a decimal number by default.
Currently, fmt supports two fixed formats:

● X: Converts n to a hexadecimal string. In this format, n can contain only


hexadecimal characters 0 to 9, A to F, and a to f.
– In the format of XX, the number of Xs must be greater than or equals the
number of characters preceding them.
– If the target format is 0X, the value of n must be 0 or a positive integer.
● 000.00: Converts n to the decimal format. The number of digits before the
decimal point indicates the number of integers. If the number of integers in n
exceeds the number of integers in the format, an error is reported. The
number after the decimal point in fmt indicates the number of digits
following the decimal point after conversion.

The return type is NUMBER.

Example 1:

Convert 123E500 to number.


SELECT TO_NUMBER('123E500', 'XXXXXXX') from SYS_DUMMY;

TO_NUMBER('123E500', 'XXXXXXX')
----------------------------------------
19129600

1 rows fetched.

Example 2:

Convert 123.500 to number.


SELECT TO_NUMBER('123.500', '000.0000') from SYS_DUMMY;

TO_NUMBER('123.500', '000.0000')
----------------------------------------
123.5

1 rows fetched.

Example 3:

Convert 00FFFFFF to the number type.


SELECT TO_NUMBER('00FFFFFF', '0000000X') from SYS_DUMMY;
----------------------------------------
16777215

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 237


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

TO_TIMESTAMP
Syntax:
TO_TIMESTAMP(expr[,fmt])

Purpose: Converts expr to a time type.


● fmt specifies the target format, for example, yyyy/mm/dd/hh/hh12/
hh24/mi/ss/ff3.
● The input parameter is an expression that can be converted to a TIMESTAMP
value.
● The return type is TIMESTAMP.
Example:
Convert a string to the time type.
SELECT TO_TIMESTAMP('2018-06-28 13:14:15', 'YYYY-MM-DD HH24:MI:SS:FF') FROM SYS_DUMMY;

TO_TIMESTAMP('2018-06-28 13:14:15', 'YYYY-MM-DD HH24:MI:SS:FF')


---------------------------------------------------------------
2018-06-28 13:14:15.000000

1 rows fetched.

UNHEX
Syntax:
UNHEX(expr1)

Purpose: expr1 is a hexadecimal string. It converts a hexadecimal string to


characters represented by bytes.
Example:
Convert a hexadecimal string (746869732069732061207465737420737472) to
characters represented by bytes.
SELECT UNHEX('746869732069732061207465737420737472') FROM SYS_DUMMY;

UNHEX('746869732069732061207465737420737472')
----------------------------------------------------------------
this is a test str

1 rows fetched.

3.5.6 Aggregate Functions

Nested calls are not supported between aggregation functions.

AVG
Syntax:
AVG(expr)

Purpose: Calculates the average (arithmetic mean) of all input values.


Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 238


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Return the average value of MANAGER_ID in the staffS table.


CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
SELECT AVG(MANAGER_ID) AS "AVG" FROM staffs;

AVG
----------------------------------------
116.333333333333333333333333333333333333

1 rows fetched.

COUNT
Syntax:
COUNT(expr)

Purpose: Returns the number of records by column. If this function is executed for
a single column, a not-NULL column value counts 1 and a NULL column value
counts 0. If this function is executed for all columns, that is, count(*), a record
counts 1 even if there are NULL values in the record.

Example:

Return the number of records in the staffs table.


CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 239


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
SELECT COUNT(staff_ID) AS "COUNT" FROM staffS;

COUNT
--------------------
3

1 rows fetched.

MAX
Syntax:
MAX(expr)

Purpose: Returns the maximum value. It can be used for data in the numeric,
date, or character type. If it is used for the character type, letters are ordered from
Z to A. If it is used for the date type, the latest date will be returned.
Example:
Return the maximum value of section_ID in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
SELECT MAX(section_ID) AS "MAX" FROM staffs;

MAX
----------------------------------------

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 240


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

50

1 rows fetched.

MEDIAN
Syntax:
MEDIAN(expr)

Purpose: Returns the median. The median is the value separating the higher half
from the lower half of a sorted result set. If the query result set contains an even
number of records, the median is the mean of the middle two values.

Example:

Return the median of staff_ID in the staffS table.


-- Delete the STAFFS table.
DROP TABLE IF EXISTS STAFFS;
-- Create the STAFFS table.
CREATE TABLE STAFFS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
-- Insert records into the STAFFS table.
INSERT INTO STAFFS (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO STAFFS (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO STAFFS (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
-- Return the median of the staff_ID column.
SELECT MEDIAN(staff_ID) AS "MEDIAN" FROM STAFFS;

MEDIAN
----------------------------------------
199

1 rows fetched.

MIN
Syntax:
MIN(expr)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 241


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Returns the minimum value. It can be used for data in the numeric, date,
or character type. If it is used for the character type, letters are ordered from A to
Z. If it is used for the date type, the earliest date will be returned.
Example:
Return the minimum value of staff_ID in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
SELECT MIN(staff_ID) AS "MIN" FROM staffs;

MIN
----------------------------------------
198

1 rows fetched.

SUM
Syntax:
SUM(expr)

Purpose: Calculates the sum of a group.


Note: The value of expr must be an expression that can be converted to the
NUMBER type.
Example:
Return the total salary in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 242


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);
SELECT SUM(SALARY) AS "SUM" FROM staffs;

SUM
----------------------------------------
9600

1 rows fetched.

STDDEV
Syntax:
STDDEV(expr)

Purpose: Returns the sample standard deviation of a group. It is used as an


aggregation or analytic function.
Example:
Return the standard deviation of salaries in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 243


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SELECT STDDEV(SALARY) AS "STDDEV" FROM staffs;

STDDEV
----------------------------------------
1039.23048454132637611646780490352342017

1 rows fetched.

STDDEV_SAMP
Syntax:
STDDEV_SAMP(expr)

Function: Calculates the standard deviation of a group. It is used as an


aggregation or analytic function.
Note: If there is only one row of data, STDDEV returns 0 and STDDEV_SAMP
returns null.
Example:
Return the sample standard deviation of salaries in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);
SELECT STAFF_ID, FIRST_NAME, SALARY, STDDEV_SAMP(SALARY) OVER (PARTITION BY staff_ID) AS
"samp" FROM staffs;

STAFF_ID FIRST_NAME SALARY


samp
---------------------------------------- -------------------- ----------------------------------------
----------------------------------------
198 Donald 2600 0
198 Donald 2600 0
199 Douglas 2600
200 Jennifer 4400

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 244


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

STDDEV_POP
Syntax:
STDDEV_POP(expr)

Purpose: Calculates the standard deviation of a data set in a group. It is used as


an aggregation or analytic function.

Note: STDDEV_POP is used to calculate the standard deviation of a definitive data


set rather than a sample standard deviation. It returns the arithmetic square root
of a variance. Its calculation formula is slightly different from that of STDDEV.

Example:

Return the overall standard deviation and sample standard deviation of the
salaries in the staffS table.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);
SELECT STDDEV_POP(SALARY) "Pop", STDDEV_SAMP(SALARY) "Samp" FROM staffs;

Pop Samp
---------------------------------------- ----------------------------------------
779.422863405994782087350853677642565124 900

1 rows fetched.

GROUP_CONCAT
Syntax:
GROUP_CONCAT([DISTINCT] expr1 [, expr2...] [ORDER BY {unsigned_integer | col_name | expr} [ASC |
DESC] [, col_name...]] [SEPARATOR str_val])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 245


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Concatenates strings in groups and separates them using specified


delimiters.
Note:
● If two or more expressions are specified, the function concatenates the
expressions before concatenating strings in groups. The expressions are not
separated by delimiters.
● The default delimiter is a comma (,).
● The function supports a maximum of 64 parameters, and the delimiter of the
GROUP_CONCAT function is one of them. A maximum of 63 parameters can
be specified.
Example:
Group records by staff_ID and concatenate the values in SALARY.
CREATE TABLE staffS
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
);
INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,
employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (200, 'Jennifer', 'Whalen', 'JWHALEN', '515.123.4444', to_date('17-09-1987', 'dd-mm-yyyy'),
'AD_ASST', 4400.00, null, 101, 10);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID)
VALUES (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);
SELECT staff_ID,GROUP_CONCAT(SALARY) FROM staffs GROUP BY staff_ID;

STAFF_ID GROUP_CONCAT(SALARY)
---------------------------------------- ----------------------------------------------------------------
200 4400
198 2600,2600
199 2600

3 rows fetched.

3.5.7 Analytic Functions


LAG
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 246


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

LAG(expr,n ,m) over([ partition by [expr1][ ,... ] ] [order by [expr2][ ,... ] [NULLS FIRST | LAST] ])

Purpose: Returns data in the nth row of the same column before the current
record. Data is returned as an independent column. If the required data does not
exist, the default value is returned.

● expr1 is a name or an expression that represents the columns to be grouped.


expr2 is a name or an expression that represents the columns to be sorted.
● n is the offset, an integer greater than or equal to 0.
● m is the default value. It can be a column value, a constant, or an expression.
● For details about [NULLS FIRST | LAST], see •ORDER BY.

Note:

● If there is no value in the expr column in the nth row before the current
record, the default value m is returned.
● If the function has neither the parameter n nor m, the value of the expr
column in the previous row of the current row is returned. If the value does
not exist, NULL is returned.

Examples:

Return the staff salary two months ago in the staffs table.
-- Delete the staffs table.
DROP TABLE IF EXISTS staffs;
-- Create the staffs table.
CREATE TABLE staffs
(
staff_id NUMBER(6) not null,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
);
-- Insert data.
insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2200.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2400.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK',
4000.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 247


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

commission_pct, manager_id, section_id)


values (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK',
4200.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK',
4400.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (105, 'David', 'Austin', 'DAUSTIN', '590.423.4569', to_date('25-06-1997', 'dd-mm-yyyy'), 'IT_PROG',
4400.00, null, 103, 60);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (105, 'David', 'Austin', 'DAUSTIN', '590.423.4569', to_date('25-06-1997', 'dd-mm-yyyy'), 'IT_PROG',
4600.00, null, 103, 60);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (105, 'David', 'Austin', 'DAUSTIN', '590.423.4569', to_date('25-06-1997', 'dd-mm-yyyy'), 'IT_PROG',
4800.00, null, 103, 60);
-- Return the staff salary two months ago.
select staff_ID, lag(salary, 2,null)over(partition by staff_ID order by staff_ID) from staffs;

105
105
105 4400
198
198
198 2200
199
199
199 4000
9 rows fetched.

3.5.8 Table Functions

DBA_ANALYZE_TABLE
Syntax:
select * from table(dba_analyze_table(param1, param2));

Purpose: Returns the analysis result of the table, including the total number of
occupied pages, number of extents, total number of rows, number of row
connections, number of migrated rows, and average length of each row.

Note:

● If the database parameter UPPER_CASE_TABLE_NAMES is set to TRUE


(default value), the username and table name in the database are capitalized
by default. The parameters specified in this function should also be
capitalized, or error messages will be displayed, indicating that the objects do
not exist or users do not have sufficient permissions.
● If the parameter is set to FALSE or the user uses double quotation marks ("")
to enter a case sensitive table object, the same case sensitive parameter
should be given in the function. Otherwise, an error message is displayed,
indicating that the object does not exist.
● This table function allows only the current user to query their own tables and
users having the DBA role to query the tables of other users.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 248


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Note:
● param1: username string
● param2: table name string
● STAT_ITEM: names of the items involved in the analysis
● VALUE: value of the corresponding item
Example:
select * from table(dba_analyze_table('gaussdba', 'test_t1'));

STAT_ITEM VALUE
---------------------------------------------------------------- --------------------
total pages 8
total extents 1
total rows 8
linked rows 0
mirgated rows 0
average row size 133

6 rows fetched.

DBA_PROC_DECODE
Syntax:
select * from table(dba_proc_decode(param1, param2, param3));

Purpose: Returns the compilation result of a stored procedure, customized


function, or trigger. It is displayed in logical lines.
Note:
● If the database parameter UPPER_CASE_TABLE_NAMES is set to TRUE
(default value), the username and table name in the database are capitalized
by default. The parameters specified in this function should also be
capitalized, or error messages will be displayed, indicating that the objects do
not exist or users do not have sufficient permissions.
● If the parameter is set to FALSE or the user uses double quotation marks ("")
to enter a case sensitive table object, the same case sensitive parameter
should be given in the function. Otherwise, an error message is displayed,
indicating that the object does not exist.
● This table function allows only the current user to query their own stored
procedures, customized functions, and triggers; and allows users having the
DBA role to query the stored procedures, customized functions, and triggers
of other users.
Note:
● param1: username string
● param2: program name string
● param3: Program type string. The value can be PROCEDURE, FUNCTION, or
TRIGGER.
● LINE_NUM: logical line number
● LINE_TYPE: logical line type
● LOC_LINE: first physical line number corresponding to a logical line

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 249


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● SPECIAL_DESCRIPTION: Special description of the logic line. (Currently, only


the description of the logical line redirection relationship is provided.)

Example:
select * from table(dba_proc_decode('gaussdba', 'GATHER_CHANGE_STATS', 'PROCEDURE'));

LINE_NUM LINE_TYPE LOC_LINE SPECIAL_DESCRIPTION


------------ -------------------------------- ------------ ----------------------------------------------------------------
1 LINE_BEGIN 9 except[null];end[29];
2 LINE_IF 11 t_line[null];f_line[7];next[7];
3 LINE_SQL 12
4 LINE_IF 13 t_line[null];f_line[6];next[6];
5 LINE_RETURN 14
6 LINE_END_IF 15
7 LINE_END_IF 16
8 LINE_PROC 19
9 LINE_FOR 22 next[18];
10 LINE_BEGIN 28 except[12];end[17];
11 LINE_PROC 29
12 LINE_EXCEPTION 30 end[16];
13 LINE_WHEN 31
14 LINE_NULL 32
15 LINE_END_WHEN 32
16 LINE_END_EXCEPTION 32
17 LINE_END 33
18 LINE_END_LOOP 34 loop[9];
19 LINE_FOR 37 next[28];
20 LINE_BEGIN 38 except[22];end[27];
21 LINE_PROC 39
22 LINE_EXCEPTION 40 end[26];
23 LINE_WHEN 41
24 LINE_NULL 42
25 LINE_END_WHEN 42
26 LINE_END_EXCEPTION 42
27 LINE_END 43
28 LINE_END_LOOP 44 loop[19];
29 LINE_END 46

29 rows fetched.

DBA_PROC_LINE
Syntax:
select * from table(dba_proc_line(param1, param2));

Purpose: Returns the source code of the stored procedure. The result is displayed
in lines.

Note:

● If the database parameter UPPER_CASE_TABLE_NAMES is set to TRUE


(default value), the username and table name in the database are capitalized
by default. The parameters specified in this function should also be
capitalized, or error messages will be displayed, indicating that the objects do
not exist or users do not have sufficient permissions.
● If the parameter is set to FALSE or the user uses double quotation marks ("")
to enter a case sensitive table object, the same case sensitive parameter
should be given in the function. Otherwise, an error message is displayed,
indicating that the object does not exist.
● This table function allows only the current user to query the stored
procedures, customized functions, and triggers created by themselves, and

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 250


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

allows users having the DBA role to query the procedures, customized
functions, and triggers of other users.

Note:

● param1: username string


● param2: program name string
● LOC_LINE: physical line number
● SOURCE_LINE: program source code corresponding to a single physical line

Example:
select * from table(dba_proc_line('gaussdba', 'GATHER_CHANGE_STATS'));

LOC_LINE SOURCE_LINE
------------ ----------------------------------------------------------------
1 CREATE OR REPLACE PROCEDURE GATHER_CHANGE_STATS (
2 estimate_percent NUMBER DEFAULT 30,
3 change_percent NUMBER DEFAULT 10,
4 force BOOLEAN DEFAULT TRUE
5 )
6 --force false: don't gather when cbo is disable
7 IS
8 cbo_enable VARCHAR(3);
9 BEGIN
10 --check cbo flag
11 IF force = FALSE THEN
12 SELECT VALUE INTO cbo_enable FROM SYS.DV_PARAMETERS WHERE NAME='CBO';
13 IF UPPER(cbo_enable) = 'OFF' THEN
14 RETURN;
15 END IF;
16 END IF;
17
18 --flush modification to table
19 DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO();
20
21 --gather the table changed
22 FOR ITEM IN (SELECT A.OWNER, A.TABLE_NAME
23 FROM DBA_TABLES A, DBA_TAB_MODIFICATIONS B
24 WHERE A.PARTITIONED = 0 AND A.OWNER = B.TABLE_OWNER AND
A.TABLE_NAME=B.TABLE_NAME
25 AND( A.NUM_ROWS is null or
26 ((NVL(B.INSERTS, 0) + NVL(B.UPDATES, 0) + NVL(B.DELETES, 0))>= (CHANGE_PERCENT *
A.NUM_ROWS/100))))
27 LOOP
28 BEGIN
29 DBMS_STATS.GATHER_TABLE_STATS(ITEM.OWNER, ITEM.TABLE_NAME, NULL,
estimate_percent);
30 EXCEPTION
31 WHEN OTHERS THEN
32 NULL;
33 END;
34 END LOOP;
35
36 --temp table without statistic will gather at the first time
37 FOR ITEM IN (SELECT OWNER, TABLE_NAME FROM DBA_TABLES WHERE PARTITIONED = 0
AND TABLE_TYPE <> 'HEAP' AND LAST_ANALYZED IS NULL) LOOP
38 BEGIN
39 DBMS_STATS.GATHER_TABLE_STATS(ITEM.OWNER, ITEM.TABLE_NAME, null,
estimate_percent);
40 EXCEPTION
41 WHEN OTHERS THEN
42 NULL;
43 END;
44 END LOOP;
45

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 251


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

45 rows fetched.

GET_TAB_PARALLEL
Syntax:
select * from table(get_tab_parallel(param1, param2))

Purpose: Obtains the group information for parallel scanning.


Note:
● param1: table name
● param2: Degree of parallelism. The value range is [1,16].
● PART_ID: Returned table partition number. The value -1 is returned for an
ordinary table.
● BEG: begin pageid in the returned group information
● END: end pageid in the returned group information
Example:
select * from table(get_tab_parallel('tab1', 4));

PART_ID BEG END


------------ -------------------- --------------------
-1 12884901892 12884902266
-1 12884902267 12884902641
-1 12884902642 12884903018
-1 12884903019 4393751543808

4 rows fetched.

GET_TAB_ROWS
Syntax:
select * from table(get_tab_rows(param1, param2,param3,param4,param5,param6));

Purpose: Directly obtains original row records from the storage engine.
Note:
● param1: table name
● param2: table partition number. The value –1 is used for an ordinary table.
● param3: SCN ID
● param4: Matching condition. If no conditions are specified, the value NULL is
used.
● param5: start pageid
● param6: end pageid
Example:
select * from table(get_tab_rows('tab1', -1, 'NULL', 1641400608411649, 12884903244,4393751543808));

C1 C2 NAME
------------ ------------ ------------------------------
0 23454 12334546
1 23454 12334546
2 23454 12334546

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 252


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3 23454 12334546
4 23454 12334546
5 23454 12334546
6 23454 12334546
7 23454 12334546
8 23454 12334546
9 23454 12334546
10 23454 12334546
11 23454 12334546
12 23454 12334546
13 23454 12334546
14 23454 12334546
15 23454 12334546
...

PARALLEL_SCAN
Syntax:
select * from table(parallel_scan(param1,param2,param3,param4,param5));

Purpose: Scans table data in parallel.


Note:
● param1: table name
● param2: SCN ID
● param3: start pageid
● param4: end pageid
● param5: Table partition number. The value -1 is used for an ordinary table.
Example:
select * from table(parallel_scan('tab1', 1641400608411649, 12884903244,4393751543808,-1));

C1 C2 NAME
------------ ------------ ------------------------------
213 23454 12334546
214 23454 12334546
215 23454 12334546
216 23454 12334546
217 23454 12334546
218 23454 12334546
219 23454 12334546
220 23454 12334546
221 23454 12334546
222 23454 12334546
223 23454 12334546
0 23454 12334546
1 23454 12334546
2 23454 12334546
3 23454 12334546
4 23454 12334546
5 23454 12334546
6 23454 12334546
7 23454 12334546
...

3.5.9 Other Functions


BIN2HEX
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 253


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

BIN2HEX(expr)

Purpose: Converts data of the following types to hexadecimal numbers (with 0x).

Data Type Description

GS_TYPE_CHAR Char type

GS_TYPE_VARCHAR Varchar type

GS_TYPE_STRING String type MD

GS_TYPE_VARBINARY Varbinary type

GS_TYPE_BINARY Binary type

GS_TYPE_RAW Raw type

Example:
Convert the binary string 'A123' to a hexadecimal number.
SELECT BIN2HEX('A123') from SYS_DUMMY;

BIN2HEX('A123')
---------------
0x41313233

1 rows fetched.

CHAR_LENGTH
Syntax:
CHAR_LENGTH(str)

Purpose: Returns the length of a string.


● str must be enclosed in single quotation marks (' ').
● If the input parameter is a number, it is implicitly converted to a string. The
number cannot exceed 40 digits (the maximum conversion length), or the
result may be incorrect.
Example:
Return the length of the string 'character'.
SELECT CHAR_LENGTH('character') FROM SYS_DUMMY;

CHAR_LENGTH('CHARACTER')
------------------------
9

1 rows fetched.

COALESCE
Syntax:
COALESCE ( expression, expression [ , ...] )

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 254


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Purpose: Returns the first not-null expression in the input parameter.

expression can be any expression.


Note: If all parameters are NULL, COALESCE returns NULL.

Example:

Returns the first not-null expression.


SELECT COALESCE( NULL, 34, 13, 0 );

COALESCE( NULL, 34, 13, 0 )


---------------------------
34

1 rows fetched.

CONNECTION_ID
Syntax:
CONNECTION_ID()

Purpose: Returns the ID of the session corresponding to the current connection.

Note:

● The session IDs of all concurrent connections at the same time are different.
● Note that if a connection is disconnected and the corresponding session is
reused by a new connection, the corresponding session ID is also reused.

Example:

Return the ID of the currently connected session.


SELECT CONNECTION_ID() from SYS_DUMMY;

CONNECTION_ID()
---------------
48

1 rows fetched.

TYPE_ID2NAME
Syntax:
TYPE_ID2NAME(data_type_id)

Purpose: Returns the data type name corresponding to the data type ID.

Note:

● This function is a diagnosis function. If the data type ID does not exist,
UNKNOWN_TYPE is returned.
● data_type_id is the data type ID. The mapping is as follows.
data_type_id data_type_name

20001 BINARY_INTEGER

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 255


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

data_type_id data_type_name

20002 BINARY_BIGINT

20003 BINARY_DOUBLE

20004 NUMBER

20005 DECIMAL

20006 DATE

20007 TIMESTAMP

20008 CHAR

20009 VARCHAR

20010 VARCHAR

20011 BINARY

20012 VARBINARY

20013 CLOB

20014 BLOB

20015 CURSOR

20016 COLUMN

20017 BOOLEAN

20018 TIMESTAMP_TZ

20019 TIMESTAMP_LTZ

20020 INTERVAL

20021 INTERVAL YEAR TO MONTH

20022 INTERVAL DAY TO SECOND

20023 RAW

20024 IMAGE

20025 INTEGER UNSIGNED

20026 BIGINT UNSIGNED

20027 SMALLINT

20028 SMALLINT UNSIGNED

20029 TINYINT

20030 TINYINT UNSIGNED'

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 256


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example:
Return the data type name corresponding to the data type ID.
select TYPE_ID2NAME(20029);

TYPE_ID2NAME(20029)
----------------------------------------------------------------
TINYINT

1 rows fetched.

DECODE_NAME
Syntax:
DECODE_NAME(INDEX_NAME)

Purpose: Removes the OID part of the same indexes or constraints. This function
is not enabled for now.

FOUND_ROWS
Syntax:
FOUND_ROWS()

Purpose: Returns a SELECT statement with the LIMIT clause that is executed to
filter a part of the result and to know the number of rows of the complete result
set (that contains the results filtered by LIMIT).
Note:
● If FOUND_ROWS() is invoked after a SELECT statement that does not specify
SQL_CALC_FOUND_ROWS is executed, the number of rows returned by
FOUND_ROWS() is the number of records in the result set returned by the
SELECT statement. The number of rows that are filtered by the LIMIT clause
are not included.
● For UNION, UNION ALL, or MINUS statements, FOUND_ROWS() affects only
the global LIMIT clause. The LIMIT statements in SELECT subsets are not
affected.
● Before the FOUND_ROWS() function is executed, if the SELECT statement has
not been executed or failed to be executed, or if an update statement has
been executed, the FOUND_ROWS() function returns an undefined value.
Generally, the value 0 is returned.
Example:
Return the number of employees whose staff_id is greater than 1.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Search for employees whose staff_id is greater than 1.


SELECT * FROM employee where staff_id>1;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 257


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

STAFF_ID FIRST_NAME
------------ ----------------------------------------------------------------
2 Jack
3 Brown

2 rows fetched.
-- Return the number of rows that meet the condition.
SELECT FOUND_ROWS();

FOUND_ROWS()
--------------------
2

1 rows fetched.

GET_DISTRIBUTE_STR
This function is used only in distributed scenarios. In a standalone scenario, the
returned result is empty.

GET_LOCK
Syntax:
GET_LOCK(name_expr [, timeout_expr])

Purpose: Obtains an advisory lock named name_expr for a session. If another


session invokes GET_LOCK() and attempts to obtain a lock with the same name, it
waits for the number of seconds specified by timeout_expr. If the first session
releases the lock during this period, the second session can obtain the lock
successfully. If the first session does not release the lock after the specified
timeout seconds, the second session fails to obtain the lock.
The return values of GET_LOCK() are as follows:
● 1: The lock is obtained successfully.
● 0: Failed to obtain the lock.
The lock obtained through GET_LOCK() can be released in either of the following
ways:
● Explicit release: The lock is released by invoking RELEASE_LOCK().
● Implicit release: When a session is interrupted (normally or abnormally), the
lock occupied by the session is automatically released.
Note:
● The length of the name_expr calculation result cannot exceed 64 bytes.
● A maximum of 32 locks can be added to a session.
● The same lock can be locked for multiple times in the same session. In this
case, you need to unlock the same lock name for the same number of times.
If the same lock name is used for locking for multiple times, since its second
lock, the number of lock times is not counted into the 32 locks mentioned
above.
● If timeout_expr is not specified or is set to a negative value, GET_LOCK() will
wait until the lock is obtained.
Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 258


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Lock a column in the table.


-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Lock the staff_id column.


SELECT GET_LOCK('staff_id',5);

GET_LOCK('STAFF_ID',5)
--------------------
1

1 rows fetched.

TRY_GET_LOCK
Syntax:
TRY_GET_LOCK(name_expr)

Purpose: TRY_GET_LOCK(name_expr) attempts to obtain an exclusive advisory


lock named name_expr for a session. If the lock is obtained, TRUE is returned.
Later, if another session invokes TRY_GET_LOCK(name_expr) and attempts to
obtain the lock with the same name, FALSE is returned immediately, and the lock
with the same name fails to be obtained until the lock is released.
The return values of TRY_GET_LOCK() are as follows:
● TRUE: The lock is obtained successfully.
● FALSE: Failed to obtain the lock.
The lock obtained through TRY_GET_LOCK(name_expr) can be released in either
of the following ways:
● Explicit release: The lock is released by invoking RELEASE_LOCK().
● Implicit release: When a session is interrupted (normally or abnormally), the
lock occupied by the session is automatically released.
Note:
● The length of the name_expr calculation result cannot exceed 64 bytes.
● A maximum of 32 locks can be added to a session.
● The same lock can be locked for multiple times in the same session. In this
case, you need to unlock the same lock name for the same number of times.
If the same lock name is used for locking for multiple times, since its second
lock, the number of lock times is not counted into the 32 locks mentioned
above.
Example:
Lock a column in the table.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 259


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create the employee table.


CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Lock the staff_id column.


SELECT TRY_GET_LOCK('staff_id');

TRY_GET_LOCK('STAFF_ID')
--------------------
TRUE

1 rows fetched.

GET_SHARED_LOCK
Syntax:
GET_SHARED_LOCK(name_expr [, timeout_expr])

Purpose: GET_SHARED_LOCK() obtains a shared advisory lock named name_expr


for a session. A later session can also invoke GET_SHARED_LOCK() to obtain the
lock. If the lock has been used by another session as an exclusive advisory lock,
the later session waits for the period of time specified by timeout_expr. During this
period, if the exclusive lock is released or is used only in the current session, the
lock is successfully obtained. If lock is not released, it fails to be obtained.

The return values of GET_SHARED_LOCK() are as follows:

● TRUE: The lock is obtained successfully.


● FALSE: Failed to obtain the lock.

The lock obtained through GET_SHARED_LOCK() can be released in either of the


following ways:

● Explicit release: The lock is released by invoking


RELEASE_SHARED_LOCK(name_expr).
● Implicit release: When a session is interrupted (normally or abnormally), the
lock occupied by the session is automatically released.

Note:

● The length of the name_expr calculation result cannot exceed 64 bytes.


● A maximum of 32 locks can be added to a session.
● The same lock can be locked for multiple times in the same session. In this
case, you need to unlock the same lock name for the same number of times.
If the same lock name is used for locking for multiple times, since its second
lock, the number of lock times is not counted into the 32 locks mentioned
above.
● If timeout_expr is not specified or is set to a negative value,
GET_SHARED_LOCK() will wait until the lock is obtained.
● When TRY_GET_SHARED_LOCK(name_expr) attempts to obtain a session-level
shared advisory lock named name_expr, it returns the result immediately
regardless of whether lock is successfully obtained or not.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 260


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example:
Lock a column in the table.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;
-- Lock the staff_id column.
SELECT GET_SHARED_LOCK('staff_id',5);

GET_SHARED_LOCK('STAFF_ID',5)
--------------------
TRUE

1 rows fetched.

GET_XACT_LOCK
Syntax:
GET_XACT_LOCK(name_expr)

Purpose: GET_XACT_LOCK(name_expr) attempts to obtain an exclusive advisory


lock named name_expr for a transaction. If the lock is obtained, TRUE is returned.
Later, if another transaction invokes TRY_GET_LOCK(name_expr) and attempts to
obtain the lock with the same name, it will wait until the lock is released.
The return values of GET_XACT_LOCK(name_expr) are as follows:
● TRUE: The lock is obtained successfully.
● FALSE: Failed to obtain the lock.
The lock obtained through GET_XACT_LOCK(name_expr) can be released in the
following ways:
● Implicit release: When a transaction or session is interrupted (normally or
abnormally), the lock occupied by the transaction or session is automatically
released.
Note:
● The length of the name_expr calculation result cannot exceed 64 bytes.
● A maximum of 32 locks can be added to a transaction.
● A transaction can be locked by locks with the same name for multiple times.
When a transaction or session ends, the locks are automatically released. You
do not need to explicitly release them. If the same lock name is used for
locking for multiple times, since its second lock, the number of lock times is
not counted into the 32 locks mentioned above.
Example:
Lock a column in the table.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 261


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create the employee table.


CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Lock the staff_id column.


SELECT GET_XACT_LOCK('staff_id');

GET_XACT_LOCK('STAFF_ID')
--------------------
TRUE

1 rows fetched.

TRY_GET_XACT_LOCK
Syntax:
TRY_GET_XACT_LOCK(name_expr)

Purpose: TRY_GET_XACT_LOCK(name_expr) attempts to obtain an exclusive


advisory lock named name_expr for a transaction. If the lock is obtained, TRUE is
returned. Later, if another transaction invokes TRY_GET_LOCK(name_expr) and
attempts to obtain the lock with the same name, FALSE is returned immediately,
and the lock with the same name fails to be obtained until the lock is released.

The return values of TRY_GET_XACT_LOCK() are as follows:

● TRUE: The lock is obtained successfully.


● FALSE: Failed to obtain the lock.

The lock obtained through TRY_GET_XACT_LOCK(name_expr) can be released in


the following way:

● Implicit release: When a transaction or session is interrupted (normally or


abnormally), the lock occupied by the transaction or session is automatically
released.

Note:

● The length of the name_expr calculation result cannot exceed 64 bytes.


● A maximum of 32 locks can be added to a transaction.
● A transaction can be locked by locks with the same name for multiple times.
When a transaction or session ends, the locks are automatically released. You
do not need to explicitly release them. If the same lock name is used for
locking for multiple times and the first lock is successfully added, since its
second lock, the number of lock times is not counted into the 32 locks
mentioned above.

Example:

Lock a column in the table.


-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 262


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Lock the staff_id column.


SELECT TRY_GET_XACT_LOCK('staff_id');

TRY_GET_XACT_LOCK('STAFF_ID')
--------------------
TRUE

1 rows fetched.

GET_XACT_SHARED_LOCK
Syntax:
GET_XACT_SHARED_LOCK(name_expr [, timeout_expr])

Purpose: GET_XACT_SHARED_LOCK(name_expr[, timeout_expr]) obtains a shared


advisory lock named name_expr for a transaction. If the lock is obtained
successfully, TRUE is returned. A later transaction can also invoke
GET_XACT_SHARED_LOCK(name_expr) to obtain the same lock. If the lock has
been used by another transaction as an exclusive advisory lock, the later session
waits for the number of seconds specified by timeout_expr. During this period, if
the exclusive lock is released, the later session successfully obtains the lock.
Otherwise, the lock fails to be obtained.
The return values of GET_XACT_SHARED_LOCK(name_expr[, timeout_expr]) are as
follows:
● TRUE: The lock is obtained successfully.
● FALSE: Failed to obtain the lock.
The lock obtained through GET_XACT_SHARED_LOCK(name_expr[, timeout_expr])
can be released in the following way:
● Implicit release: When a transaction or session is interrupted (normally or
abnormally), the lock occupied by the transaction or session is automatically
released.
● When TRY_GET_XACT_SHARED_LOCK(name_expr) attempts to obtain a
shared advisory lock named name_expr, it returns the result immediately
regardless of whether lock is successfully obtained or not.
Note:
● The length of the name_expr calculation result cannot exceed 64 bytes.
● A maximum of 32 locks can be added to a transaction.
● A transaction can be locked by locks with the same name for multiple times.
When a transaction or session ends, the locks are automatically released. You
do not need to explicitly release them. If the same lock name is used for
locking for multiple times, since its second lock, the number of lock times is
not counted into the 32 locks mentioned above.
Example:
Lock a column in the table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 263


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the employee table.


DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;

-- Lock the staff_id column.


SELECT GET_XACT_SHARED_LOCK('staff_id',5);

GET_XACT_SHARED_LOCK('STAFF_ID',5)
--------------------
TRUE

1 rows fetched.

GREATEST
Syntax:
GREATEST( expr1 [, expr2, ... expr_n] )

Purpose: Returns the maximum value in one or more expressions.


● The return value type is the same as the parameter type of expr1.
● expr1 indicates whether the first expression to be evaluated is the largest.
● expr2, ... expr_n is optional. It specifies other expressions to be evaluated.
Example 1:
SELECT GREATEST(2, 5, 12, 3);

GREATEST(2, 5, 12, 3)
---------------------
12

1 rows fetched.

Example 2:
SELECT GREATEST('2', '5', '12', '3');

GREATEST('2', '5', '12', '3')


-----------------------------
5

1 rows fetched.

Example 3:
SELECT GREATEST('apples', 'oranges', 'bananas');

GREATEST('APPLES', 'ORANGES', 'BANANAS')


----------------------------------------
oranges

1 rows fetched.

Example 4:
SELECT GREATEST('apples', 'applis', 'applas');

GREATEST('APPLES', 'APPLIS', 'APPLAS')

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 264


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

--------------------------------------
applis

1 rows fetched.

ISNUMERIC
Syntax:
ISNUMERIC(str)

Purpose: Checks whether the input parameter str can be converted to a number. If
it can, 1 is returned. If it cannot, 0 is returned.
Note:
● The input parameter is a numeric string or a character string.
● The input parameter cannot be $.
Example 1:
SELECT ISNUMERIC('1' + 0) from SYS_DUMMY;

ISNUMERIC('1' + 0)
---------------------
1

1 rows fetched.

Example 2:
SELECT ISNUMERIC('a' || '1') from SYS_DUMMY;

ISNUMERIC('A' || '1')
---------------------
0

1 rows fetched.

LAST_INSERT_ID
Syntax:
LAST_INSERT_ID([expr])

Purpose:
1. If the parameter is empty, the function returns the value automatically
generated in the AUTO_INCREMENT column of the last INSERT statement in
the current session.
2. If the expr parameter is specified, the function returns the value of the
parameter and uses it as the next value returned by LAST_INSERT_ID().
Example:
Return the value automatically generated in the AUTO_INCREMENT column of
the last INSERT statement.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,first_name
VARCHAR(10));

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 265


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Insert data.
INSERT INTO employee VALUES (NULL, 'Bob');
INSERT INTO employee VALUES (NULL, 'BROWN');
INSERT INTO employee VALUES (NULL, 'ALICE');
-- Return the value automatically generated in the AUTO_INCREMENT column of the last INSERT
statement.
SELECT LAST_INSERT_ID();

LAST_INSERT_ID()
--------------------
3

1 rows fetched.

LEAST
Syntax:
LEAST( expr1 [, expr2, ... expr_n] )

Purpose: Returns the minimum value in one or more expressions.


● The return value type is the same as the data type of the minimum input
parameter expr_n.
● expr1 indicates whether the first expression to be evaluated is the smallest.
● expr2, ... expr_n is optional. It specifies other expressions to be evaluated.
Example 1:
SELECT LEAST(2, 5, 12, 3);

LEAST(2, 5, 12, 3)
------------------
2

1 rows fetched.

Example 2:
SELECT LEAST('apples', 'oranges', 'bananas');

LEAST('APPLES', 'ORANGES', 'BANANAS')


-------------------------------------
apples

1 rows fetched.

Example 3:
SELECT LEAST('apples', 'applis', 'applas');

LEAST('APPLES', 'APPLIS', 'APPLAS')


-----------------------------------
applas

1 rows fetched.

MD5
Syntax:
md5([expr])

Purpose: The MD5 function encrypts the input parameter expr based on the MD5
algorithm and outputs the encrypted text.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 266


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● If this parameter is set to NULL, NULL is returned.


● If expr is specified, the MD5 value of expr is returned.
Example:
-- Encrypt the string gauss according to the MD5 algorithm.
select md5('gauss') from SYS_DUMMY;

MD5('GAUSS')
--------------------------------
710a4950250286365cf841f765a790f1

1 rows fetched.
-- Create the t_md5_test table.
create table t_md5_test(f1 int,f2 real,f3 blob,f4 numeric(4,1),f5 varchar(10));

Succeed.
-- Insert data into the t_md5_test table.
insert into t_md5_test values(2147483648-1,2.345,'100100111111',2.345,'aabbcc');

1 rows affected.
-- Encrypt data columns f1, f2, f3, f4, and f5 in the table.
select md5(f1),md5(f2),md5(f3),md5(f4),md5(f5) from t_md5_test;
MD5(F1) MD5(F2) MD5(F3) MD5(F4)
MD5(F5)
-------------------------------- -------------------------------- --------------------------------
-------------------------------- --------------------------------
c588c0a459f4ccc6f3dd26518d24707a 972da5c9c62440f43c8ad9c672e8bf36
3c96ce254c3e76d02e6959f19609c6dc 1a18da63cbbfb49cb9616e6bfd35f662
61a60170273e74a5be90355ffe8e86ad

1 rows fetched.

OBJECT_ID
Syntax:
OBJECT_ID(expr[, object_type [, object_owner]])

Purpose: Based on the specified database object name (the first parameter),
database object type, and object owner, returns the OBJECT_ID of the database
object that meets specified conditions in the USER_OBJECTS view. If no owners
are specified, the function searches for the database objects owned by the user of
the current session. If no required database objects are found, NULL is returned.
Note:
In the current version, the following database objects can be specified:
● TABLE (default)
● VIEW
● DYNAMIC VIEW
● PROCEDURE
● TRIGGER
● FUNCTION
In addition, because the database object in GaussDB 100 does not have a globally
unique identifier, the returned OBJECT_ID cannot be globally unique. The value
must be unique in the specified database object type.
Example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 267


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Create a table and query the OBJECT_ID of the table.


-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;
-- Query the OBJECT_ID of employee.
SELECT OBJECT_ID('employee','TABLE');

OBJECT_ID('EMPLOYEE','TABLE')
-----------------------------
2070

1 rows fetched.

RELEASE_LOCK
Syntax:
RELEASE_LOCK(name_expr)

Purpose: Obtains the lock of the GET_LOCK() function before releasing the session
by specifying the lock name.

The return values of RELEASE_LOCK() are as follows:

● 1: The specified lock is obtained successfully.


● NULL: The current session does not occupy the specified lock.

Example:

Lock a column in the table and unlock it.


-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id INT NOT NULL, first_name VARCHAR(64));
-- Insert data.
INSERT INTO employee(staff_id,first_name) values ('1', 'Alice');
INSERT INTO employee(staff_id,first_name) values ('2', 'Jack');
INSERT INTO employee(staff_id,first_name) values ('3', 'Brown');
-- Commit the transaction.
COMMIT;
-- Lock the staff_id column.
SELECT GET_LOCK('staff_id',5);

GET_LOCK('STAFF_ID',5)
----------------------
1

1 rows fetched.
-- Unlock the staff_id column.
SELECT RELEASE_LOCK('staff_id');

RELEASE_LOCK('STAFF_ID')
----------------------
1

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 268


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

ROW_NUMBER() OVER
Syntax:
ROW_NUMBER() OVER (partition by expr order by expr)

Purpose: The function can be used only in a column list. It groups and sort data
returned by the query, and then number the data by group.
Example:
The salary level of each department is displayed according to the department
group.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;

-- Create the employee table.


CREATE TABLE employee (staff_id INT,section_id INT,max_salary NUMBER(10,2));
-- Insert data.
INSERT INTO employee values(1,10,5500.00);
INSERT INTO employee values(2,10,4500.00);
INSERT INTO employee values(3,20,1900.00);
INSERT INTO employee values(4,20,4800.00);
INSERT INTO employee values(5,40,6500.00);
INSERT INTO employee values(6,40,14500.00);
INSERT INTO employee values(7,40,44500.00);
-- Commit the transaction.
COMMIT;
-- Query employee salaries by department and sort them.
SELECT *, Row_Number() OVER (partition by section_id ORDER BY max_salary desc) rank FROM employee;

STAFF_ID SECTION_ID MAX_SALARY RANK


------------ ------------ ---------------------------------------- ------------
1 10 5500 1
2 10 4500 2
4 20 4800 1
3 20 1900 2
7 40 44500 1
6 40 14500 2
5 40 6500 3

7 rows fetched.

SCN2DATE
Syntax:
SCN2DATE(scn)

Purpose: The value is converted from the scn value to a time value.
Note:
● The value of scn must be valid. You can obtain the value by querying related
views of the object.
Example:
Return the time value corresponding to the value of scn.
select scn2date(t.org_scn) from sys.SYS_TABLES t where t.name = 'TEST';

SCN2DATE(T.ORG_SCN)
----------------------
2019-01-10 20:35:38

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 269


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

1 rows fetched.

SERIAL_LASTVAL
Syntax:
SERIAL_LASTVAL('OWNER','TABLE_NAME')

Purpose: Returns the cache value of the auto-increment column of the table.
● OWNER is the owner of the table.
● TABLE_NAME is the table name.
Note:
● OWNER and TABLE_NAME must be capitalized and must be enclosed in
quotation marks.
● If the table does not contain any auto-increment columns, the function
returns the following error:
GS-00866, the table has no auto increment column.

Example:
Returns the cache value of the AUTO_INCREMENT column of the employee
table.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee (staff_id INT AUTO_INCREMENT primary key ,section_id INT,max_salary
NUMBER(10,2)) AUTO_INCREMENT 1000;
-- Return the cache value of the auto-increment column in the employee table.
SELECT SERIAL_LASTVAL('SYS','EMPLOYEE');

SERIAL_LASTVAL('SYS','EMPLOYEE')
--------------------
1000

1 rows fetched.

SHA

This function is not recommended in security scenarios.

Syntax:
SHA(str_expr)

Purpose: Generates a fixed-length hash value for the input parameter by using
the SHA algorithm and returns the hash value in string format (40 bytes). This
function is an alias of the SHA1 function and their usage are the same.
Note:
● str_expr is a string expression. If the length exceeds 8000, an error is reported.
● If the input value is NULL, NULL is returned.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 270


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example:
Return the hash value of abc.
SELECT SHA('abc');

SHA('ABC')
--------------------
A9993E364706816ABA3E25717850C26C9CD0D89D

1 rows fetched.

SHA1

This function is not recommended in security scenarios.

Syntax:
SHA1(str_expr)

Purpose: Generates a fixed-length hash value for the input parameter by using
the SHA1 algorithm and returns the hash value in string format (40 bytes).
Note:
● str_expr is a string expression. If the length exceeds 8000, an error is reported.
● If the input value is NULL, NULL is returned.
Example:
Return the hash value of abc.
SELECT SHA1('abc');

SHA1('ABC')
--------------------
A9993E364706816ABA3E25717850C26C9CD0D89D

1 rows fetched.

SOUNDEX
Syntax:
SOUNDEX(expr)

Purpose: Returns the sound representation of a string parameter.


Example:
Return the name of the employee whose surname is pronounced as SMYTHE.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;

-- Create the employee table.


CREATE TABLE employee (last_name varchar(20) ,first_name varchar(20));
-- Insert data.
INSERT INTO employee(last_name,first_name) values('Smith','Lindsey');
INSERT INTO employee(last_name,first_name) values('Smith','William');
INSERT INTO employee(last_name,first_name) values('Brown','Bill');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 271


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Search for the name of the employee whose surname is pronounced as SMYTHE.
SELECT last_name, first_name
FROM employee
WHERE SOUNDEX(last_name)
= SOUNDEX('SMYTHE')
ORDER BY last_name, first_name;

LAST_NAME FIRST_NAME
-------------------- --------------------
Smith Lindsey
Smith William

2 rows fetched.

SYS_CONTEXT
Syntax:
SYS_CONTEXT(namespace_expr, parameter_expr [, length])

Purpose: Returns the value of the configuration parameter (parameter) in the


context associated with the specified namespace.
The namespace and parameters supported in the current version are as follows:
Namespace name: USERENV. Supported parameters include:
● SID: Session ID corresponding to the current connection. Similar to
CONNECTION_ID(), if a session is used by a new connection after the
previous connection is disconnected, its corresponding session ID is also
reused.
● TERMINAL: host name of the client of the current session
● CURRENT_SCHEMA: default schema name of the current query
● CURRENT_SCHEMAID: default schema ID of the current query
● DB_NAME: name of the current database
● OS_USER: OS username of the client that is currently connected
Note:
● namespace_expr and parameter_expr must be expressions that can be
converted to strings.
● The return value type is a string. The default length is 256 bytes. The overlong
part is truncated.
● The third parameter length indicates the maximum length of the value
returned by the function. length must be an expression that can be implicitly
converted into the INTEGER type. The valid length of the length field is 1–
4000. If the specified length is not within this range, the default length 256
bytes is used.
Example 1:
Return the current session ID.
SELECT SYS_CONTEXT('USERENV', 'SID') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'SID')
----------------------------------------------------------------
49

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 272


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Example 2:
Return the host name of the client machine of the current session.
SELECT SYS_CONTEXT('USERENV', 'TERMINAL') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'TERMINAL')
----------------------------------------------------------------
127.0.0.1

1 rows fetched.

Example 3:
Return the default schema name of the current query.
SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')
----------------------------------------------------------------
gaussdba

1 rows fetched.

Example 4:
Return the default schema ID of the current query.
SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMAID') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'CURRENT_SCHEMAID')
----------------------------------------------------------------
2

1 rows fetched.

Example 5:
Return the name of the current database.
SELECT SYS_CONTEXT('USERENV', 'DB_NAME') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'DB_NAME')
----------------------------------------------------------------
GaussDB

1 rows fetched.

Example 6:
Return the OS username of the client that is currently connected.
SELECT SYS_CONTEXT('USERENV', 'OS_USER') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'OS_USER')
----------------------------------------------------------------
gaussdba

1 rows fetched.

SYS_GUID
Syntax:
SYS_GUID()

Purpose: Generates a 16-byte global unique identifier. The return value type is
BINARY.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 273


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Note: To receive the SYS_GUID() result with a string type column, because the
binary byte is converted into a string in hexadecimal representation, you need to
define the column as 32 bytes or larger.

The features of the SYS_GUID function are the same as UUID. The differences are
as follows:

● The SYS_GUID function is used in versions earlier than GaussDB 100


V300R001C00SPC200.
● The UUID function is used in GaussDB 100 V300R001C00SPC200 and later.

Example:

Create a table and use the globally unique ID as the primary key.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;
-- Create the employee table.
CREATE TABLE employee(staff_id raw(16) default sys_guid() primary key, first_name VARCHAR(32));
-- Insert data.
INSERT INTO employee(first_name) values ( 'GREECE ');
INSERT INTO employee(first_name) values ( 'ALAN');
INSERT INTO employee(first_name) values ( 'FRANK ');
-- Commit the transaction.
COMMIT;
-- Query the table.
SELECT * FROM employee;

STAFF_ID FIRST_NAME
---------------------------------------------------------------- --------------------------------
B5E49C6E665846A9BF7F00794748AA50 GREECE
2698BC648AC247968DC987555DEAB179 ALAN
46540BE9789E4BF49D0EA87705A444CC FRANK

3 rows fetched.

UUID
Syntax:
UUID()

Purpose: Generates a 16-byte global unique identifier. The return value type is
BINARY.

Note: To receive the UUID() result with a string type column, because the binary
byte is converted into a string in hexadecimal representation, you need to define
the column as 32 bytes or larger.

The features of the UUID function are the same as SYS_GUID. The differences are
as follows:

● The SYS_GUID function is used in versions earlier than GaussDB 100


V300R001C00SPC200.
● The UUID function is used in GaussDB 100 V300R001C00SPC200 and later.

Example:

Create a table and use the globally unique ID as the primary key.
-- Delete the employee table.
DROP TABLE IF EXISTS employee;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 274


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create the employee table.


CREATE TABLE employee(staff_id raw(16) default uuid() primary key, first_name VARCHAR(32));
-- Insert data.
INSERT INTO employee(first_name) values ( 'GREECE ');
INSERT INTO employee(first_name) values ( 'ALAN');
INSERT INTO employee(first_name) values ( 'FRANK ');
-- Commit the transaction.
COMMIT;
-- Query the table.
SELECT * FROM employee;

STAFF_ID FIRST_NAME
---------------------------------------------------------------- --------------------------------
B5E49C6E665846A9BF7F00794748AA50 GREECE
2698BC648AC247968DC987555DEAB179 ALAN
46540BE9789E4BF49D0EA87705A444CC FRANK

3 rows fetched.

UPDATING
Syntax:
UPDATING(col_name)

Purpose: Used in the UPDATE trigger to determine whether the UPDATE


operation has been performed on the column.

Example:

Check whether the column of the trigger is updated. If it is, an exception is


thrown.
-- Delete existing tables named training.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Create a trigger named trigger_training.
CREATE OR REPLACE TRIGGER trigger_training BEFORE UPDATE ON training FOR EACH ROW AS
wrong_error exception;
errno NUMBER;
errmsg VARCHAR2(30);
BEGIN
IF UPDATING('course_name') THEN
errno := '-20030';
errmsg := 'cannot update this column';
RAISE wrong_error;
END IF;
EXCEPTION
WHEN wrong_error THEN
raise_application_error(errno,errmsg);
END;
/

USERENV
Syntax:
USERENV(parameter_expr)

Purpose: A downward compatible version of SYS_CONTEXT(). It returns the value


of the configuration parameter of the default namespace USERENV.

Parameters supported in the current version are as follows:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 275


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● SID: Session ID corresponding to the current connection. Similar to


CONNECTION_ID(), if a session is used by a new connection after the
previous connection is disconnected, its corresponding session ID is also
reused.
● TERMINAL: host name of the client of the current session
● CURRENT_SCHEMA: default schema name of the current query
● CURRENT_SCHEMAID: default schema ID of the current query
● DB_NAME: name of the current database
● OS_USER: OS username of the client that is currently connected
Note: parameter_expr must be an expression that can be converted to a string.
The return value type is a string with a maximum length of 256 bytes. The
overlong part is truncated.
Example 1:
Return the current session ID.
SELECT SYS_CONTEXT('USERENV', 'SID') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'SID')
----------------------------------------------------------------
49

1 rows fetched.

Example 2:
Return the host name of the client machine of the current session.
SELECT SYS_CONTEXT('USERENV', 'TERMINAL') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'TERMINAL')
----------------------------------------------------------------
127.0.0.1

1 rows fetched.

Example 3:
Return the default schema name of the current query.
SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')
----------------------------------------------------------------
gaussdba

1 rows fetched.

Example 4:
Return the default schema ID of the current query.
SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMAID') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'CURRENT_SCHEMAID')
----------------------------------------------------------------
2

1 rows fetched.

Example 5:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 276


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Return the name of the current database.


SELECT SYS_CONTEXT('USERENV', 'DB_NAME') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'DB_NAME')
----------------------------------------------------------------
GaussDB

1 rows fetched.

Example 6:
Return the OS username of the client that is currently connected.
SELECT SYS_CONTEXT('USERENV', 'OS_USER') FROM SYS_DUMMY;

SYS_CONTEXT('USERENV', 'OS_USER')
----------------------------------------------------------------
gaussdba

1 rows fetched.

VERSION
Syntax:
VERSION()

Purpose: Obtains the current version information.


Example:
Obtain the current version information.
SELECT VERSION();

VERSION()
--------------------------------------------------
GaussDB-100-V300R001C00B300 Release c87fe47

1 rows fetched.

VSIZE
Syntax:
VSIZE(expr)

Purpose: Returns the number of bytes occupied by the value of the specified
expression in GaussDB 100 storage.
Note:
● If the expression is NULL, the function returns NULL.
● This function does not support input parameter expressions of the CLOB type.
Example:
Return the number of bytes occupied by Alice in GaussDB 100 storage.
SELECT VSIZE('Alice') FROM SYS_DUMMY;

VSIZE('ALICE')
--------------------
5

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 277


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

1 rows fetched.

3.5.10 Window Functions


Syntax:
function_name over( [ partition by [expr1][ ,... ] ] [order by [expr2][ ,... ] [NULLS FIRST | LAST] ] )

Purpose: Performs calculation within a subset of the return result related to the
current rows.
function_name is a window function name. Currently, the following functions are
supported: LAG, MAX, MIN, ROW_NUMBER, STDDEV, STDDEV_POP,
STDDEV_SAMP, and SUM.
● partition by indicates data grouping. expr1 is the name of a column to be
grouped. order by indicates data sorting. expr2 is the name of a column to be
ordered.
● If function_name is set to ROW_NUMBER(), the partition by and order by
clauses cannot be omitted. Other functions can be omitted.
● For details about [NULLS FIRST | LAST], see •ORDER BY.
Examples:
Return the maximum salary in the staff table.
-- Delete the staffs table.
DROP TABLE IF EXISTS staffs;
-- Create the staffs table.
CREATE TABLE staffs
(
staff_id NUMBER(6) not null,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
);
-- Insert data.
insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2200.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2400.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (198, 'Donald', 'OConnell', 'DOCONNEL', '650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'),
'SH_CLERK', 2600.00, null, 124, 50);

insert into staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id, salary,
commission_pct, manager_id, section_id)
values (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844', to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK',
4000.00, null, 124, 50);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 278


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Return the maximum salary of the staff sorted by staff_ID.


select staff_ID, MAX(salary)over(partition by staff_ID order by staff_ID) from staffs;
STAFF_ID MAX(SALARY)OVER(PARTITION BY STAFF_ID ORDER BY STAFF_ID)
---------------------------------------- --------------------------------------------------------
198 2600
198 2600
198 2600
199 4000

3.6 Operators
During the compiling of SQL statements or the stored procedure, operators can be
used to process columns. Operators can be used to process one or more operands
and can be placed before, after, or between operands. Results are returned after
the processing.

3.6.1 Logical Operators


GaussDB 100 supports logic operations: AND, OR, and NOT.

● AND: The logic AND operation can be used in query conditions, such as
WHERE, ON, and HAVING.
● OR: The logic OR operation can be used in query conditions, such as WHERE,
ON, and HAVING.
● NOT: The NOT keyword can be added before the condition expression after
the WHERE or HAVING clause to reverse the condition result. This keyword is
used together with the relational operation, such as, NOT IN and NOT
EXISTS. The syntax is as follows:
select * from table where/having not {condition};

Table 3-12 lists operation rules, where a and b represent logical expressions.

Table 3-12 Operation rules

a b a AND b a OR b Result NOT a


Result Result

TRUE TRUE TRUE TRUE FALSE

TRUE FALSE FALSE TRUE FALSE

TRUE NULL NULL TRUE FALSE

FALSE FALSE FALSE FALSE TRUE

FALSE NULL NULL FALSE TRUE

NULL NULL NULL NULL NULL

3.6.2 Comparison Operators


Comparison operators are available for all data types and return Boolean values.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 279


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

All comparison operators are binary operators. Only data types that are the same
or can be implicitly converted can be compared using comparison operators.

Table 3-13 lists comparison operators provided by GaussDB 100.

Table 3-13 Comparison operators

Operators Function

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

= Equal to

<> or != Unequal

Comparison operators are available for all relevant data types. All comparison
operators are binary operators that returned values of Boolean type. Expressions
like 1 < 2 < 3 are invalid. (Because Boolean values cannot be compared with 3.)

3.6.3 Arithmetic Operators


An arithmetic operator is used for calculating numeric operands, such as plus,
minus, multiplication, and division.

Table 3-14 lists arithmetic operators supported by GaussDB 100.

Table 3-14 Arithmetic operators

Operator Description Example

+ Plus SELECT 2+3 AS RESULT FROM SYS_DUMMY;


RESULT
--------------------
5

1 rows fetched.

– Minus SELECT 2-3 AS RESULT FROM SYS_DUMMY;


RESULT
--------------------
-1

1 rows fetched.

* Multiply SELECT 2*3 AS RESULT FROM SYS_DUMMY;


RESULT
--------------------
6

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 280


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Operator Description Example

/ Divide (The result is not SELECT 4/2 AS RESULT FROM SYS_DUMMY;


RESULT
rounded.) --------------------
2

1 rows fetched.
SELECT 4/3 AS RESULT FROM SYS_DUMMY;
RESULT
--------------------
1.33333333333333

1 rows fetched.

% Modulo operation SELECT 20%6 AS RESULT FROM SYS_DUMMY;


RESULT
------------
2

1 rows fetched.

|| String concatenation SELECT '10001' || '011' AS RESULT FROM


SYS_DUMMY;
RESULT
--------
10001011

1 rows fetched.

| Bitwise OR SELECT '17' | '13' AS RESULT FROM SYS_DUMMY;


RESULT
--------------------
29

1 rows fetched.
Note: 17 (binary: 10001), 13 (binary:
01101), and the bitwise OR result is
11101 (29).

& Bitwise AND SELECT '17' & '13' AS RESULT FROM SYS_DUMMY;
RESULT
--------------------
1

1 rows fetched.
Note: 17 (binary: 10001), 13 (binary:
01101), and the bitwise AND result is
00001 (1).

^ Bitwise XOR SELECT '17' ^ '13' AS RESULT FROM SYS_DUMMY;


RESULT
--------------------
28

1 rows fetched.
Note: 17 (binary: 10001), 13 (binary:
01101), and the bitwise XOR result is
11100 (28).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 281


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Operator Description Example

<< Left shift SELECT 10<<2 AS RESULT FROM SYS_DUMMY;

RESULT
--------------------
40

1 rows fetched.
Note: 10. The left two bits are
equivalent to 10*4.

>> Right shift SELECT 10>>2 AS RESULT FROM SYS_DUMMY;

RESULT
--------------------
2

1 rows fetched.

● The priority sequence is: four arithmetic operations > left/right shift > bitwise AND>
bitwise XOR > bitwise OR.
● When bitwise operators are used for execution and if input parameter values have
decimal digits, the values will be first rounded off before participating in the bitwise
operation. In this scenario, if the BITOR, BITAND, and BITXOR functions are used, they
will round down the input parameter values and then perform bitwise operation.
● When the above operators are executed, a null string will be returned if the input
parameter values contain NULL.

3.6.4 Test Operators


GaussDB 100 supports the test operators listed in Table 3-15:

Table 3-15 Test operators

Operator Description

IN The element is in the specified collection.

NOT IN The element is not in the specified collection.

EXISTS An element that meets the search criteria


exists.

NOT EXISTS No element that meets the search criteria


exists.

BETWEEN...AND... Between the two, for example, a BETWEEN x


AND y is equivalent to a >= x and a <= y.

NOT BETWEEN...AND... Not between the two. For example, a NOT


BETWEEN x AND Y is equivalent to a < x or a
> y.

IS NULL The value is equal to NULL.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 282


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Operator Description

IS NOT NULL Value other than NULL

LIKE ...[ESCAPE char] Searching for rows matching the specified


pattern.
Only character types are supported.

NOT LIKE...[ESCAPE char] Searching for rows not matching the specified
pattern. Only character types are supported.

REGEXP The string matches the regular expression.


Only the STRING type is supported.

REGEXP_LIKE The string matches the regular expression


and supports the STRING and NUMBER types.
Syntax:
REGEXP_LIKE(str,pattern[,match_param])

● The input parameter str is a string that


requires regular processing. It supports the
STRING and NUMBER types.
● The input parameter pattern is the regular
expression for matching.
● The input parameter match_param
indicates the search mode (i indicates
case-insensitive search, and c indicates
case-sensitive search. The default value is
c). The default value is c. .
The return value of the expression is of the
BOOL type.

ANY One value in the subquery meets the


condition.

Example:
-- Create a table:
drop table if exists T_TEST_OPERATOR;
create table T_TEST_OPERATOR(ID int, NAME varchar(36));
-- Insert four records to the table:
insert into T_TEST_OPERATOR(ID,NAME) VALUES (1,'zhangsan');
insert into T_TEST_OPERATOR(ID,NAME) VALUES (2,'lisi');
insert into T_TEST_OPERATOR(ID,NAME) VALUES (3,'wangwu');
insert into T_TEST_OPERATOR(ID,NAME) VALUES (999,null);
commit;
-- IN operator
select * from T_TEST_OPERATOR where ID IN(1,2);
select * from T_TEST_OPERATOR where NAME IN('zhangsan');
-- NOT IN operator
select * from T_TEST_OPERATOR where ID NOT IN(1,2);
select * from T_TEST_OPERATOR where NAME NOT IN('zhangsan');
-- EXISTS operator
select count(1) from SYS_DUMMY where EXISTS(select ID from T_TEST_OPERATOR where
NAME='zhangsan');
-- NOT EXISTS operator
select count(1) from SYS_DUMMY where NOT EXISTS(select ID from T_TEST_OPERATOR where
NAME='zhangsan');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 283


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- BETWEEN...AND... operator
select * from T_TEST_OPERATOR where ID BETWEEN 1 AND 2;
-- NOT BETWEEN...AND... operator
select * from T_TEST_OPERATOR where ID NOT BETWEEN 1 AND 2;
-- IS NULL operator
select * from T_TEST_OPERATOR where NAME IS NULL;
-- IS NOT NULL operator
select * from T_TEST_OPERATOR where NAME IS NOT NULL;
-- LIKE ...[ESCAPE char] operator
select * from T_TEST_OPERATOR where NAME LIKE '%an%';
select * from T_TEST_OPERATOR where NAME LIKE '\%an%' ESCAPE '\';
-- NOT LIKE...[ESCAPE char] operator
select * from T_TEST_OPERATOR where NAME NOT LIKE '%an%';
select * from T_TEST_OPERATOR where NAME NOT LIKE '\%an%' ESCAPE '\';
-- REGEXP operator
select * from T_TEST_OPERATOR where NAME REGEXP '[a-z]*';
-- REGEXP_LIKE operator
select * from T_TEST_OPERATOR where REGEXP_LIKE (NAME ,'[a-z]*');
-- ANY operator
select * from T_TEST_OPERATOR where ID = ANY(1,3,5);
select * from T_TEST_OPERATOR where NAME = ANY('zhangsan');

3.6.5 Wildcard Characters


GaussDB 100 supports the following wildcard characters:
● %: The percent sign (%) indicates any number of characters, including no
characters, used in LIKE and NOT LIKE statements.
● _: The underscore (_) indicates an unknown character, which is used in LIKE
and NOT LIKE statements.

3.6.6 Other Operators


Quotation Marks
Currently, GaussDB 100 supports single quotation marks ('), double quotation
marks ("), and reverse quotation marks (`).
● Single quotation marks indicate the string type. If there is a single quotation
mark in the string text, you must enter two single quotation marks.
● Double quotation marks and reverse quotation marks indicate the name or
alias of an object, such as a table, column, or index. If an object name or alias
is not enclosed in double quotation marks or reverse quotation marks,
GaussDB 100 will process it in case-insensitive mode. Otherwise, the name or
alias in the quotation marks will be processed in case-sensitive mode. In
addition, keywords can be used as the object names or aliases.

3.7 Type Conversion


SQL statements can, intentionally or not, require the mixing of different data
types in the same expression, resulting in inconsistency of execution results.
GaussDB 100 can convert between different data types to ensure result
consistency.
Type conversion is performed in the following example:
-- Create the T_TEST_CAST table.
DROP TABLE IF EXISTS T_TEST_CAST;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 284


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

CREATE TABLE T_TEST_CAST(


SECTION_ID NUMBER(10) DEFAULT NULL,
SECTION_NAME VARCHAR2(100),
SECTION_DATE DATE
);
-- Insert data.
INSERT INTO T_TEST_CAST VALUES (1, 'Li Hong', '2018-01-07 17:18:18');
INSERT INTO T_TEST_CAST VALUES (2, 'Li Li', '2018-03-07 14:20:18');
INSERT INTO T_TEST_CAST VALUES (3, 'Zhang Gang', '2018-06-04 17:12:18');
-- String --> int
select cast('123123' as int) from SYS_DUMMY;
-- Update string column, but enter an integer
UPDATE T_TEST_CAST SET SECTION_NAME = 1000;
-- Insert the date field, but enter a string.
INSERT INTO T_TEST_CAST(SECTION_DATE) VALUES('2017-12-12 23:23:23');

However, not all data types can be converted to each other. For example, the
following SQL statement uses an integer column to update the value of the date
column. Such operations cannot be performed. SQL statements performing such
operations will be filtered out in validation or before execution.
UPDATE T_TEST_CAST SET SECTION_DATE = 1000;
GS-00606, [1:39]inconsistent datatypes, expected DATE - got BINARY_INTEGER

The following table lists the conversion relationships between different data types.
The first row in the table indicates the target conversion type, and the first column
indicates the source type. If the two types of conversion do not meet the
relationship in the table, an error indicating that the type does not match is
returned.

Table 3-16 Type conversion

Data Numeric String Date Binary Boolean Time


Type type Interval

Numeric √ √ × × Integer ×
(√)
The
value 0
indicates
false,
and
other
values 0
indicate
true.

String √ √ √ √ √ √

Date × √ √ × × ×
type

Binary × √ × √ × ×

Boolean √ √ × × √ ×
(Integer (String
0 or 1) TRUE or
FALSE)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 285


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Data Numeric String Date Binary Boolean Time


Type type Interval

Time × √ × × × √, but
interval INTERVA
type L YEAR
TO
MONTH
and
INTERVA
L DAY
TO
SECOND
cannot
be
converte
d to each
other.

For details about the conversion rules among preset data types and Boolean, see "Data
Dictionary and Views" in GaussDB 100 V300R001C00 Database Reference.

3.8 Type Mapping


GaussDB 100 supports data type mapping. Type mapping is used when the service
cannot modify the table definition. The database replaces the NUMBER type with
the required data type according to the user-defined rule.

Precautions
● The type mapping function is used only for executing tables or modifying
table definitions and executing DDL statements.
● The type mapping function takes effect only when USE_NATIVE_DATATYPE is
set to TRUE.
● After the mapping file is added or modified, the database restarts for the
modification to take effect.

Procedure
Step 1 Add the TYPE_MAP_FILE=<filename> configuration item to the zengine.ini file.

<filename> is a type mapping file. The default path is ${GSDB_DATA}/cfg. You


can also specify an absolute path.

Step 2 In the type mapping file, add a type mapping rule based on the user type.

The user name supports simple fuzzy match. The format of the type mapping file
is as follows:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 286


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

[username]
old_datatype=map_datatype
● Data type of the integer type. Automatic type mapping is supported. The
boundary value must be explicitly configured in the mapping rule file based
on the actual application scenario to enable the specified type mapping
capability.
● NUMBER(p,s) (s>0) data type. Because the precision is involved, the data type
needs to be configured by explicitly specifying the type mapping.
The following table describes the rule.

Table 3-17 Data mapping


Mapping Original Data Type Mapped Data Type
Mode

Automatic type NUMBER(p). The value TINYINT


mapping range of p is [1,2].

NUMBER(p), p=4 SMALLINT

NUMBER(p). The value INTEGER


range of p is [6,9].

NUMBER(p). The value BIGINT


range of p is [12,18].

Specified type NUMBER(p), p=3 TINYINT


mapping
NUMBER(p), p=5 SMALLINT

NUMBER(p), p=10 INTEGER

NUMBER(p), p=19 BIGINT

----End

Examples
Step 1 Add the TYPE_MAP_FILE configuration item to the zengine.ini file, and set the
mapping file address to export/app/data/cfg/type_map_file.ini.
vim zengine.ini
TYPE_MAP_FILE = /export/app/data/cfg/type_map_file.ini

Step 2 Modify the mapping file type_map_file.ini to specify the mapping type.
Configure a mapping plan for user1. Set NUMBER(3) to INTEGER and
NUMBER(11) to BIGINT.
Configure a mapping plan for user2. Set NUMBER(5) to INTEGER and
NUMBER(25,5) to DOUBLE.
vim zengine.ini
[user1]
number(3)=integer
number(11)=bigint
[user2]
number(5)=integer
number(25,5)=double

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 287


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Step 3 Restart the database for the mapping rule to take effect.

----End

3.9 Transaction Management


A transaction is a user-defined sequence of database operations, which form an
integral unit of work.

In transaction management, you can start, commit, and roll back transactions,
prepare two-phase commit, set the transaction isolation level, and create a save
point for a transaction.

Starting a Transaction
GaussDB 100 provides no statement to start a transaction. The first executable
SQL statement (except the login statement) indicates the start of a transaction.

Committing a Transaction
The COMMIT statement changes all operations in the work units of the current
transaction to be permanent and ends the transaction.

Table 3-18 SQL statements for committing a transaction

Function SQL Statement

Committing a transaction COMMIT

Rolling Back a Transaction


The ROLLBACK statement rolls back (cancel) all operations in the work units of
the current transaction and ends the transaction.

Table 3-19 SQL statements for rolling back a transaction

Function SQL Statement

Rolling back a transaction ROLLBACK

Implicitly Committing a Transaction


When a DDL statement is encountered, the database automatically commits the
previous transaction, and then starts a new transaction to execute the DDL
statement. This is referred to as implicit committing. The database automatically
commits the previous transaction when the following SQL statement is
encountered:

● CREATE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 288


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● ALTER
● TRUNCATE
● DROP
● GRANT
● REVOKE

3.10 Expressions
GaussDB 100 expressions include simple expressions and compound expressions.

3.10.1 SQL Expressions


An expression consists of one or more values, operators, and SQL functions.

Scenario
You can use expressions in:
● A select list of the SELECT statement, for example, SELECT expr from object.
● A condition specified by the WHERE or HAVING clause, for example, ...
WHERE expr1 = expr2 or WHERE expr IN (expr1, expr2, ...).
● The ORDER BY clause, for example, ...ORDER BY expr.
● The VALUES clause in the INSERT statement, for example, INSERT INTO
table VALUES(expr1, expr2, ...).
● The SET clause in the UPDATE statement, for example, UPDATE table SET
table_column1 = expr1, table_column2 = expr2,....

Data Types of Return Values


The return value data type of an expression usually depends on the data types of
its constituent parts.
For example, the following simple expression returns 8 with the data type
NUMERIC.
4+4

Use the following complex expression as another example. The expression adds
one day to the current date, converts the new timestamp into the CHAR data type
by invoking the TO_CHAR function, and finally returns a portion of the character
string by invoking the SUBSTR function. The return value is a string.
SUBSTR(TO_CHAR(SYSTIMESTAMP+1), 3)

3.10.2 Simple Expressions


A simple expression can contain a column name, pseudocolumn, constants,
reserved words, NULL, and sequences.

Syntax
{ [ query_name.
| [schema.] { table. | view. | materialized view. }

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 289


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

| t_alias.
] { column | ROWID }
| ROWNUM
| string
| number
| sequence. { CURRVAL | NEXTVAL }
| NULL
}

3.10.3 Compound Expressions


A compound expression specifies a combination of simple expressions and other
expressions.

Syntax
{ (expr)
| { + | - | PRIOR } expr
| expr { * | / | + | - | || | & | | | ^ } expr
}

● || is not Backus-Naur Form (BNF) syntax notation, but a part of the syntax. It indicates
serial operations.
● When || is used for serial operations, a maximum of 32767 bytes can be processed in
serial. The excessive bytes will be truncated.
● A constant expression (operands in the expression are constants), for example, 1 + 3, is
verified and calculated during SQL parsing. If the expression does not meet the
calculation rule, an error is reported immediately. For example, in the select 0/0 from
SYS_DUMMY; statement, the expression 0/0 does not meet the calculation rule (the
divisor cannot be 0). For higher performance, the error is reported immediately after the
verification during SQL parsing other than SQL execution.

3.10.4 CASE Expressions


A CASE expression operates like the C functions IF ELSEIF END and SWITCH CASE.

Syntax
CASE { simple_case_expression
| searched_case_expression
}
[else_clause]
END

● simple_case_expression:
expr { WHEN comparison_expr THEN return_expr } [ ... ]
● searched_case_expression:
{ WHEN condition THEN return_expr } [ ... ]

● else_clause:
ELSE else_expr

3.11 Data Query

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 290


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.11.1 Overview
A query is an operation that retrieves data from one or more tables or views.
Query is one of the basic applications of a database. GaussDB 100 provides
various query modes to meet application requirements.
This section describes different types of queries and subqueries and how to use
them. For the full syntax of all the clauses and the semantics of SELECT, see
SELECT.

Prerequisites
To view data from a table or view, ensure that the table or view must be in your
own schemas or you have the READ or SELECT permission for the table or view.

Syntax
SELECT [hint_info] [SQL_CALC_FOUND_ROWS] [ DISTINCT ] { expression
[ [ AS ] name ] } [ , ... ]
[ FROM { table_reference [ AS OF {SCN(scn_number) | TIMESTAMP(date)} ] [ [AS] alias ] } [ , ... ] ]
[ WHERE { condition | [ NOT ] EXISTS ( correlated subquery ) } ]
[ [START WITH condition ] CONNECT BY [ NOCYCLE ] [ PRIOR ] condition ]
[ GROUP BY { column_name | expression } [ , ... ] ]
[ HAVING condition [ , ... ] ]
[ { UNION [ ALL ] | MINUS } select ]
[ ORDER [SIBLINGS] BY { column_name | number | expression } [ ASC | DESC ][ NULLS FIRST | NULLS
LAST ] [ , ... ] ]
[ LIMIT [ start, ] count | LIMIT count OFFSET start | OFFSET start[ LIMIT count ] ]
[ FOR UPDATE ]
● hint_info:
{/*+ {access_method_hint | join_order_hint | join_method_hint | parallel_hint }[...] */}
– access_method_hint:
{ FULL(table_name [...])
| INDEX(table_name index_name[...])
| NO_INDEX(table_name index_name[...])
| INDEX_ASC(table_name index_name[...])
| INDEX_DESC(table_name index_name[...])
| INDEX_FFS(table_name index_name[...])
| NO_INDEX_FFS(table_name index_name[...])
}
– join_order_hint:
{ ORDERED
| LEADING(table_name[...])
}
– join_method_hint:
{ USE_NL(table_name[...])
| USE_MERGE(table_name[...])
| USE_HASH(table_name[...])
}
– parallel_hint
{ parallel(degree)
}
● table_reference:
{ [ schema_name. ]table_name [partition(partition_name)][ [AS] alias ]
| [ schema_name. ]view_name [ [AS] alias]
| ( select query ) [ [AS] alias ]
| join_table
}
– join_table:
INNER join by default

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 291


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

When INNER is selected, the ON condition can be omitted.


table_reference [LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER] | INNER] JOIN table_reference
ON conditional_expr
● Outer join operator (+)
An outer join can be described either by the LEFT/RIGHT keyword or the
operator (+). A condition that contains (+) in the WHERE clause is used for
an outer join. Specifically, the table containing (+) is the right node of a left
join, and the table without (+) is the left node of the left join.
– The outer join operator can be used as follows:

▪ If there is a join keyword, (+) cannot be used.

▪ Only table columns can precede (+).

▪ (+) can only be used in the WHERE clause, and the condition that
contains (+) does not belong to the OR clause.

▪ In a comparison condition, (+) allows for only six operators: =, <>, >,
<, >=, <=.

▪ In a comparison condition, (+) can be placed on either sides.

▪ If (+) is on one side of a comparison condition, columns of at most


one table are allowed on each side of the condition.

▪ The operator (+) takes effect if only it appears on one side of a


comparison condition. Multiple operators (+) produce the same
effect as one operator.

▪ If multiple conditions contain (+), for example, t1.f1=t2.f1(+) and


t1.f1(+)=t2.f1, an error may be reported because the association
relationship fails to be generated.
● condition:
{ predicate } [ { AND | OR } condition ] [ , ... n ]
– predicate:
{ expression { = | <> | != | > | >= | < | <= } { ALL | ANY } expression | ( select )
| string_expression [ NOT ] LIKE string_expression
| expression [ NOT ] BETWEEN expression AND expression
| expression IS [ NOT ] NULL
| ( select | expression [,...n] ) [ NOT ] IN ( select | expression [ , ... n ] )
| [ NOT ] EXISTS ( select )
}

Parameter Description
● hint_info
– Specifies special comments in a SQL statement that pass instructions to
the database optimizer. The optimizer uses these hints to choose an
execution plan for the statement, unless there are some conditions that
prevent the optimizer from doing so.
– Exercise caution when using hint_info. You are advised to use hints for a
table query only when you have collected statistics about the table and
evaluated the execution plan without hints by using EXPLAIN PLAN.
– In later database versions, database conditions may change and query
performance will be enhanced, which will affect the use of hints. Note

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 292


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

that short-term benefits generated by hints do not necessarily lead to


long-term improvement.
– Currently, parallel hints support only full table scanning of a single table.
Aggregate functions, ORDER BY, GROUP BY, and building of hash tables
are supported.
● SQL_CALC_FOUND_ROWS
It is a reserved word. SQL_CALC_FOUND_ROWS records the number of rows
the SELECT statement would have returned without LIMIT specified. Then,
you can use the FOUND_ROWS() function to obtain the number.
SQL_CALC_FOUND_ROWS can be specified only after the first SELECT
keyword in the SELECT statement. If SELECT is a clause of a UNION, UNION
ALL, or MINUS statement, SQL_CALC_FOUND_ROWS can be specified only in
the first SELECT clause. This reserved word is valid only when the
FOUND_ROWS() function is used.
For details, see FOUND_ROWS() in Other Functions.
● DISTINCT
Returns only one copy of each set of duplicate rows selected.
Value range: existing column name or column expression
● AS OF {SCN(scn_number) | TIMESTAMP(date)}
Queries the table data of a specified SCN or at a specified time point.
Currently, temporary tables and system views cannot be queried.
– AS OF
Performs a flashback query.
– SCN(scn_number)
Queries the result set of the table with the SCN specified by scn_numer.
– TIMESTAMP(date)
Queries the result set at the time point specified by date. date must be a
valid past timestamp (convert a string to a time type using the
TO_TIMESTAMP function).
Note: The specified time point must be earlier than the table creation
time. Otherwise, an error is reported.
● START WITH condition CONNECT BY [ NOCYCLE ] [ PRIOR ] condition
Specifies a clause for querying tree-structured data. If a table contains tree-
structured data, you can use this clause to query data.
– START WITH
Specifies the row that is the root of a tree-structured data query.
– CONNECT BY
Specifies the relationship between parent rows and child rows of a tree-
structured data query. It is used in conjunction with PRIOR.
– NOCYCLE
Instructs the database to return rows from a query even if CONNECT BY
LOOP exists in the data.
– PRIOR
PRIOR is a unary operator and has the same precedence as the unary +
and - arithmetic operators. The PRIOR keyword can be on either side of

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 293


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

the equal sign (=). If PRIOR is placed together with the parent ID, the
query traverses data in the direction of parent nodes. If it is placed
together with the child ID, the query traverses data in the direction of
child nodes.
– CONNECT_BY_ISCYCLE pseudocolumn
The CONNECT_BY_ISCYCLE pseudocolumn indicates whether the current
tuple will form the tree-structured data into a loop. It is valid only when
the NOCYCLE keyword is used in a hierarchical query clause. The
CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a
child which is also its ancestor. Otherwise, it returns 0.
– CONNECT_BY_ISLEAF pseudocolumn
The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a
leaf of the tree defined by the CONNECT BY condition. Otherwise, it
returns 0. This information indicates whether a given row can be further
expanded to show more of the hierarchy.
– LEVEL pseudocolumn
For each row returned by a hierarchical query, the LEVEL pseudocolumn
returns 1 for a root row, 2 for a child of a root, and so on. A root row is
the highest row within an inverted tree. A child row is any nonroot row. A
parent row is any row that has children. A leaf row is any row without
children.
● expression
Specifies a field or field expression to be queried.
● table_reference
Specifies a table or view to be queried, or a subquery.
[partition(partition_name)]
Specifies the partition of a table for query. partition_name indicates the
partition name.
● condition
Restricts the rows selected to those that satisfy one or more conditions.
Query conditions are defined by expressions and operators. Multiple
conditions can be associated by AND or OR. In GaussDB 100, conditions can
be defined by using:
– Comparison operators, such as >, <, >=, <=, !=, <>, and =.
– Test operators, such as LIKE, NOT LIKE, BETWEEN, NOT BETWEEN,
NULL, NOT NULL, IN, and NOT IN.
– EXISTS (select), which requires that the columns to be queried exist.
– NOT EXISTS (select), which requires that the columns to be queried do
not exist.
● GROUP BY
Specifies a column based on which a result set is grouped.
● HAVING
Specifies the filter conditions for restricting the results of a GROUP BY.
● ORDER BY
Specifies a column based on which a result set is sorted.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 294


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

ORDER SIBLINGS BY
Specifies the columns used for sorting sibling nodes. This parameter can be
used only when CONNECT BY is specified.
● ASC | DESC
Specifies whether the ordering sequence is ascending or descending. The
default value is ASC.
● NULLS FIRST | NULLS LAST
Specifies the position of NULL values in the ORDER BY sorting. FIRST
indicates that NULL values are placed before non-NULL values and LAST
indicates that NULL values are placed after non-NULL values. If this
parameter is not specified, NULLS LAST is used in ASC mode and NULLS
FIRST is used in DESC mode by default.
● FOR UPDATE
Locks the selected rows for UPDATE.
● offset_expr, count_expr
offset_expr limits the offset of a result set and count_expr limits the number
of rows in a result set.
● start,count
count specifies the maximum number of rows to return, while start specifies
the number of rows to skip before the first row is returned. When both are
specified, rows specified by start will be skipped before rows specified by
count are returned.
● UNION [ALL]
Returns all rows in the result sets of multiple SELECT statements.
● FULL(table_name [...])
Specifies a full-table scan.
● INDEX(table_name index_name[...])
Specifies an index scan.
● NO_INDEX(table_name index_name[...])
Specifies a non-index scan.
● INDEX_ASC(table_name index_name[...])
Specifies an ascending index scan.
● INDEX_DESC(table_name index_name[...])
Specifies a descending index scan.
● INDEX_FFS(table_name index_name[...])
Specifies a fast full index scan.
● NO_INDEX_FFS(table_name index_name[...])
Excludes a fast full index scan of the specified indexes on the specified table.
● ORDERED
Joins tables in the order in which they appear in the FROM clause.
● LEADING(table_name[...])
Joins tables in the specified order.
● USE_NL(table_name[...])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 295


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Joins each specified table to another row source using a nested-loop join.
● USE_MERGE(table_name[...])
Joins each specified table with another row source using a sort-merge join.
● USE_HASH(table_name[...])
Joins each specified table with another row source using a hash join.
● join_table
Specifies a set of tables for join query.
– [INNER] JOIN returns records that have matching values in both tables.
In this case, the subsequent ON condition can be omitted.
– LEFT [OUTER] JOIN returns all records from the left table and the
matched records from the right table. The result is NULL from the right
side, if there is no match.
– RIGHT [OUTER] JOIN returns all records from the right table and the
matched records from the left table. The result is NULL from the left side,
when there is no match.
– FULL [OUTER] JOIN returns all records when there is a match in either
left or right table It is an equivalent of OUTER JOIN.
● {predicate } [ { AND | OR } condition]
Specifies the conditions that the query result set must satisfy.
– AND
Both of the two conditions must be satisfied.
– OR
Either of the two conditions must be satisfied.
● predicate:
Specifies the conditions that the query result set must satisfy.

3.11.2 Simple Query


Generally, queries are implemented through the FROM clause.

Syntax
SELECT [ , ... ] FROM table_reference [ , ... ]

This is a simplified syntax. For detailed syntax, see SELECT.

Usage
● The expression between the SELECT keyword and the FROM clause is called a
SELECT item. SELECT items are used to specify the columns to be queried,
and the FROM clause specifies the table where the columns are located. To
query all columns, use an asterisk (*) after SELECT. To query certain column,
specify the column names after SELECT and separate the names with
commas (,). For details, see 1 and 2.
● If two or more tables have the same column names, you are advised to
specify both table names and column names. Query results can be returned
without specifying column names but extra workload is required. Therefore,
you are advised to specify both table names and column names to reduce

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 296


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

processing workload of the database and improve the return performance of


the query.
● You can specify an alias for a column by adding AS (optional) and the alias
after the column name in the SELECT statement. For details, see 3.
● You can use hints in a SELECT statement to pass instructions to the database
optimizer. The optimizer selects an optimized execution plan for the
statement based on hints. For details, see •hint_info.

Examples
● Example 1: Create a training table and insert three rows of data into the
table. Query all columns in the training table.
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert three rows of data into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25
12:00:00',90);
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'information safety','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26
12:00:00',95);
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'master all kinds of thinking methonds','2017-07-15 12:00:00','2017-07-20
12:00:00','2017-07-25 12:00:00',97);

Use an asterisk (*) after SELECT to query all columns in the training table.
SELECT * FROM training;
STAFF_ID COURSE_NAME COURSE_START_DATE
COURSE_END_DATE EXAM_DATE SCORE
------------ -------------------------------------------------- ---------------------- ----------------------
---------------------- ------------
10 SQL majorization 2017-06-15 12:00:00 2017-06-20 12:00:00
2017-06-25 12:00:00 90
10 information safety 2017-06-20 12:00:00 2017-06-25 12:00:00
2017-06-26 12:00:00 95
10 master all kinds of thinking methonds 2017-07-15 12:00:00 2017-07-20
12:00:00 2017-07-25 12:00:00 97

● Example 2: Query for staff IDs and course names in the training table.
SELECT staff_id,course_name FROM training;
STAFF_ID COURSE_NAME
------------ --------------------------------------------------
10 SQL majorization
10 information safety
10 master all kinds of thinking methonds

3 rows fetched.

● Example 3: Use an alias.


SELECT staff_id AS empno,course_name FROM training;
EMPNO COURSE_NAME
------------ --------------------------------------------------
10 SQL majorization
10 information safety
10 master all kinds of thinking methonds

3 rows fetched.

3.11.3 Condition Query


In a SELECT statement, you can specify conditions for more accurate query.
Conditions are specified by using expressions and operators, and the return value
is TRUE, FALSE, or UNKNOWN.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 297


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

For details about how to define query conditions in GaussDB 100, see • condition.
Query conditions can be used in the WHERE, HAVING, and START WITH
condition CONNECT BY [NOCYCLE] [PRIOR] condition clauses.

Syntax
condition:
select_statement { predicate } [ { AND | OR } condition ] [ , ... n ]
● predicate:
{ expression { = | <> | != | > | >= | < | <= } { ALL | ANY } expression | ( select )
| string_expression [ NOT ] LIKE string_expression
| expression [ NOT ] BETWEEN expression AND expression
| expression IS [ NOT ] NULL
| expression [ NOT ] IN ( select | expression [ , ... n ] )
| [ NOT ] EXISTS ( select )
}

Usage
Query conditions are defined by using expressions and operators. In GaussDB 100,
conditions can be defined by using:
● Comparison Operators, such as >, <, >=, <=, !=, <>, and =.
In the expression, single quotation marks are optional for the numeric type
but mandatory for character and date types. For details, see 1.
● Test Operators, which specify query ranges. For details, see examples in Test
Operators.
To specify multiple conditions, use the AND logical operator to connect these
conditions. To specify one of multiple conditions, use the OR logical operator to
connect these conditions. In 2, you can query the staffs table for information
about the staff who were hired after 2000 and has a salary greater than 5000.

Examples
● Example 1: Use the comparison operator >, <, >=, <=, !=, <>, or = to specify a
query condition. For example, query the training table for information about
the students who learn SQL majorization.
SELECT * FROM training WHERE course_name = 'SQL majorization';
STAFF_ID COURSE_NAME COURSE_START_DATE
COURSE_END_DATE EXAM_DATE SCORE
------------ -------------------------------------------------- ---------------------- ----------------------
---------------------- ------------
10 SQL majorization 2017-06-15 12:00:00 2017-06-20 12:00:00
2017-06-25 12:00:00 90

1 rows fetched.

● Example 2: Query the staffs table for information about the staff who meet
the following conditions: hired later than 2000 and salary >5000.
SELECT * FROM staffs WHERE HIRE_DATE>'2000-01-01 00:00:00' AND SALARY>'5000';
STAFF_ID FIRST_NAME LAST_NAME EMAIL
PHONE_NUMBER HIRE_DATE EMPLOYMENT_ID SALARY
COMMISSION_PCT MANAGER_ID SECTION_ID
---------------------------------------- -------------------- ------------------------- -------------------------
-------------------- ---------------------- ------------- ----------------------------------------
---------------------------------------- ----------------------------------------
----------------------------------------
149 Eleni Zlotkey EZLOTKEY
011.44.1344.429018 2000-01-29 00:00:00 SA_MAN 10500 .

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 298


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

2 100 80
164 Mattea Marvins MMARVINS
011.44.1346.329268 2000-01-24 00:00:00 SA_REP 7200 .
1 147 80
165 David Lee DLEE
011.44.1346.529268 2000-02-23 00:00:00 SA_REP 6800 .
1 147 80
166 Sundar Ande SANDE
011.44.1346.629268 2000-03-24 00:00:00 SA_REP 6400 .
1 147 80
167 Amit Banda ABANDA
011.44.1346.729268 2000-04-21 00:00:00 SA_REP 6200 .
1 147 80
173 Sundita Kumar SKUMAR
011.44.1343.329268 2000-04-21 00:00:00 SA_REP 6100 .
1 148 80
179 Charles Johnson CJOHNSON
011.44.1644.429262 2000-01-04 00:00:00 SA_REP 6200 .
1 149 80

7 rows fetched.

● Example 3: Query the staffs and employment_history tables for staff's name
and hiring time.
SELECT e.start_date,s.first_name,s.last_name FROM employment_history e, staffs s WHERE e.staff_id =
s.staff_id;
START_DATE FIRST_NAME LAST_NAME
---------------------- -------------------- -------------------------
1989-09-21 00:00:00 Neena Kochhar
1993-10-28 00:00:00 Neena Kochhar
1993-01-13 00:00:00 Lex De Haan
1998-03-24 00:00:00 Den Raphaely
1999-01-01 00:00:00 Payam Kaufling
1998-03-24 00:00:00 Jonathon Taylor
1999-01-01 00:00:00 Jonathon Taylor
1987-09-17 00:00:00 Jennifer Whalen
1994-07-01 00:00:00 Jennifer Whalen
1996-02-17 00:00:00 Michael Hartstein

10 rows fetched.

3.11.4 JOIN Query


Generally, data to be queried is distributed in multiple tables. A query that
combines multiple tables or views is called a join query. In most cases, a join query
is executed for a parent table and its child tables.

Related Concepts
A Cartesian product is also called a direct product. For sets X and Y, the Cartesian
product of the two sets is presented as X × Y. Therefore, if X has I tuples and N
attributes and Y has J tuples and M attributes, their Cartesian product will have IxJ
tuples and N+M attributes. The two relations may have attributes with the same
name.
For example, perform Cartesian product operation for the areas and
employments tables.
-- There are four records in the areas table.
SELECT COUNT(*) FROM areas;
COUNT(*)
--------------------
4

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 299


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- There are 19 records in the employments table.


SELECT COUNT(*) FROM employments;
COUNT(*)
--------------------
19

1 rows fetched.
-- If the areas and employments tables are jointly queried without specifying conditions, 76 (4x19) records
are returned.
SELECT areas.area_name, employments.employment_id FROM areas, employments;

Syntax
SELECT [ , ... ] FROM table_reference
[LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER] | INNER]
JOIN table_reference
[ON { predicate } [ { AND | OR } condition ] [ , ... n ]]
● table_reference:
{ table_name [ [AS] alias ]
| view_name [ [AS] alias]
| ( select query ) [ [AS] alias ]
}
● Outer join operator (+)
An outer join can be described either by the LEFT/RIGHT keyword or the
operator (+). A condition that contains (+) in the WHERE clause is used for
an outer join. Specifically, the table containing (+) is the right node of a left
join, and the table without (+) is the left node of the left join.
– The outer join operator can be used as follows:

▪ If there is a join keyword, (+) cannot be used.

▪ Only table columns can precede (+).

▪ (+) can only be used in the WHERE clause, and the condition that
contains (+) does not belong to the OR clause.

▪ In a comparison condition, (+) allows for only six operators: =, <>, >,
<, >=, <=.

▪ In a comparison condition, (+) can be placed on either sides.

▪ If (+) is on one side of a comparison condition, columns of at most


one table are allowed on each side of the condition.

▪ The operator (+) takes effect if only it appears on one side of a


comparison condition. Multiple operators (+) produce the same
effect as one operator.

▪ If multiple conditions contain (+), generating the join relationship


may fail, and an error will be reported. For example, t1.f1=t2.f1(+)
and t1.f1(+)=t2.f1.
In GaussDB 100, a join is INNER JOIN by default.

Usage
If multiple tables are included in the FROM clause for query, the database
executes a join query. The SELECT items of the query can be any columns in these
tables. For example:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 300


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SELECT table1.column, table2.column FROM table1, table2;

If any two of these tables have the same column name, the table name must be
used to avoid reference ambiguity in the query.
Most join queries contain at least one query condition, which can be either in the
FROM or WHERE clause. For example:
SELECT table1.column, table2.column FROM table1 JOIN table2 ON(table1.column1 = table2.column2);
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;

Inner Join
The keyword INNER JOIN is provided where INNER can be omitted. If an inner
join is used, the join execution sequence will follow the sequence of tables in the
statement.
Example: Use an inner join to query tables.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date) VALUES(11,'BIG
DATA','2018-06-15 12:00:00','2018-06-20 12:00:00','2018-06-25 12:00:00');
-- Insert record 3 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(12,'Performance Turning','2018-06-25 12:00:00','2018-06-27 12:00:00','2018-06-29 12:00:00',95);
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8), graduate_school VARCHAR(64),
graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'doctor','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'','Peking University','2017-07-06 12:00:00','211&985');
-- Insert record 4 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(13,'scholar','Peking University','2017-07-06 12:00:00','211&985');
-- Query for employee IDs, highest educational qualifications, and exam scores. Use the staff_id column in
the training and education columns for query.
SELECT e.staff_id, e.highest_degree, t.score FROM education e JOIN training t ON (e.staff_id = t.staff_id);

STAFF_ID HIGHEST_DEGREE SCORE


------------ ------------- ------------
10 doctor 90
11 master
12 95

3 rows fetched.

Outer Join
In inner joins, two data sources specified are equal. However, in outer joins, one
data source is used as the base for the other source to match according to

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 301


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

conditions. An inner join returns records that have matching values in both tables.
If the rest records need to be returned, use an outer join. An outer join returns all
records that have matching values in either the left or right table. Outer joins
include left outer joins, right outer joins, and full outer joins, which are also called
left joins, right joins, and full joins, respectively.
● Left join: As shown in Figure 3-1, the query is driven by the left table. It is
joined with the right table according to the specified connection; and all data
from the base table and the data satisfying the condition from the right table
are obtained.
For example, change the query in Inner Join to a left join.
SELECT e.staff_id, e.highest_degree, t.score FROM education e LEFT JOIN training t ON (e.staff_id =
t.staff_id);
STAFF_ID HIGHEST_DEGREE SCORE
------------ ------------- ------------
10 doctor 90
11 master
12 95
13 scholar

4 rows fetched.

● Right join: As shown in Figure 3-2, the query is driven by the right table. On
the basis of the inner join, the data recorded in the right table but not in the
left table is also queried.
For example, change the query in Inner Join to a right join.
SELECT e.staff_id, e.highest_degree, t.score FROM education e RIGHT JOIN training t ON (e.staff_id =
t.staff_id);
STAFF_ID HIGHEST_DEGREE SCORE
------------ ------------- ------------
10 doctor 90
11 master
12 95

3 rows fetched.

● Full join: As shown in Figure 3-3, all records satisfying or not satisfying the
condition from either left or right table are returned. That is, a full join is the
sum of the left join and right join. If a full join is used on two tables, a left
join and then a right join will be performed, and the union set of the two
temporary result sets will be returned.
For example, use a full join on the education and training tables.
SELECT e.staff_id, e.highest_degree, t.score FROM education e FULL JOIN training t ON (e.staff_id =
t.staff_id);
STAFF_ID HIGHEST_DEGREE SCORE
------------ ------------- ------------
10 doctor 90
11 master
12 95
13 scholar

4 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 302


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Figure 3-1 Left outer join

Figure 3-2 Right outer join

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 303


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Figure 3-3 Full outer join

Semi-Join
A semi-join is a special type of join, and there is no keyword specified in the SQL
statement. It is implemented by a subquery with IN or EXISTS following WHERE.
If multiple rows in the IN or EXISTS subquery match the conditions, the query
returns only one row instead of all the matched rows.
For example, view education information about the employees who have
participated in the training. Even if multiple rows in the training table match the
subquery conditions (that is, there are multiple employees in the same staff_id),
only one row is returned from the training table. For details about the definitions
of the education and training tables, see Inner Join.
SELECT staff_id, highest_degree, education_note FROM education WHERE EXISTS (SELECT * FROM training
WHERE education.staff_id = training.staff_id);
STAFF_ID HIGHEST_DEGREE EDUCATION_NOTE
------------ ------------- ----------------------------------------------------------------
10 doctor 211
11 master 211&985
12 211&985

3 rows fetched.

Anti-Join
An anti-join is a special type of join, and there is no keyword specified in the SQL
statement. It is implemented by a subquery with NOT IN or NOT EXISTS
following WHERE. It returns all rows that do not meet the condition. The concept
of an anti-join is opposite to that of a semi-join.
For example, query for education information about the employees who have not
participated in the training. For details about the definitions of the education and
training tables, see Inner Join.
SELECT staff_id, highest_degree, education_note FROM education WHERE staff_id NOT IN (SELECT staff_id
FROM training);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 304


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

STAFF_ID HIGHEST_DEGREE EDUCATION_NOTE


------------ ------------- ----------------------------------------------------------------
13 scholar 211&985

1 rows fetched.

If the subquery is in the OR branch of the WHERE clause, semi-joins and anti-joins cannot
be performed.

3.11.5 Subquery
A subquery is a query embedded into a statement for querying, table creation, or
data insertion, aiming to obtain a temporary result set. Subqueries are classified
into correlated subqueries and non-correlated subqueries.
● Correlated subquery: The subquery is executed based on attribute values one
by one of the outer query. That is:
– A subquery contains a reference to a table in the outer query.
– The values of a subquery depend on the table column values in the outer
query.
– Each subquery is executed once for every row of the outer query.
For examples of correlated subqueries, see example 1 and example 2 in
Examples.
The parent statement of a subquery can be a SELECT, UPDATE, or DELETE
statement.
● Non-correlated subquery: A subquery is independent from the outer query.
The subquery is executed before the outer query and does not need to obtain
values from the outer query. The execution result of the subquery is returned
to the outer query.

Syntax
Subquery syntax:
select_statement
{ query_block
| subquery {{ UNION [ALL] | MINUS } subquery } [...]
}
[ order_by_clause ]
[ row_limiting_clause ]

Query_block syntax:
select_statement
[ with cluase ] SELECT [ hint ] [ DISTINCT ] select_list
FROM {
[ table_reference
| join_clause
| inline_analytic_view ]
}
[,...] [where_clause] [group_by_clause]

Usage
● Subqueries can be used in the FROM and WHERE clauses. A subquery in the
FROM clause is also called an in-line view. You can nest any number of
subqueries within an in-line view. A subquery in the WHERE clause is also
called a nested subquery. A maximum of 127 subquery levels can be nested.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 305


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● If a column in a subquery has the same name as the column in the statement
contained in the subquery, the table name or alias must be used as the prefix
of the column. To make statements easier to read, specify table or view
names or aliases for columns.

Subqueries can be used to:

● Specify the rows to be inserted in the INSERT or CREATE TABLE statement.


● Specify the rows to be included in a view in the CREATE VIEW statement.
● Specify the values to be allocated to the existing rows in the UPDATE
statement.
● Provide values for conditions in the WHERE, HAVING, and START WITH
clauses in the SELECT, UPDATE, and DELETE statements.
● Specify tables to be operated.
You can use a subquery in the FROM clause to specify the tables to be
operated, just like specifying table names in the FROM clause. You can use
subqueries to replace table names in the INSERT, UPDATE, and DELETE
statements.

Examples
● Example 1: Use a correlated subquery to query for the staff whose salary is
higher than the average salary in each department.
SELECT s1.last_name, s1.section_id, s1.salary
FROM staffs s1
WHERE salary >(SELECT avg(salary) FROM staffs s2 WHERE s2.section_id = s1.section_id)
ORDER BY s1.section_id;

For each row in the staffs table, the outer query uses a correlated subquery
to calculate the average salary in a department. The correlated subquery
performs the following steps for each row in the staffs table:
a. Determine section_id of the row.
b. Evaluate the outer query based on section_id.
c. If the salary in a row is higher than the department average salary, return
this row.
The subquery is executed once for each row in the staffs table.
● Example 2: For details about correlated subqueries in join queries, see Semi-
Join in JOIN Query.

● Example 3: Use a non-correlated subquery to query for the staff whose salary
is higher than the department average salary in the department with the ID
80.
SELECT staff_id, last_name, salary
FROM staffs
WHERE section_id = '80'
AND salary >(SELECT avg(salary)
FROM staffs
WHERE section_id= '80');

● Example 4: Use a subquery to create a table.


Create a table with the same table structure as the staffs table.
CREATE TABLE staffs_new AS SELECT * FROM staffs WHERE 1<>1;

● Example 5: Insert all data in the staffs table to the staffs_new table.
INSERT staffs_new SELECT * FROM staffs;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 306


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.11.6 Query from SYS_DUMMY


SYS_DUMMY is a table automatically created by GaussDB 100. The SYS_DUMMY
table is in the schema of user SYS. All users can access the SYS_DUMMY table by
specifying the table name. The SYS_DUMMY table has only one column DUMMY
defined to be VARCHAR(1 BYTE), and contains one row with a value X. The
SYS_DUMMY table is used to calculate a constant expression in the SELECT
statement. The SYS_DUMMY table has only one row. Therefore, the constant is
returned only once.
Do not insert data into this table, or update or delete this table. Otherwise, the
system may become unavailable.

Usage
● Query for the current user.
SELECT USER FROM SYS_DUMMY;
● Invoke a system function.
SELECT function_name FROM SYS_DUMMY;
● Obtain the current or next value of a sequence.
SELECT sequence_name .{ NEXTVAL | CURRVAL }FROM SYS_DUMMY;
● Use the table for calculating.
SELECT expression FROM SYS_DUMMY;

Examples
● Example 1: Invoke a system function to obtain the current system time.
SELECT to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') FROM SYS_DUMMY;

TO_CHAR(SYSDATE,'YYYY-MM-DD HH24:MI:SS')
------------------------------------------------
2019-02-01 16:57:58

1 rows fetched.
● Example 2: Calculate the result of 7 plus 1.
SELECT 7+1 FROM SYS_DUMMY;

7+1
--------------------
8

1 rows fetched.

3.11.7 UNION
GaussDB 100 provides the UNION operator to combine the result sets of multiple
query blocks into one.

Syntax
select_statement UNION [ALL] select_subquery

Usage
● The number of columns in each query block must be the same.
● The corresponding column among each query block must be in the same data
type or data type group, and the data types must support UNION. Otherwise,
UNION is not allowed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 307


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Table 3-20 describes data type groups and the combination rules of them.
● The keyword ALL indicates that all duplicate data is retained. If ALL is not
contained, all duplicate data is deleted.

Table 3-20 Data type groups


Data Type Data Type Combination Rule and Precedence
Group

Numeral NUMBER/ ● If the corresponding columns to be


(DECIMAL) combined have the same data type with the
same precision and number of decimal
BINARY_DOUBL places, the combination result is returned in
E the original data type with the precision and
BINARY_INTEGE decimal places retained.
R ● If the corresponding columns to be
combined have different data types, the
BINARY_BIGINT combination result is returned in the data
type of the highest precedence. The
precedence is as follows:
NUMBER>BINARY_DOUBLE>BINARY_BIGINT
>BINARY_INTEGER
● If the precision and number of decimal
places are different for the corresponding
columns to be combined, the combination
result is returned without specifying the
precision and number of decimal places by
default.

Character CHAR(size ● If the corresponding columns to be


[BYTE | CHAR]) combined have the same data type with the
same size and storage mechanism, the
combination result is returned in the original
data type with the size and storage
mechanism retained.
● If the corresponding columns to be
combined have different data types, the
combination result is returned in the data
type of the highest precedence. The
precedence is as follows: VARCHAR>CHAR.
● If the data types of the corresponding
columns to be combined are different but
the storage mechanisms are the same, the
combination result is returned with the
original storage mechanism and the
maximum size.
● If the corresponding columns to be
combined have different data types and
storage mechanisms, the value of
CHAR_TO_BYTES_RATIO (ratio of
converting characters to bytes) in GaussDB

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 308


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Data Type Data Type Combination Rule and Precedence


Group

VARCHAR(size 100 is 6 by default. Assume that you will


[BYTE | CHAR]) combine column A (n1 char) and column B
(n2 byte). x=n1 × CHAR_TO_BYTES_RATIO.
– If x <= n2, the combination result is
returned at the size n2, without char.
– If x > n2, the combination result is
returned at the larger size between n1
and n2, with char.

Binary BINARY ● If the corresponding columns to be


combined have different data types, the
VARBINARY combination result is returned in the data
type of the highest precedence. The
precedence is as follows:
VARBINARY>BINARY.
● The combination result is returned at the
largest size among the corresponding
columns to be combined.

RAW The result set of the RAW data type cannot be


combined with that of the BINARY or
VARBINARY data type.

Date DATE ● Result sets of different date types can be


combined. The precedence is as follows:
TIMESTAMP TIMESTAMP WITH TIME ZONE>TIMESTAMP
TIMESTAMP WITH LOCAL TIME
WITH LOCAL ZONE>TIMESTAMP>DATE
TIME ZONE ● The combination result is returned in the
precision with the maximum digits among
TIMESTAMP the corresponding columns to be combined.
WITH TIME The precision of the DATE type is 0.
ZONE

Time INTERVAL YEAR ● Result sets of different time interval types


interval TO MONTH cannot be combined.

INTERVAL DAY ● When result sets of the same time interval


TO SECOND type are combined, the combination result is
returned in the precision with the maximum
digits among the corresponding columns to
be combined.

Boolean BOOLEAN -

LOB CLOB Result sets of different LOB types cannot be


combined.
BLOB

IMAGE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 309


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
Query for information about the employees whose bonuses exceed 7000.
-- Delete the bonuses_depa1 table, if any.
DROP TABLE IF EXISTS bonuses_depa1;
-- Delete the bonuses_depa2 table, if any.
DROP TABLE IF EXISTS bonuses_depa2;
-- Create the bonuses_depa1 table.
CREATE TABLE bonuses_depa1(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Create the bonuses_depa2 table.
CREATE TABLE bonuses_depa2(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer',5000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(24,'limingying','tester',7000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(29,'liuxue','tester',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document developer',
11000);
-- Commit the transaction.
COMMIT;
-- Insert record 1 into the bonuses_depa2 table.
INSERT INTO bonuses_depa2(staff_id, staff_name, job, bonus) VALUES(30,'wangxin','developer',9000);
-- Insert record 2 into the bonuses_depa2 table.
INSERT INTO bonuses_depa2(staff_id, staff_name, job, bonus) VALUES(31,'wangxufeng','document
developer',6000);
-- Insert record 3 into the bonuses_depa2 table.
INSERT INTO bonuses_depa2(staff_id, staff_name, job, bonus) VALUES(34,'denggui','quality control',5000);
-- Insert record 4 into the bonuses_depa2 table.
INSERT INTO bonuses_depa2(staff_id, staff_name, job, bonus) VALUES(33,'liuying','quality control',10000);
-- Insert record 5 into the bonuses_depa2 table.
INSERT INTO bonuses_depa2(staff_id, staff_name, job, bonus) VALUES(35,'caojiongming','document
developer',12000);
-- Commit the transaction.
COMMIT;
-- Query for information about the employees whose bonuses exceed 7000.
SELECT staff_id, staff_name, bonus FROM bonuses_depa1 WHERE bonus > 7000 UNION ALL SELECT
staff_id, staff_name, bonus FROM bonuses_depa2 WHERE bonus > 7000 ;

STAFF_ID STAFF_NAME BONUS


------------ -------------------------------------------------- ----------------------------------------
30 wangxin 9000
33 liuying 10000
35 caojiongming 12000
25 liulili 8000
29 liuxue 8000
21 caoming 11000

6 rows fetched.

3.11.8 MINUS
GaussDB 100 provides the MINUS operator to subtract a result set.

For example, A MINUS B C returns the result set of A minus the result sets of B
and C. That is, only unique rows returned by A but not by B and C are returned.

Syntax
select_statement MINUS select_statement2 [ ... ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 310


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Parameters
● select_statement1
A SELECT statement that generates the first result set.
● select_statement2
Specifies the SELECT statement that generates the second result set.

Examples
Query data using MINUS.
-- Delete the education table, if any.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school VARCHAR(64),
graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note) VALUES
(10, 'Doctor', 'Xidian University', '2017-07-06 12:00:00', '211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note) VALUES
(11, 'Master', 'Northwestern Polytechnical University', '2017-07-06 12:00:00', '211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note) VALUES
(12, 'Bachelor', 'Xi'an University of Architecture and Technology', '2017-07-06 12:00:00', 'not 211 or 985');
-- Commit the transaction.
COMMIT;
-- Delete the education_disable table.
DROP TABLE IF EXISTS education_disable;
-- Create the education_disable table.
CREATE TABLE education_disable(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70));
-- Insert a record into the education_disable table.
INSERT INTO education_disable(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'doctor','Xidian University','2017-07-06 12:00:00','211');
-- Commit the transaction.
COMMIT;
-- Query data using MINUS.
SELECT * FROM education MINUS SELECT * FROM education_disable WHERE staff_id=10;

3.11.9 Hierarchical Query


In a relational database, a record in a data table can have duplicate column
values, generating parallel relationships between different records. Sometimes,
there may be parent-child relationships between records. When the parent-child
relationships are complex, data in the entire table can be considered as a tree
structure. A query based on the tree structure is called a hierarchical query. A
hierarchical query sets a recursive query condition on records having a parent-child
relationship.
For example, a company has branches in major cities around the world, as shown
in the following figure.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 311


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Figure 3-4 Tree structure o the branches

Syntax
select_statement [START WITH condition ] CONNECT BY [ NOCYCLE ] [ PRIOR ] condition

Usage
● START WITH
Specifies one or more root rows of the hierarchy, that is, the start row of a
traverse. If multiple rows are specified, the query will traverse multiple root
rows.
● CONNECT BY
Specifies the relationship between parent rows and child rows of a tree-
structured data query. It is used in conjunction with PRIOR. For example,
CONNECT BY PRIOR staff_id=manager_id indicates that staff_id of the next
record is manager_id of the previous record.
● NOCYCLE
Instructs the database to return rows from a query even if CONNECT BY
LOOP exists in the data.
A loop occurs if:
For example, it is found that parent_id for region_id of 1 is 24684 and that
parent_id for region_id of 24684 is also 1. As a result, an infinite loop occurs.
After the data is corrected, the query will be recovered.
● PRIOR
Is a unary operator and has the same precedence as the unary + and -
arithmetic operators.
The PRIOR keyword can be on either side of the equal sign (=). For example,
in CONNECT BY PRIOR area_id=country_id where PRIOR is placed on the
left of the equal mark and with the child ID area_id, the query traverses data
in the direction of child nodes, that is, a top-down query. If the statement is
changed to CONNECT BY country_id= PRIOR are_id where PRIOR is placed
with the parent ID area_id, the query traverses data in the direction of parent
nodes, that is, a bottom-up query.
If multiple join conditions are specified after CONNECT BY, the PRIOR
keyword must be specified for each condition.
● CONNECT_BY_ISCYCLE pseudocolumn
The CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a
child which is also its ancestor. Otherwise, it returns 0.
● CONNECT_BY_ISLEAF pseudocolumn
The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a leaf
of the tree defined by the CONNECT BY condition. Otherwise, it returns 0.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 312


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

This information indicates whether a given row can be further expanded to


show more of the hierarchy.
● LEVEL pseudocolumn
For each row returned by a hierarchical query, the LEVEL pseudocolumn
returns 1 for a root row, 2 for a child of a root, and so on. A root row is the
highest row within an inverted tree. A child row is any nonroot row. A parent
row is any row that has children. A leaf row is any row without children.

Examples
Query the country table for the countries where all branches are located in
Europe. For details, see Figure 3-4.
-- Delete the country table, if any.
DROP TABLE IF EXISTS country;
-- Create the country table.
CREATE TABLE country (
area_id INT NOT NULL,
area_name VARCHAR(30),
country_id INT NOT NULL,
country_name VARCHAR(30)
);
-- Insert data.
INSERT INTO country VALUES(1, 'NSA', 21, 'Mexico');
INSERT INTO country VALUES(1, 'NSA', 22, 'USA');
INSERT INTO country VALUES(1, 'NSA', 23, 'Brazil');
INSERT INTO country VALUES(2, 'EU', 24, 'Canada');
INSERT INTO country VALUES(2, 'EU', 25, 'Italy');
INSERT INTO country VALUES(2, 'EU', 26, 'Britain');
INSERT INTO country VALUES(3, 'AS', 27, 'Japan');
INSERT INTO country VALUES(3, 'AS', 28, 'China');
INSERT INTO country VALUES(3, 'AS', 29, 'Singapore');
COMMIT;
-- Use the START WITH clause to query for the countries where all branches are located in Europe.
SELECT area_name, country_name FROM country START WITH area_id=2 CONNECT BY PRIOR
area_id=country_id;

AREA_NAME COUNTRY_NAME
------------------------------ ------------------------------
EU Canada
EU Italy
EU Britain

3 rows fetched.

3.11.10 GROUP BY
The GROUP BY clause is very important for database queries. It collects data
across multiple records and groups the results by one or more columns.

Syntax
GROUP BY { column_name | expression } [ , ... ]

How to Use
Expressions in the GROUP BY clause can be any columns from the table or view in
the FROM clause, regardless of whether the columns appear in the SELECT list.

The GROUP BY clause groups rows, but does not guarantee the order in result
sets. To sort groups, use the ORDER BY clause.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 313


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Expressions after GROUP BY can be in parentheses, for example, GROUP BY


(expr1, expr2) or GROUP BY (expr1), (expr2). However, the GROUP BY (expr1,
expr2), expr3 format is not supported.

Examples
Query for the total number of employees in each department by using section_id
for grouping.
-- Delete the staffs table, if any.
DROP TABLE IF EXISTS staffs;
-- Create the staffs table.
CREATE TABLE staffs
(
staff_id NUMBER(6) not null,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
);
-- Insert data.
INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (198, 'Donald', 'OConnell', 'DOCONNEL',
'650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'), 'SH_CLERK', 2200.00, null, 124, 50);

INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (198, 'Donald', 'OConnell', 'DOCONNEL',
'650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'), 'SH_CLERK', 2400.00, null, 124, 50);

INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (198, 'Donald', 'OConnell', 'DOCONNEL',
'650.507.9833', to_date('21-06-1999', 'dd-mm-yyyy'), 'SH_CLERK', 2600.00, null, 124, 50);

INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844',
to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK', 4000.00, null, 124, 50);

INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844',
to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK', 4200.00, null, 124, 50);

INSERT INTO staffs (staff_id, first_name, last_name, email, phone_number, hire_date, employment_id,
salary, commission_pct, manager_id, section_id) VALUES (199, 'Douglas', 'Grant', 'DGRANT', '650.507.9844',
to_date('13-01-2000', 'dd-mm-yyyy'), 'SH_CLERK', 4400.00, null, 124, 50);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID) VALUES (106, 'Valli', 'Pataballa',
'VPATABAL', '590.423.4560', to_date('05-02-1998', 'dd-mm-yyyy'), 'IT_PROG', 4800.00, null, 103, 60);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID) VALUES (107, 'Diana', 'Lorentz',
'DLORENTZ', '590.423.5567', to_date('07-02-1999', 'dd-mm-yyyy'), 'IT_PROG', 4200.00, null, 103, 60);

INSERT INTO staffs (staff_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE,


employment_ID, SALARY, COMMISSION_PCT, MANAGER_ID, section_ID) VALUES (108, 'Nancy', 'Greenberg',
'NGREENBE', '515.124.4569', to_date('17-08-1994', 'dd-mm-yyyy'), 'FI_MGR', 12000.00, null, 101, 100);

COMMIT;
-- Query for the total number of employees in each department by using section_id for grouping.
SELECT section_id, COUNT(staff_id) FROM staffs GROUP BY section_id ORDER BY section_id;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 314


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SECTION_ID COUNT(STAFF_ID)
---------------------------------------- --------------------
50 6
60 2
100 1

3 rows fetched.

3.11.11 HAVING
The HAVING clause is used to filter data after grouping. HAVING returns groups
that satisfy the specified condition. The HAVING clause relies on GROUP BY.

Syntax
HAVING condition [ , ... ]

How to Use
Specify GROUP BY and HAVING after the WHERE clause and a hierarchical query.
If both GROUP BY and HAVING are specified, they can appear in any order.

Examples
Query for the total number of employees in departments with more than three
employees.
-- Delete the bonuses_depa1 table, if any.
DROP TABLE IF EXISTS bonuses_depa1;
-- Create the bonuses_depa1 table.
CREATE TABLE bonuses_depa1(section_id INT NOT NULL, staff_id INT NOT NULL, staff_name CHAR(50),
job VARCHAR(30), bonus NUMBER);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus)
VALUES(2,23,'wangxiayu','developer',9000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(2,23,'wangxia','developer',
5000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(2,24,'limingying','tester',
9000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(2,25,'liulili','quality
control',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(4,29,'liuxue','tester',7000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(4,21,'caoming','document
developer',7400);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(4,28,'caochun','tester',
7300);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(4,29,'caoxi','tester',7700);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, staff_id, staff_name, job, bonus) VALUES(1,30,'caoxixi','tester',7200);
-- Commit the transaction.
COMMIT;
-- Query for the total number of employees in departments with more than three employees.
SELECT section_id, COUNT(staff_id) FROM bonuses_depa1 GROUP BY section_id HAVING COUNT(staff_id)
> 3;

SECTION_ID COUNT(STAFF_ID)
------------ --------------------
4 4

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 315


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

2 4

2 rows fetched.

3.11.12 ORDER BY
The ORDER BY clause is used to sort rows returned by a query according to a
specified column. If there is no ORDER BY, a repeated query may retrieve data in
different orders.

Syntax
ORDER [SIBLINGS] BY { column_name | number | expression } [ ASC | DESC ][ NULLS FIRST | NULLS LAST ]
[ , ... ]

Usage
By default, the ORDER BY clause sorts records in ascending order. If a descending
order is needed, use the keyword DESC.
ORDER SIBLINGS BY specifies the columns used for sorting sibling nodes.
The NULLS FIRST | NULLS LAST keyword specifies the position of NULL values in
the ORDER BY sorting. FIRST indicates that NULL values are placed before non-
NULL values and LAST indicates that NULL values are placed after non-NULL
values. If this keyword is not specified, NULLS FIRST is used in ASC mode and
NULLS LAST is used in DESC mode by default.

Examples
● Query for the bonus information of different jobs in each department. Ensure
that the query results are first sorted by job in ascending order and then by
section_name in descending order.
-- Delete the bonuses_depa1 table, if any.
DROP TABLE IF EXISTS bonuses_depa1;
-- Create the bonuses_depa1 table.
CREATE TABLE bonuses_depa1(section_id INT NOT NULL, section_name VARCHAR(50), staff_id INT NOT
NULL, staff_name CHAR(50), job VARCHAR(30), bonus NUMBER);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus)
VALUES(1,'devepment',23,'wangxia','developer',5000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(2,'test',
24,'limingying','tester',7000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(3,'quality',
25,'liulili','quality control',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(2,'test',
29,'liuxue','tester',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(4,'products',
21,'caoming','document developer',11000);
-- Commit the transaction.
COMMIT;
-- Query for the bonus information of different jobs in each department. Ensure that the query results are
first sorted by job in ascending order and then by section_name in descending order.
SELECT section_name, job, bonus FROM bonuses_depa1 ORDER BY job, section_name DESC;

SECTION_NAME JOB BONUS


-------------------------------------------------- ------------------------------ ----------------------------------------
devepment developer 5000

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 316


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

products document developer 11000


quality quality control 8000
test tester 7000
test tester 8000

5 rows fetched.
-- Query for the bonus information of different jobs in each department. Ensure that the query results are
first sorted by job in ascending order and then by section_name in descending order. In the ORDER BY
clause, use numbers to specify the positions of columns for sorting. A number indicates the corresponding
position in the query column list.
SELECT section_name, job, bonus FROM bonuses_depa1 ORDER BY 2, 1 DESC;

SECTION_NAME JOB BONUS


-------------------------------------------------- ------------------------------ ----------------------------------------
devepment developer 5000
products document developer 11000
quality quality control 8000
test tester 7000
test tester 8000

5 rows fetched.

● Use ORDER SIBLINGS BY to sort a result set.


-- Delete the t_sibling_order table.
DROP TABLE if exists t_sibling_order;
-- Create the t_sibling_order table.
create table t_sibling_order(EMPNO NUMBER(10) NOT NULL,ENAME VARCHAR2(10),MGR NUMBER(4));
-- Insert records into the t_sibling_order table.
insert into t_sibling_order values (1,'M',NULL);
insert into t_sibling_order values (2,'N',NULL);
insert into t_sibling_order values (3,'A',NULL);
insert into t_sibling_order values (4,'C',3);
insert into t_sibling_order values (5,'B',3);
insert into t_sibling_order values (6,'F',4);
insert into t_sibling_order values (7,'E',4);
insert into t_sibling_order values (8,'D',5);
insert into t_sibling_order values (9,'G',5);
-- Use ORDER SIBLINGS BY to sort the result set.
SELECT LEVEL, t.empno, t.ename FROM t_sibling_order t START WITH t.mgr IS NULL CONNECT BY PRIOR
t.empno = t.mgr ORDER SIBLINGS BY t.ename;

3.11.13 WITH AS

Description
The WITH AS clause defines a SQL fragment, which will be used by the entire SQL
statement.

This makes SQL statements more readable. A table storing SQL fragments is
different from a base table. It is a virtual table, also called a view. The definition
and data corresponding to the view is not stored in the database but still in the
base table. If data in the base table changes, the data in the view changes
accordingly.

Syntax
WITH { table_name AS select_statement1 }[ , ...] select_statement2

Parameter Description
● table_name
Specifies the name of a user-defined table that stores SQL fragments.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 317


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● select_statement1
Specifies the SELECT statement that queries data from a base table.
● select_statement2
Specifies the SELECT statement that queries data from a user-defined table
that stores SQL fragments.

Examples
Use WITH AS to query data.
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64),graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'Doctor','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'Master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'Scholar','Xi'an University of Architecture and Technology','2017-07-06 12:00:00','not 211 or 985');
-- Commit the transaction.
COMMIT;
-- Use WITH AS to query data.
WITH tmp AS (SELECT staff_id, highest_degree FROM education) SELECT * FROM tmp;

3.11.14 LIMIT
The LIMIT clause allows users to limit the rows returned by a query. Users can
also specify the offset and the number or percent of rows to be returned. This
clause helps generate top N reports. In addition, the ORDER BY clause can be
used to ensure ordered data in the result set to be returned.

Syntax
[ LIMIT [ start, ] count | LIMIT count OFFSET start | OFFSET start[ LIMIT count ] ]

How to Use
● start: Specifies the number of rows to skip before the first row is returned.
● count: Specifies the maximum number of rows to return.
If both start and count are specified, rows specified by start will be skipped
before rows specified by count are returned. This will be illustrated by example 1
below.
After start and count are specified, the keyword OFFSET can still be used. This
will be illustrated by example 2 below. In the following examples, LIMIT 5,20 is
equivalent to LIMIT 20 OFFSET 5 and OFFSET 5 LIMIT 20.

Examples
Make two queries with the first excluding LIMIT and the second including LIMIT,
and then compare the query results. Query for information about the employees
whose bonuses exceed 7000.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 318


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the bonuses_depa1 table, if any.


DROP TABLE IF EXISTS bonuses_depa1;
-- Create the bonuses_depa1 table.
CREATE TABLE bonuses_depa1(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer',5000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(24,'limingying','tester',7000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(29,'liuxue','tester',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document developer',
11000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(27,'caoqing','tester',7400);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(28,'caochun','tester',7300);
-- Commit the transaction.
COMMIT;
-- Query for information about the employees whose bonuses exceed 7000.
SELECT staff_name, job, bonus FROM bonuses_depa1 WHERE bonus > 7000;

STAFF_NAME JOB BONUS


-------------------------------------------------- ------------------------------ ----------------------------------------
liulili quality control 8000
liuxue tester 8000
caoming document developer 11000
caoqing tester 7400
caochun tester 7300

5 rows fetched.
-- Query for information about the employees whose bonuses exceed 7000. Use LIMIT 2,2 to skip the first 2
rows and query the rest 2 rows.
SELECT staff_name, job, bonus FROM bonuses_depa1 WHERE bonus > 7000 LIMIT 2,2;

STAFF_NAME JOB BONUS


-------------------------------------------------- ------------------------------ ----------------------------------------
caoming document developer 11000
caoqing tester 7400

2 rows fetched.
-- Query for information about the employees whose bonuses exceed 7000. Use LIMIT 2 OFFSET 2 to skip
the first 2 rows and query the rest 2 rows. In this case, the result is the same as that of LIMIT 2,2.
SELECT staff_name, job, bonus FROM bonuses_depa1 WHERE bonus > 7000 LIMIT 2 OFFSET 2;

STAFF_NAME JOB BONUS


-------------------------------------------------- ------------------------------ ----------------------------------------
caoming document developer 11000
caoqing tester 7400

2 rows fetched.

3.11.15 FOR UPDATE


The FOR UPDATE clause allows users to lock a selected row so that other users
cannot lock or update the row before the current transaction ends.

Syntax
FOR UPDATE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 319


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

How to Use
The FOR UPDATE clause can only be specified in the top-level SELECT statement,
instead of a subquery.

Examples
In the following example, use the FOR UPDATE clause to lock the records that
meet the query condition.
-- Delete the education table, if any.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school VARCHAR(64),
graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'doctor','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'scholar','Peking University','2017-07-06 12:00:00','211&985');
-- Commit the transaction.
COMMIT;
-- Use the FOR UPDATE clause to lock the records whose highest_degree is doctor in the education table.
SELECT staff_id, highest_degree FROM education WHERE highest_degree='doctor' FOR UPDATE;

STAFF_ID HIGHEST_DEGREE
------------ -------------
10 doctor

1 rows fetched.

3.12 Function Syntax


In GaussDB 100, you can use the function syntax in zsql to perform system
operations.

Table 3-21 Function syntax list

Function SQL Statement

Backing up a database BACKUP

Rebuilding a database BUILD DATABASE

Restoring a database RESTORE DATABASE

Restoring data blocks RESTORE BLOCKRECOVER

Importing data LOAD

Exporting data DUMP

Logically importing data IMP

Logically exporting data EXP

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 320


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Function SQL Statement

Replaying database logs RECOVER DATABASE

Graceful shutdown SHUTDOWN

Data page verification VALIDATE

3.12.1 BACKUP

Description
BACKUP physically backs up a database.

Precautions
● This statement can be executed only in the OPEN database state.
● Start the database in the NOMOUNT state and then manually switch to the
OPEN state to run BACKUP.
-- After the database is started in the NOMOUNT state, log in to the database as user SYS.
zsql / as SYSDBA;
-- Switch to the OPEN database mode. test is the database name.
ALTER DATABASE MOUNT;
ALTER DATABASE test archivelog;
ALTER DATABASE OPEN;

Syntax
BACKUP DATABASE { FULL | INCREMENTAL LEVEL level [CUMULATIVE]}
{ FORMAT 'dest_format' }
[ AS [ZLIB | ZSTD | LZ4] COMPRESSED BACKUPSET [LEVEL compress_level]]
[ TAG 'tag' ] [ PARALLELISM count ] [ SECTION THRESHOLD size ]
[ EXCLUDE FOR TABLESPACE space_list]

Parameter Description
● FULL
Specifies a full backup.
● INCREMENTAL LEVEL level
Specifies an incremental backup level.
The value can be 0 or 1.
0 indicates a full backup. 1 indicates an incremental backup based on the
previous backup.
● CUMULATIVE
Specifies an accumulative incremental backup.
● FORMAT
Specifies the path of a backup set.
● dest_format
Specifies a backup path format.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 321


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– The value can be path, disk:path, or nbu:policy:path.


– path equals disk:path, indicating that the backup destination is a disk.
path indicates a specific path.
– In nbu:policy:path, nbu indicates that data is backed up to NBU, policy
indicates the corresponding NBU policy, and path indicates a specific
path.
– path contains a maximum of 255 characters.
● AS [ZLIB | ZSTD | LZ4] COMPRESSED BACKUPSET
Specifies that a compressed backup set is used.
[ZLIB | ZSTD | LZ4] indicates the compression algorithm. If this parameter is
not specified, the default value ZLIB is used. ZSTD is recommended.
– ZLIB: The compression ratio of ZLIB is slightly lower than ZSTD and
higher than LZ4, but the compression rate is far lower than ZSTD.
– ZSTD: The compression ratio of ZSTD is higher but the compression rate
is slightly lower than LZ4.
– LZ4: The compression rate of LZ4 is lower than ZSTD, but the
compression rate is higher.
● LEVEL compress_level
Specifies a compression level for backup. A higher compression level indicates
a higher compression ratio and a slower speed.
The value of compress_level is an integer within the range [1, 9]. 1 indicates
the highest speed and 9 indicates the highest compression ratio.
If the compression level is not specified, the default level 1 is used for backup.
● tag
Specifies the tag of a backup set.
A tab contains a maximum of 30 characters.
● PARALLELISM count
If the backup media is a disk, concurrent threads can be enabled to back up
data in parallel, improving the backup performance.
The value of count is an integer within the range of [1, 8]. If the number of
concurrent threads is not specified, four concurrent threads are started by
default.
● SECTION THRESHOLD size
In parallel backup, you can specify the maximum size of each data file to
improve the backup efficiency.
The value range of size is [128M, 32T]. A large value will decrease the
efficiency of parallel backup, and a small value will generate too many
backup files. Therefore, you are not advised to manually specify the value. If
this parameter is not specified, the database automatically selects the optimal
value.
● EXCLUDE FOR TABLESPACE space_list
Backs up tablespaces excluding the specified ones.
space_list specifies the excluded tablespaces. Multiple tablespaces are
separated with commas (,).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 322


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
● Fully back up data to disks.
BACKUP DATABASE FULL FORMAT '?/full0822.bak';
● Incrementally back up data to disks.
--Set LEVEL to 0 to perform a full backup.
BACKUP DATABASE INCREMENTAL LEVEL 0 FORMAT '?/incr.bak' tag 'incr0822_bak';
-- Set LEVEL to 1 to perform an incremental backup based on the previous backup.
BACKUP DATABASE INCREMENTAL LEVEL 1 FORMAT '?/incr0823.bak' tag 'incr0823_bak';
● Perform an accumulative incremental backup.
-- Perform an accumulative incremental backup based on the previous full backup.
BACKUP DATABASE INCREMENTAL LEVEL 1 CUMULATIVE FORMAT '?/incr0824.bak' tag
'incr0824_bak';
● Perform a backup by using a compression algorithm.
-- Perform a full backup by using a compression algorithm.
BACKUP DATABASE FULL FORMAT '?/full001.bak' tag 'full001_bak' as compressed backupset;
-- Perform an incremental backup by using a compression algorithm.
BACKUP DATABASE INCREMENTAL LEVEL 0 FORMAT '?/incr001.bak' tag 'incr001_bak' as compressed
backupset;
-- Perform a full backup by using the ZSTD compression algorithm.
BACKUP DATABASE FULL FORMAT '?/fullzstd.bak' as zstd compressed backupset;
-- Perform a full backup by using the LZ4 compression algorithm.
BACKUP DATABASE FULL FORMAT '?/fulllz4.bak' as lz4 compressed backupset;
● Perform parallel backup.
-- The database automatically calculates the maximum size of each backup file. The number of
concurrent threads is 6.
BACKUP DATABASE FULL FORMAT '?/full011.bak' tag 'full011_bak' PARALLELISM 6;
-- The maximum size of each backup file is set to 1 GB and the number of concurrent threads is 2.
BACKUP DATABASE FULL FORMAT '?/full012.bak' tag 'full012_bak' PARALLELISM 2 SECTION
THRESHOLD 1G;
● Back up tablespaces excluding the specified ones.
-- Back up tablespaces excluding spc1.
BACKUP DATABASE FORMAT '?/exclude_bak1' EXCLUDE FOR TABLESPACE spc1;
-- Back up tablespaces excluding spc1 and spc2.
BACKUP DATABASE FORMAT '?/exclude_bak2' EXCLUDE FOR TABLESPACE spc1,spc2;

3.12.2 BUILD DATABASE


Description
BUILD DATABASE rebuilds a database in HA mode.

Syntax
BUILD [CASCADED STANDBY | STANDBY] DATABASE
[COMPRESS [ ZLIB | ZSTD |LZ4 ] [ LEVEL n ] ]

Parameter Description
● CASCADED STANDBY
Rebuilds a cascaded standby database.
● STANDBY
Rebuilds a standby database.
● COMPRESS [ ZLIB | ZSTD |LZ4 ]
Compresses the logs and data sent from the primary database when a
standby database is rebuilt.
[ZLIB | ZSTD | LZ4] indicates the compression algorithm. If this parameter is
not specified, the default value ZSTD is used. ZSTD is recommended.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 323


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– ZLIB: The compression ratio of ZLIB is slightly lower than ZSTD and
higher than LZ4, but the compression rate is far lower than ZSTD.
– ZSTD: The compression ratio of ZSTD is higher but the compression rate
is slightly lower than LZ4.
– LZ4: The compression rate of LZ4 is lower than ZSTD, but the
compression rate is higher.
● LEVEL n
Specifies a compression level within the value range [1, 9].
If the compression level is not specified, the default level 1 is used.

If CASCADED STANDBY and STANDBY are not specified, the role of the rebuilt database is
determined by the role of the peer database. If the peer is a primary database, the role of
the rebuilt database is standby. If the peer is a standby database, the role of the rebuilt
database is cascaded-standby.

Examples
● Rebuild a database with the compression algorithm set to ZSTD and
compression level set to 1.
build database compress zstd level 1;

Succeed.

3.12.3 DUMP
Description
During database migration or data backup, you need to import and export data.
GaussDB 100 allows you to run the DUMP statement to export data.

Syntax
DUMP { TABLE table_name | QUERY "select_query " }
INTO FILE 'file_name '
[ FILE SIZE 'uint64_file_size' ]
[ { FIELDS | COLUMNS } ENCLOSED BY 'ascii_char' [ OPTIONALLY ] ]
[ { FIELDS | COLUMNS } TERMINATED BY 'string ']
[ { LINES | ROWS } TERMINATED BY 'string ']
[ CHARSET 'string' ];

Parameter Description
● table_name
Specifies the name of a table whose data is to be exported.
● select_query
Specifies the records to be exported. select_query is a SELECT clause.
● file_name
Specifies the name of a file to store exported data.
● uint64_file_size
Specifies the size of each file storing exported data. If a file is full, a new file
will be created to store data. The default value is 0, indicating that no new
file will be created.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 324


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● FIELDS
Specifies the format of each column.
● COLUMNS
Specifies the format of each column. It is equal to FIELDS.
● ENCLOSED BY
Encloses column values with a pair of characters.
● ascii_char
Specifies the characters used to enclose each column value. For example, in
"ABC", the value is ABC and the characters used to enclose the value are
double quotation marks (""). By default, the characters are not specified.
Value range: a single ASCII character or an empty string. The value single
quotation marks ('') indicate that no characters are specified.
– Decimal ASCII characters range from 0 to 127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-22.
● OPTIONALLY
Encloses only character and binary data. By default, OPTIONALLY is not used.
● TERMINATED BY
Separates columns with delimiters.
● string
Specifies a column delimiter. The default value is a comma (,).
Value range: a single ASCII character
– Decimal ASCII characters range from 0 to 127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-22.
● LINES
Separates rows with delimiters if a record contains multiple rows.
● ROWS
It is a synonym of LINES.
string
Specifies a row delimiter. The default value is \n.
Value range: a single ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-22.
● CHARSET
Specifies the character set to be exported.
string
Currently, only the UTF8 (without BOM) character set (CHARSET = UTF8)
and GBK character set (CHARSET = GBK) are supported. The former is used
by default.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 325


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● row_terminated_char
Specifies a row delimiter. The default value is \n.
Value range: a single ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-22.

Table 3-22 Common escape characters

Escape Description ASCII ASCII


Character (Decimal) (Hexadecimal
)

\a BELL (BEL) 007 \x07

\f Form feed (FF). Move 012 \x0C


to the beginning of
the next page.

\n Line feed (LF). Move 010 \x0A


to the beginning of
the next line.

\r Carriage return (CR). 013 \x0D


Move to the
beginning of the
current line.

\t Horizontal table (HT). 009 \x09


Jump to the next tab.

\v Vertical tab (VT) 011 \x0B

\\ One backslash (\) 092 \x5C

Two single One single quotation 039 \x27


quotation mark (')
marks ('')

\" One double quotation 034 \x22


mark (")

\? One question mark 063 \x3F


(?)

\0 Null character (NULL) 000 \x00

\ooo One- to three-digit Three-digit -


octal character code octal

\xhh One- to two-digit Two-digit -


hexadecimal hexadecimal
character code

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 326


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The single quotation mark (') is an escape character of SQL. If you need to use it as a
delimiter, use two single quotation marks ('') to represent it. For example:
.... enclosed by ''''....
The outer two single quotation marks are used to enclose the inner ones ('') that represent
a single quotation mark (').
If the character specified by ascii_char is included in the column value, the character will be
escaped again when the column value is exported. For example, if the specified character is
the double quotation mark (") which is included in the column value 1"1, the value will be
exported as "1""1".

Examples
● Export the training table, separating columns with vertical bars (|).
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'information safety','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Insert record 3 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'master all kinds of thinking methonds','2017-07-15 12:00:00','2017-07-20
12:00:00','2017-07-25 12:00:00',97);
-- Commit the transaction.
COMMIT;
-- Export the training table, separating columns with vertical bars (|).
DUMP TABLE training INTO FILE '/home/gaussdba/data/training_backup' FIELDS ENCLOSED BY '|';

● Export columns from training table with a condition being specified on the
course_name column, enclosing each column value with a pair of single
quotation marks ('') and separating columns with vertical bars (|).
DUMP QUERY "SELECT course_name,score,exam_date FROM training WHERE course_name = 'SQL
majorization'"
INTO FILE '/home/gaussdba/data/training_query_backup '
COLUMNS ENCLOSED BY ''''
COLUMNS TERMINATED BY '|';

3.12.4 EXP

Description
EXP logically exports data from a database.

Precautions
● When EXP is used to export data, SQL statements are assembled on the client
before being sent to a server, which then receives complete, specific DDL and
DML statements.
● The client operation log is specified by the LOG parameter and records the
EXP command.
● The server audit log {GSDB_DATA}/log/audit records the DDL and DML
statements.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 327


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● User SYS cannot be used to logically export data.


● Users must have required operation permissions for objects which will be
logically exported.
● EXP uses the -h parameter, help parameter, or option parameter, and ends
with ;. or /. Help information about the EXP command can be displayed.
● If FILETYPE=BIN is set, the following three types of files are exported:
metadata files (specified by users), data files (.D files), and LOB files (.L files).
● When data is logically exported, a metadata file and a data subdirectory are
generated in the specified export file path. If no file path is specified, they are
generated in the current path by default. If FILETYPE=BIN is set, the
generated subfiles (data files and LOB files) will be stored in the data
subdirectory. If the specified metadata file and the generated subfiles already
exist, an error will be reported.
● If a file with the same name exists in the target directory when data is
logically exported, the system overwrites the existing file without any prompt.

Syntax
{EXP | EXPORT}[ keyword =param [ , ... ] ] [ ... ];

Parameters
● EXP
Specifies the command for logical export. It is equivalent to EXPORT.
● keyword
Specifies the keyword for logical export.
– USERS
Specifies users whose data is to be exported. Multiple users are separated
by commas (,), and % indicates all users.
No user can export data of user SYS, but user SYS can export the data of
other users. Common users must have the DBA role to export data of
specified users. Common users can export their own data only when they
have the SELECT ANY TABLE or READ ANY TABLE permission.
– TABLES
Specifies the tables to be exported. Multiple tables are separated by
commas (,), and % indicates all tables.
– DIST_RULES
Specifies distribution rules of exported data. Multiple rules are separated
by commas (,), and % indicates all rules.
This parameter is used only when GaussDB 100 is deployed in distributed
mode.
– FILE
Specifies the file that stores exported data. The value is a file name and
its full path, enclosed with double quotation marks (""). If the path is not
specified, the file will be stored in the current directory where the
command is executed.
– FILETYPE
Specifies the type of the files that store exported data.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 328


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The value can be TXT or BIN.


(The default value is TXT.)
– LOG
Specifies the name and path of the log file generated during logical
export. The value must be enclosed with double quotation marks ("").
– COMPRESS
Specifies a compression level for data export.
Value range: [0,9]. 0 indicates no compression, and level 9 indicates the
highest compression ratio.
Default value: 0
– CONTENT
Specifies whether to export table data or table definitions.
Valid value:

▪ ALL: Export both.

▪ DATA_ONLY: Export only data.

▪ METADATA_ONLY: Export only table definitions.


Default value: ALL
– QUERY
Specifies the query condition for exporting a table. The value must be
enclosed with double quotation marks (""), for example, "where
rownum <= 10".
– SKIP_COMMENTS
Specifies whether to add comments when exporting DDL.
Valid value:

▪ Y: Add comments.

▪ N: Do not add comments.


Default value: N
– FORCE
Specifies whether to export the next object when an error occurs.
Valid value:

▪ Y: Export.

▪ N: Do not export.
Default value: N
– SKIP_ADD_DROP_TABLE
Specifies whether to add DROP to the statement before exporting a
table.
Valid value:

▪ Y: Do not add.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 329


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ N: Add.
Default value: N
– SKIP_TRIGGERS
Specifies whether to export triggers.
Valid value:

▪ Y: Do not export.

▪ N: Export.
Default value: N
– QUOTE_NAMES
Specifies whether to enclose exported objects with double quotation
marks ("").
Valid value:

▪ Y: Enclose.

▪ N: Do not enclose.
Default value: N
– COMMIT_BATCH
Specifies the amount of data to be batch submitted.
Value range: natural number. 0 indicates that all the data in a table.
Default value: 1000
– INSERT_BATCH
Specifies the amount of data inserted by a single INSERT statement.
Value range: natural number
Default value: 1
– FEEDBACK
Specifies how many records need to be exported to trigger the display of
the export progress.
Value range: natural number 0 indicates that the progress is displayed
once for a table.
Default value: 10000, indicating the progress is displayed when 10000
records are exported.
– PARALLEL
Specifies the number of concurrent threads.
Value range: natural number

▪ A value from 2 to 16 indicates the number of concurrent threads.

▪ Value 1 or a value greater than 16 indicates a single thread.


Default value: 0
– CONSISTENT
Specifies whether to export the consistency of global data.
Valid value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 330


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Y: Export.

▪ N: Do not export.
Default value: N
– CREATE_USER
Specifies whether to export user definition statements, that is, DDL
statements used for creating users. This keyword must be used in
conjunction with USERS.
Valid value:

▪ Y: Export.

▪ N: Do not export.
Default value: N
– ROLE
Specifies whether to export role (non-SYS) definition statements, that is,
DDL statements used for creating roles. This keyword must be used in
conjunction with USERS.
Valid value:

▪ Y: Export.

▪ N: Do not export.
Default value: N
– GRANT
Specifies whether to export GRANT statements of users or roles. This
keyword must be used in conjunction with USERS and ROLES.
Valid value:

▪ Y: Export.

▪ N: Do not export.
Default value: N
– TABLESPACE
Specifies whether to export all tablespaces. Currently, exporting all
tablespaces allows for only those created by users, excluding system-
reserved ones. The file storage directory is the same as the default
tablespace path of the system.
Valid value:

▪ Y: Export.

▪ N: Do not export.
Default value: N
– TABLESPACE_FILTER
Specifies the filter for specifying tablespaces. Multiple tablespaces are
separated by commas (,). The specified tablespace is used only for
filtering. No creation statement is generated. The symbol % is not
supported, that is, filtering all tablespace is not supported.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 331


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– WITH_CR_MODE
Specifies whether to add CR_MODE for exporting tables and index
scripts.
Valid value:

▪ Y: Add.

▪ N: Do not add.
Default value: N

Examples
● Export data from tab1 and tab2 of the current user.
-- Delete the tab1 and tab2 tables.
DROP TABLE IF EXISTS tab1;
DROP TABLE IF EXISTS tab2;
-- Create the tab1 table.
CREATE TABLE tab1(ID INT NOT NULL,score INT,COMMENT1 VARCAHR(2000));
-- Insert data into the tab1 table.
INSERT INTO tab1 (1,'92','Test');
INSERT INTO tab1 (2,'98','Security');
INSERT INTO tab1 (3,'95','Development');
INSERT INTO tab1 (4,'97','O&M');
-- Commit the transaction.
COMMIT;
-- Create the tab2 table.
CREATE TABLE tab2(ID INT NOT NULL,score INT,COMMENT2 VARCAHR(2000));
-- Insert data into the tab2 table.
INSERT INTO tab2 (11,'93','Test suggestions');
INSERT INTO tab2 (12,'98','Security specifications');
INSERT INTO tab2 (13,'93','Development and maintenance');
INSERT INTO tab2 (14,'96','O&M');
-- Commit the transaction.
COMMIT;
EXP TABLES=tab1,tab2 FILE="file1.dmp";

● Export the data of users EMP, DEPT, and MGR.


-- Delete the existing users EMP, DEPT, and MGR.
DROP USER IF EXISTS EMP;
DROP USER IF EXISTS DEPT;
DROP USER IF EXISTS MGR;
-- Create the EMP, DEPT, and MGR users.
CREATE USER EMP IDENTIFIED BY 'database_123';
CREATE USER DEPT IDENTIFIED BY 'database_123';
CREATE USER MGR IDENTIFIED BY 'database_123';
EXP USERS = EMP,DEPT,MGR FILE="file1.dmp";

● Export data from RULE1 and RULE2.


EXP DIST_RULES = RULE1,RULE2 FILE="file1.dmp";

● Create a user TEST_USER and a role TEST_ROLE, grant permissions to them,


and export the user, role, and user table structure information.
-- Delete the existing user test_user:
DROP USER IF EXISTS test_user;
-- Delete the existing role test_role:
DROP ROLE test_role;
-- Create user test_user:
CREATE USER test_user IDENTIFIED BY 'huawei_123';
-- Create role test_role:
CREATE ROLE test_role IDENTIFIED BY 'exp_user123';
-- Grant permissions to test_user:
GRANT DBA TO test_user;
-- Grant permissions to test_role:
GRANT CREATE TABLE TO test_role;
-- Assign the test_role role to user test_user:
GRANT test_role TO test_user;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 332


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Export user test_user, role test_role, and table structure information of the user:
EXP USERS = TEST_USER CONTENT = METADATA_ONLY CREATE_USER = Y ROLE = Y GRANT = Y
FILE = "file1.dmp";

● Export tablespaces.
EXP USERS = TEST_USER CONTENT = METADATA_ONLY TABLESPACE= Y FILE = "file1.dmp";

● Exports data from a tablespace that is filtered out.


EXP USERS = TEST_USER TABLESPACE_FILTER = A,B FILE = "file1.dmp";

● Export data of specified users as compressed files.


EXP USERS = TEST_USER FILE = "file1.dmp" COMPRESS = 1;

3.12.5 IMP
Description
IMP logically imports data to a database.

Precautions
● When IMP is used to import data, SQL statements are assembled on the
client before being sent to a server, which then receives complete, specific
DDL and DML statements.
● The client operation log is specified by the LOG parameter and records the
IMP command.
● The server audit log {GSDB_DATA}/log/audit records the DDL and DML
statements.
● When you import a .bin file and set content to DATA_ONLY or
METADATA_ONLY, the exported file must use the same content value.
● If IMP uses the -h, help, or option parameter and ends with a semicolon (;)
or slash (/), the help information about IMP will be displayed.
● User SYS cannot be used to logically import data.
● When FILETYPE is TXT, a maximum of 8 KB data of the CLOB, BLOB, TEXT, or
IMAGE type can be imported.
● If FILETYPE is BIN, user, table, and remap cannot be selected. You can only
fully import an exported file.
● IMP can import a file from the database of an earlier version to the current
database.
● If a file with the same name exists in the target directory when data is
logically imported, the system overwrites the existing file without any prompt.

Syntax
{IMP | IMPORT} [ keyword =param [ , ... ] ] [ ... ];

Parameters
● IMP
Specifies the command for logical import. It is equivalent to IMPORT.
● keyword
Specifies the keyword for logical import.
– USERS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 333


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies users whose data is to be imported. Multiple users are separated


by commas (,), and % indicates all users.
A common user must have the DBA role to import data of other users
(except SYS). Common users can import their own data only when they
have the required permissions. For example, to import data for creating a
table, the CREATE TABLE permission is required.
– TABLES
Specifies the tables to be imported. Multiple tables are separated by
commas (,), and % indicates all tables.
– FILE
Specifies the file that stores imported data. The value is a file name and
its full path, enclosed with double quotation marks ("").
The file name must be specified. If no path is specified, the default path
\pkg\bin\ will be used.
– LOG
Specifies the name and path of the log file generated during logical
import. The value must be enclosed with double quotation marks ("").
– FILETYPE
Specifies the type of the files that store imported data.
Valid value:

▪ TXT: TEXT format

▪ BIN: Binary format


Default value: TXT
– FULL
Specifies whether to perform a full import.
Valid value:

▪ Y: Perform.

▪ N: Do not perform.
Default value: N
– CONTENT
Specifies whether to import table data or table definitions.
Valid value:

▪ DATA_ONLY: Import only table data.

▪ METADATA_ONLY: Import only table definitions.

▪ ALL: Import both.


Default value: ALL
– REMAP_SCHEMA
Specifies schema mapping. For example, to import data from users A, B,
C to user D, REMAP_SCHEMA will be A,B,C:D.
– SHOW

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 334


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies whether to print SQL statements or import them.


Valid value:

▪ Y: Print but do not import.

▪ N: Import but do not print.


Default value: N
– FEEDBACK
Specifies how many records need to be imported to trigger the display of
the import progress.
Value range: natural number
Default value: 10000
– IGNORE
Specifies whether to execute the next statement when a statement fails
to be executed.
Valid value:

▪ Y: Execute.

▪ N: Do not execute.
Default value: N
– REMAP_TABLESPACE
Specifies tablespace mapping. For example, to import data from
tablespace A to tablespace B, REMAP_TABLESPACE will be A: B. Use
commas (,) to separate multiple mapping relationships.
– CREATE_USER
Specifies whether to import user definition statements, that is, DDL
statements for creating users.
Valid value:

▪ Y: Import.

▪ N: Do not import.
Default value: N
– PARALLEL
Specifies the number of parallel DML statements.
Value range: [1,32]
Default value: 1
– DDL_PARALLEL
Specifies the number of parallel DDL statements.
Value range: [1,32]
Default value: 1
– NOLOGGING
Specifies whether to enable nologging of redo logs. Only the bin format
is supported.
Valid value:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 335


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Y: Enable.

▪ N: Disable.
Default value: N
– TIMING
Specifies whether to print the timing statistics about the import.
Valid value:

▪ ON: Print.

▪ OFF: Do not print.


Default value: OFF
– BATCH_COUNT
Specifies the number of rows to be imported in each batch. This
parameter takes effect only if filetype=bin is set.
Value range: [1,10000]
Default value: 10000

Examples
● Import data from tab1 and tab2 of the current user.
IMP TABLES=tab1,tab2 FILE="file1.dmp";

● Import the data of users EMP, DEPT, and MGR.


IMP USERS=EMP,DEPT,MGR FILE="file1.dmp";

● Import only the table structure.


IMP USERS=TEST_USER CONTENT=METADATA_ONLY FILE = "file1.dmp";

● Import only user data.


IMP USERS=USR1,USR2 FILE="file1.dmp" CONTENT=DATA_ONLY;

3.12.6 LOAD

Description
During database migration or data backup, you need to import and export data.
GaussDB 100 allows you to run the LOAD statement to import data.

Syntax
LOAD DATA INFILE "file_name" INTO TABLE table_name
[{ FIELDS | COLUMNS } ENCLOSED BY 'ascii_char' [ OPTIONALLY ]]
[{ FIELDS | COLUMNS } TERMINATED BY 'string']
[{ LINES | ROWS } TERMINATED BY 'string']
[ TRAILING COLUMNS( COLUMN1[ , COLUMN2, ... ] ) ]
[ IGNORE uint64_num { LINES | ROWS }]
[ CHARSET string ]
[ THREADS uint32_threads ]
[ ERRORS uint32_num ]
[ NOLOGGING ]
[ NULL2SPACE ]
[ DEBUG ];

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 336


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Parameter Description
● file_name
Specifies the path and name of a file to be imported.
● table_name
Specifies the name of a table to store imported data.
● FIELDS
Specifies the format of each column.
● COLUMNS
Specifies the format of each column. It is equal to FIELDS.
● ENCLOSED BY
Encloses column values with a pair of characters.
● ascii_char
Specifies the characters used to enclose each column value. By default, no
characters are specified.
Value range: a single ASCII character, or an empty string ('') which indicates
that no characters are specified.
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-23.
● OPTIONALLY
Encloses only character and binary data. By default, they are enclosed with a
pair of single quotation marks ('').
● TERMINATED BY
Separates columns with delimiters.
string
Specifies a column delimiter. The default value is a comma (,).
Value range: one or more ASCII characters. A maximum of 10 characters are
allowed.
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-23.
● LINES
Separates rows with delimiters if a record contains multiple rows.
● ROWS
It is a synonym of LINES.
string
Specifies a row delimiter. The default value is \n.
Value range: a single ASCII character
– The value range of ASCII characters in decimal notation is 0-127.
– Hexadecimal ASCII characters range from \x00 to \x7F.
– Common escape characters are listed in Table 3-23.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 337


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● IGNORE
Specifies the number of lines to be ignored.
● uint64_num
Ignores the first uint64_num lines. The default value is 0.
● THREADS
Specifies the number of threads for concurrent data import.
● uint32_threads
Specifies the number of threads for concurrent import. The default value is 1.
Multi-thread import is used to improve efficiency. Deviation is allowed to
collect statistics about the number of errors. In addition, detailed information
about records that cause errors is recorded and the errors will not affect the
subsequent import.
Value range: [1, 128]
● ERRORS
Specifies the number of SQL statements that are allowed to cause errors.
● uint32_num
Specifies the number of SQL statements that are allowed to cause errors. The
default value is 0.
● NOLOGGING
Does not record redo or undo logs for imported data. This parameter is
available only when the target table is set to append only.
● DEBUG
Prints debugging information generated during tool running to a screen.
● CHARSET
Specifies the character set to be imported.
string
Currently, only the UTF8 (without BOM) character set (CHARSET = UTF8)
and GBK character set (CHARSET = GBK) are supported. The former is used
by default.
● TRAILING COLUMNS( COLUMN1[ , COLUMN2, ... ] )
Specifies the columns to which data is to be imported. COLUMN1[,
COLUMN2, ...] specifies column names and at least one name must be
specified.
● NULL2SPACE
Inserts a space to replace NULL, if an empty value of the CHAR or LOB type is
to be imported and NOT NULL is specified.

Table 3-23 Common escape characters

Escape Description ASCII (Decimal) ASCII


Character (Hexadecimal)

\a BELL (BEL) 007 \x07

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 338


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Escape Description ASCII (Decimal) ASCII


Character (Hexadecimal)

\f Form feed (FF). Move to 012 \x0C


the beginning of the
next page.

\n Line feed (LF). Move to 010 \x0A


the beginning of the
next line.

\r Carriage return (CR). 013 \x0D


Move to the beginning
of the current line.

\t Horizontal table (HT). 009 \x09


Jump to the next tab.

\v Vertical tab (VT) 011 \x0B

\\ One backslash (\) 092 \x5C

Two single One single quotation 039 \x27


quotation mark (')
marks ('')

\" One double quotation 034 \x22


mark (")

\? One question mark (?) 063 \x3F

\0 Null character (NULL) 000 \x00

\ooo One- to three-digit octal Three-digit octal -


character code

\xhh One- to two-digit Two-digit -


hexadecimal character hexadecimal
code

The single quotation mark (') is an escape character of SQL. If you need to use it as a
delimiter, use two single quotation marks ('') to represent it. For example:
.... enclosed by ''''....
The outer two single quotation marks are used to enclose the inner ones ('') that represent
a single quotation mark (').
If the character specified by ascii_char is included in the column value, the character will be
escaped again when the column value is exported. For example, if the specified character is
the double quotation mark (") which is included in the column value 1"1, the value will be
exported as "1""1".

Examples
Import data from the training_backup table file to the training_new table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 339


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the training table.


DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'information safety','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Insert record 3 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'master all kinds of thinking methonds','2017-07-15 12:00:00','2017-07-20 12:00:00','2017-07-25
12:00:00',97);
-- Commit the transaction.
COMMIT;
-- Export the training table, separating columns with vertical bars (|).
DUMP TABLE training INTO FILE '/home/gaussdba/data/training_backup' FIELDS ENCLOSED BY '|';
-- Create the training_new table to which data is to be imported.
CREATE TABLE training_new(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Import data from the training_backup table file to the training_new table.
LOAD DATA INFILE "/home/gaussdba/data/training_backup" INTO TABLE training_new FIELDS ENCLOSED
BY '|';
-- Import data from the training_backup table file to the course_name column of the training_new table.
LOAD DATA INFILE "/home/gaussdba/data/training_backup" INTO TABLE training_new TRAILING
COLUMNS(course_name);

3.12.7 RECOVER DATABASE

Description
RECOVER DATABASE replays all logs of the database or replays logs to a specified
time point, restoring database data.

Precautions
● RECOVER DATABASE (excluding RECOVER DATABASE UNTIL CANCEL) can
be executed only after RESTORE DATABASE is executed successfully. If the
RECOVER DATABASE execution fails, the database will fail to be opened.
● RECOVER DATABASE UNTIL CANCEL is executed only when the database
cannot be started due to log damages, and can be executed only in the
MOUNT database state. After running RECOVER DATABASE UNTIL CANCEL,
you must run ALTER DATABASE RESTLOGS or ALTER DATABASE IGNORE
LOGS to start the database.

Syntax
RECOVER DATABASE [ UNTIL [TIME 'time_string' | CANCEL] ]

Parameter Description
● UNTIL TIME
Restores the database to the time point specified by time_string.
● time_string
Specifies a time point for replaying database logs.
The format is YYYY-MM-DD HH-MM-SS, accurate to seconds.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 340


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● UNTIL CANCEL
Restores the database to the last available log point. It is used to ignore
damaged logs and forcibly start the database when the database cannot be
started due to log damages. This operation may incur data loss or damage
data consistency and can be operated only when the database cannot be
started due to log damages.

Examples
● Fully restore the database (by replaying all logs).
-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/full0824.bak';
-- Clear the data directory $GSDB_DATA/data and restore data files in the NOMOUNT database state.
RESTORE DATABASE FROM '?/full0824.bak';
-- Fully restore the database (by replaying all logs).
RECOVER DATABASE;

● Restore the database to a specified time point (by replaying logs at a


specified time point).
-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/fullbackup01.bak';
-- Clear the data directory $GSDB_DATA/data and restore data files in the NOMOUNT database state.
RESTORE DATABASE FROM '?/fullbackup01.bak';
-- Restore the database to a specified time point (by replaying logs at a specified time point).
RECOVER DATABASE UNTIL TIME '2018-06-29 15:28:54';

● Restore the database to the last available log point in the MOUNT database
state, ignoring the subsequent log damages.

● If the database can be restored to CONSISTENT POINT, the data consistency can
be ensured and ALTER DATABASE OPEN RESTLOGS can be executed successfully.
● Otherwise, the data consistency cannot be ensured. In this case, you can start the
database only by running ALTER DATABASE OPEN IGNORE LOGS.
RECOVER DATABASE UNTIL CANCEL;
ALTER DATABASE OPEN RESTLOGS;

3.12.8 RESTORE DATABASE

Description
RESTORE DATABASE restores physical files and restores data files from backup
sets.

Precautions
To restore the database, the database must be in the NOMOUNT state, the
required data directory exists, and data files have been cleaned.

Syntax
RESTORE DATABASE FROM path [ DISCONNECT FROM SESSION ] [ PARALLELISM count ] [TABLESPACE
tablespace_name]

Parameter Description
● path

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 341


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies a backup file path. The value is the same as that of format in the
BACKUP statement.
● DISCONNECT FROM SESSION
Specifies asynchronous execution. The database returns a response
immediately after receiving the RESTORE request. To check whether the
execution is successful, query the status column in DV_BACKUP_PROCESSES.
If this parameter is not specified, synchronous execution is performed by
default. The database returns the result after the execution is complete.
● PARALLELISM count
If the backup media is a disk, concurrent threads can be enabled to restore
data in parallel, improving the restoration performance.
The value of count is an integer within the range of [1, 8]. If the number of
concurrent threads is not specified, four concurrent threads are started by
default.
● TABLESPACE tablespace_name
Specifies a tablespace whose data is to be restored based on full backup.

Examples
● Restore the database from a disk.
-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/full0824.bak';
-- Restore the database in the NOMOUNT database state.
RESTORE DATABASE FROM '?/full0824.bak';

● Asynchronously restore the database from a disk.


-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/full0825.bak';
-- Asynchronously restore the database in the NOMOUNT database state.
RESTORE DATABASE FROM '?/full0825.bak' DISCONNECT FROM SESSION;

● Restore the database from a disk and specify the number of concurrent
threads.
-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/full0826.bak';
-- Restore the database in the NOMOUNT database state and set the number of concurrent threads
to 2.
RESTORE DATABASE FROM '?/full0826.bak' PARALLELISM 2;

● Restore the data of a specified tablespace from the full backup file.
-- Fully back up the database to a disk to in the OPEN database state.
BACKUP DATABASE FULL FORMAT '?/full0826.bak';
-- Restore the data of the existing tsp tablespace in the NOMOUNT database state.
RESTORE DATABASE FROM '?/full0826.bak' TABLESPACE tsp;

3.12.9 RESTORE BLOCKRECOVER


Description
RESTORE BLOCKRECOVER restores a damaged disk data page by using backup
sets. This command is invoked only by ztrst and cannot be executed by users.
After invoking this command, ztrst backs up damaged pages to its temporary
directory and then restores the pages.

Precautions
● This command is invoked only by ztrst and cannot be executed by users.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 342


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The database must contain all redo logs generated from the time when the
backup started to the time when the disk data page became faulty.
● Data pages of temporary and nologging tablespaces cannot be restored.
● Data page of tablespace description cannot be restored.

Syntax
RESTORE BLOCKRECOVER DATAFILE file_id PAGE page_id FROM backup_path

Parameter Description
● file
Specifies the serial number of the data file where the damaged page is
located. The value range is [0,1022].
When a page of the database is damaged, the serial number of the
corresponding data file is recorded in run logs. Therefore, you can obtain the
serial number from run logs.
● page
Specifies the serial number of the damaged page in the data file. The
minimum value is 1, and the maximum value is the maximum number of
pages in the data file.
When a page of the database is damaged, the serial number of the damaged
page in the data file is recorded in run logs. Therefore, you can obtain the
serial number from run logs.
● path
Specifies the path of backup files. The value is the same as that of
dest_format in the BACKUP statement.

Examples
Restore a damaged page using a backup set in the MOUNT database state.
RESTORE BLOCKRECOVER DATAFILE 3 PAGE 2 FROM '?/full0824.bak';

3.12.10 SHUTDOWN
Description
SHUTDOWN gracefully shuts down the database. After SHUTDOWN is executed,
TCP listening is stopped. After all session transactions are complete, the main
process is stopped.

Precautions
● An error is returned if the SHUTDOWN statement is executed during
transaction execution.
● An error is returned if the SHUTDOWN statement is executed when the
primary server is demoted to the standby.
● If IMMEDIATE and ABORT are not specified, the NORMAL mode is used by
default. In NORMAL mode, no new connections are allowed after
SHUTDOWN is executed, and the main process is stopped after all
transactions are complete.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 343


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Syntax
SHUTDOWN [ IMMEDIATE | ABORT ]

Parameter Description
● IMMEDIATE
Stops receiving connection requests from clients, rolls back incomplete
transactions, and finally stops the main process.
● ABORT
Stops receiving connection requests from clients and immediately stops the
main process.

Examples
Shut down the database immediately.
SHUTDOWN ABORT;

3.12.11 VALIDATE

Description
VALIDATE performs checksum verification on a data page to check whether the
page is damaged. If a success message is returned, the page is undamaged. This
command is invoked only by ztrst and cannot be executed by users.

Precautions
● This command is invoked only by ztrst and cannot be executed by users.
● The database status must be MOUNT or OPEN.
● The value of PAGE_CHECKSUM cannot be OFF.

Syntax
VALIDATE DATAFILE file_id PAGE page_id

Parameter Description
● file_id
Specifies the ID of the data file where the damaged page is located. The value
range is [0, 1022].
● page_id
Specifies the ID of the damaged page in the data file. The minimum value is 1
and the maximum value is the maximum number of pages in the data file.

Examples
Validate the page 2 in data file 3.
VALIDATE DATAFILE 3 PAGE 2;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 344


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13 SQL Syntax


GaussDB 100 fully supports the SQL-89 standard and partially supports later
standards, such as SQL-92, SQL:1999, and SQL:2003. In addition to SQL standards,
various SQL syntax ecosystems provided by GaussDB 100 are also supported.

3.13.1 DCL Syntax


Data Control Language (DCL) is used to set or change database transactions, user
permissions, and to lock tables.

Transaction Management

Table 3-24 SQL statements for transaction management


Description SQL Statement

Committing a transaction COMMIT

Rolling back a transaction ROLLBACK

Savepoint Operations
Savepoint operations include creating and deleting savepoints. For details, see
Table 3-25.

Table 3-25 SQL statements for savepoint operations


Description SQL Statement

Create a savepoint. SAVEPOINT

Delete a savepoint. REALEASE SAVEPOINT

Event Isolation

Table 3-26 SQL statements for event isolation


Description SQL Statement

Event isolation SET TRANSACTION

Granting Permissions
In permission management, you can grant permissions to users or roles, revoke
permissions, create roles, and delete roles.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 345


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The following table lists the related SQL statements.

Table 3-27 SQL statements for permission management

Description SQL Statement

Granting permissions GRANT

Revoking permissions REVOKE

Table Locking
The SHARE and EXCLUSIVE table locking modes are supported. The following
table lists the related SQL statements.

Table 3-28 SQL statements for locking tables

Description SQL Statement

Locking a table LOCK TABLE

Shutdown

Table 3-29 SQL statements for shutdown

Description SQL Statement

Stopping the database SHUTDOWN

3.13.2 DDL Syntax


Data Definition Language (DDL) is used to define or modify database objects, for
example, tables, indexes, views, synonyms, databases, sequences, users, roles,
tablespaces, profiles, and sessions.

Defining a Database
A database is a warehouse for organizing, storing, and managing data. Defining a
database includes creating a database and modifying database attributes. The
following table lists the related SQL statements.

Table 3-30 SQL statements for defining a database

Description SQL Statement

Creating a database CREATE DATABASE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 346


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Description SQL Statement

Modifying database attributes ALTER DATABASE

Defining a Tablespace
A tablespace is used to manage data objects and corresponds to a catalog on a
disk. The following table lists the related SQL statements.

Table 3-31 SQL statements for defining a tablespace

Description SQL Statement

Creating a tablespace CREATE TABLESPACE

Modifying tablespace attributes ALTER TABLESPACE

Deleting a tablespace DROP TABLESPACE

Defining a Table
A table is a special data structure in a database and is used to store data objects
and relationship between data objects. The following table lists the related SQL
statements.

Table 3-32 SQL statements for defining a table

Description SQL Statement

Creating a table CREATE TABLE

Modifying table attributes ALTER TABLE

Deleting a table DROP TABLE

Deleting all data from a table TRUNCATE TABLE

Table Flashback
The time in the past to which a table can be flashed back depends on the amount
of undo data in the system. The following table lists the related SQL statements.

Table 3-33 SQL statements for table flashback

Description SQL Statement

Table flashback FLASHBACK TABLE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 347


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Defining a Partitioned Table


A partitioned table is a logical table used to improve query performance and does
not store data (data is stored in common tables). The following table lists the
related SQL statements.

Table 3-34 SQL statements for defining a partitioned table

Description SQL Statement

Creating a partitioned table CREATE TABLE PARTITION

Creating a partition ALTER TABLE

Modifying partitioned table attributes ALTER TABLE

Deleting a partition ALTER TABLE

Deleting a partitioned table DROP TABLE

Defining an Index
An index indicates the sequence of values in one or more columns in a database
table. It is a data structure that improves the speed of data access to specific
information in a database table. The following table lists the related SQL
statements.

Table 3-35 SQL statements for defining an index

Description SQL Statement

Creating an index CREATE INDEX

Modifying index attributes ALTER INDEX

Deleting an index DROP INDEX

Defining a Role
A role is used to manage permissions. For database security, management and
operation permissions can be granted to different roles. The following table lists
the related SQL statements.

Table 3-36 SQL statements for defining a role

Description SQL Statement

Creating a role CREATE ROLE

Deleting a role DROP ROLE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 348


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Defining a User
A user is used to log in to a database. Different permissions can be granted to
users for managing data accesses and operations of the users. The following table
lists the related SQL statements.

Table 3-37 SQL statements for defining a user


Description SQL Statement

Creating a user CREATE USER

Modifying user attributes ALTER USER

Deleting a user DROP USER

Defining a View
A view is a virtual table exported from one or more basic tables. It is used to
control data accesses of users. The following table lists the related SQL
statements.

Table 3-38 SQL statements for defining a view


Description SQL Statement

Creating a view CREATE VIEW

Deleting a view DROP VIEW

Defining a Sequence
A sequence can generate numbers with the same interval and the numbers are
used as primary key values. When a sequence value is generated, the sequence is
incremented. The following table lists the related SQL statements.

Table 3-39 SQL statements for defining a sequence


Description SQL Statement

Creating a sequence CREATE SEQUENCE

Modifying sequence attributes ALTER SEQUENCE

Deleting a sequence DROP SEQUENCE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 349


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Defining a Synonym
A synonym is an alias or alternate name for a schema object. It allows users to
easily access database objects owned by other users and saves database space.
The following table lists the related SQL statements.

Table 3-40 SQL statements for defining a synonym


Description SQL Statement

Creating a synonym CREATE SYNONYM

Deleting a synonym DROP SYNONYM

Defining a Comment
You can use the COMMENT statement to add to the data dictionary a comment
about a table, a table column, or view. The following table lists the related SQL
statements.

Table 3-41 SQL statements for defining a comment


Description SQL Statement

Commenting a table or table column COMMENT ON

Modifying System Parameters

Table 3-42 SQL statements for modifying system parameters


Description SQL Statement

Modifying System Parameters ALTER SYSTEM

Killing a session ALTER SYSTEM KILL SESSION

Recycle Bin
A recycle bin is temporary storage for objects, such as indexes, tablespaces, and
tables deleted by running the DROP statement. To permanently remove them, run
the PURGE statement. To roll back the DROP operation, run the FLASHBACK
statement. The following table lists the related SQL statements.

Table 3-43 SQL statements for purging a recycle bin


Description SQL Statement

Purging a recycle bin PURGE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 350


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Defining a Profile
A profile is a set of limits on database resources available to users. The following
table lists the related SQL statements.

Table 3-44 SQL statements for defining a profile

Description SQL Statement

Creating a profile CREATE PROFILE

Modifying profile attributes ALTER PROFILE

Deleting a profile DROP PROFILE

Session Management
A session is a connection established between a user and the database. The
following table lists the related SQL statements.

Table 3-45 SQL statements for session management

Description SQL Statement

Modifying a session ALTER SESSION

Killing a session ALTER SYSTEM KILL SESSION

Others
The following table lists other DDL statements.

Table 3-46 Other statements

Description SQL Statement

Collecting statistics ANALYZE

Creating SQL mapping ALTER SQL_MAP

Deleting SQL mapping DROP SQL_MAP

3.13.3 DML Syntax


Data Manipulation Language (DML) is used to perform operations on data in
database tables, such as inserting, updating, and querying data.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 351


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Data Operations

Table 3-47 SQL statements for data operations

Description SQL Statement

Inserting data INSERT

Deleting data DELETE

Updating data UPDATE

Merging data MERGE

Replacing data REPLACE

Others

Table 3-48 Other statements

Description SQL Statement

Viewing an execution plan EXPLAIN PLAN

3.13.4 DDL Syntax


Data Query LanguageData (DQL) is used to query data in the database.

Table 3-49 SQL statements for data query

Function SQL Statement

Querying data SELECT

3.13.5 ALTER DATABASE

Description
ALTER DATABASE modifies a database.

Precautions
● To run this statement, you must have the ALTER DATABASE system
permission.
● Files cannot be automatically managed on the standby database server.
● Log files cannot be added to or deleted from the standby database server.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 352


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Syntax
ALTER DATABASE [ database_name ]
{ startup_clauses
| logfile_clauses
| archlogfile_clauses
| standby_database_clauses
| alter_datafile_clauses
| clear_logfile_clauses
| SWITCHOVER
| FAILOVER
| CANCEL RESTRICT
| CONVERT TO { READONLY | READWRITE } |{[ CASCADED ] PHYSICAL STANDBY [ MOUNT ] }
}

● startup_clauses:
{ MOUNT | OPEN [ RESETLOGS | READ ONLY | READ WRITE | RESTRICT | FORCE IGNORE LOGS] }

● logfile_clauses:
{ [ ARCHIVELOG | NOARCHIVELOG ] add_logfile_clauses | drop_logfile_clauses }

– add_logfile_clauses:
ADD LOGFILE redo_log_file_spec

redo_log_file_spec:
( { 'file_name' SIZE integer [ K | M | G | T | P | E ]
} [ , ... ]
)

– drop_logfile_clauses:
DROP LOGFILE ( 'file_name' )

● archlogfile_clauses:
DELETE ARCHIVELOG { ALL | UNTIL TIME 'date_string' } [ FORCE ]

● standby_database_clauses:
SET STANDBY DATABASE TO MAXIMIZE { PROTECTION
| AVAILABILITY
| PERFORMANCE
}

● alter_datafile_clauses:
DATAFILE { { 'file_name' | file_number
} [, ...]
}
{ autoextend_clause | resize_clause }

– autoextend_clause:
AUTOEXTEND { OFF
| ON [ NEXT integer [ K | M | G] ]
[ MAXSIZE { integer [ K | M | G]
| UNLIMITED
}
]
}

– resize_clause clause:
RESIZE integer [ K | M | G ]

– clear_logfile_clauses :
CLEAR LOGFILE file_id

Parameters
● database_name
Specifies the name of a database to be modified. If the database name is not
specified, the database in the MOUNT state is used.
● startup_clauses
Specifies the database status (MOUNT or OPEN).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 353


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– MOUNT: The database is mounted but not started. In this state, only
database administrators can modify the database and users cannot
establish connections or sessions with the database.
An error will be reported if you change the status of a database in the
MOUNT state to MOUNT again.
– OPEN: The database is successfully started.
When the database status is set to OPEN, the data dictionary is initialized
and heap file metadata is loaded to the memory.

▪ RESETLOGS resets the serial number of the database log to 1.

▪ READ WIRTE enables read and write. It is the default state after the
database status becomes OPEN.

▪ READ ONLY enables only read. In this case, the database supports
only query.

▪ RESTRICT loads only core system catalogs, allowing for user SYS
only.
Before upgrading the database, switch the database status to
RESTRICT.
In RESTRICT mode, indexes can be recreated on system catalogs by
strictly following the provided instructions.

▪ FORCE IGNORE LOGS forcibly ignores log files when the database is
in the OPEN state.
It is used to forcibly ignore damaged logs when database log files are
damaged and cannot be restored to CONSISTENT POINT.
This operation cannot ensure database consistency. If the database is
not restored to CONSISTENT POINT, a message is displayed in run
logs and OPEN_INCONSISTENCY in the DV_DATABASE view
changes to TRUE.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 354


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● You can change the database status from MOUNT to OPEN, but cannot change it
from OPEN to MOUNT.
● You can change the database from the OPEN state to an OPEN substate, or
change between OPEN substates except READ WRITE and READ ONLY only by
performing the following steps. Otherwise, an error occurs.
1. Run the python zctl.py -t stop command to stop the database.
2. Start the database in NOMOUNT or MOUNT mode and connect it.
3. Switch the database status to a child status of OPEN.
● The RESTRICT mode is dedicated for upgrade. This mode needs to be used
together with the upgrade script upgrade.py. For details, see Installation and
Deployment > Installation Preparation > Upgrading a Database in GaussDB 100
V300R001C00 User Guide (Standalone). Other operations will cause database
exceptions, for example, abnormal exit.
● In RESTRICT mode, indexes can be recreated on system catalogs. You are advised
to perform this operation only when absolutely necessary. If the index structure of
system catalogs is sparse, occupying much space and affecting the service running
speed, you are advised to recreate indexes in RESTRICT mode. In RESTRICT mode,
run ALTER SYSTEM LOAD DICTIONARY FOR xxx; to load all system catalogs
before recreating indexes. You are not allowed to create system catalog indexes
online or change tablespaces of the system catalogs. In primary/standby mode,
when you rebuild indexes of the system catalog in the primary database, the
standby database must be in RESTRICT mode.
● logfile_clauses
Adds or deletes log files.
Enables and disables redo log archiving in the MOUNT database state. You
can add and delete redo logs only when the database is in the OPEN state.
– ARCHIVELOG
Enables redo log archiving.
– NOARCHIVELOG
Disables redo log archiving.

In primary/standby deployment of a database, you can set the redo log mode
only to ARCHIVELOG.
– add_logfile_clauses
Adds one or more redo log files to the primary server. If no directory is
specified, files are added to the $GSDB_HOME/data directory by default.
redo_log_file_spec
Specifies one or more redo log files. The parameter value must contain
the file size, and the file name or absolute path. The file size is unlimited.

▪ The total number of log files on the primary and standby servers
cannot exceed 256. If the number exceeds 256, an error will be
reported.

▪ SIZE integer [ K | M | G | T | P | E ]
Specifies the file size. The default unit is byte. K indicates KB, M
indicates MB, G indicates GB, T indicates TB, and E indicates EB.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 355


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– drop_logfile_clauses
Deletes one redo log file from the primary server.
● archlogfile_clauses
Deletes archived log files.
– ALL
Deletes all archived logs that meet the deletion policy.
The deletion policy specifies whether the space occupied by archived logs
has reached 85% of MAX_ARCH_FILES_SIZE, whether archived logs have
been backed up, and whether archived logs have been replayed by the
standby node. You can configure the deletion policy through the FORCE
keyword and the ARCH_CLEAN_IGNORE_STANDBY parameter. For
details about the parameters, see Parameters > Databases > Archive
Logs in GaussDB 100 V300R001C00 Database Reference.
– UNTIL TIME 'date_string'
Deletes the archived logs that meet the deletion policy and are generated
before the specified time.

▪ date_string: Specifies a time. The format can be YYYY-MM-DD


hh:mm:ss or YYYY-MM-DD.
– FORCE
Deletes archived logs earlier than the time specified by rcy_point no
matter whether they are backed up. The FORCE clause is a high-risk
statement and use it only when necessary.
● standby_database_clauses
Specifies data protection mode on the standby database server.
– PROTECTION This command can be executed only on the standby node
MOUNT.
Highest-level data protection. Transactions on the primary database
server can be committed only after the standby database server receives
the redo logs. This mode ensures that no data is lost, but has high
requirements on network conditions and greatly compromises database
performance.
– AVAILABILITY
Highest-level data availability. Data protection level in this mode is only
second to PROTECTION. In principle, transactions on the primary
database server can be committed only after the standby database server
receives the redo logs. If the redo logs cannot be written onto the
standby server, the data protection mode is temporarily changed to
PERFORMANCE until the standby server receives the redo logs. This
mode ensures that data on the standby server running properly is not
lost, but compromises database performance to some extent.
– PERFORMANCE
Highest-level data performance. Transactions on the primary server are
committed no matter whether the standby server receives the redo logs.
However, if the standby server fails to receive the redo logs related to the
transactions committed by the primary server, the transaction data will be
lost.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 356


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● alter_datafile_clauses
Modifies attributes of one or more data files in the database. Currently, only
automatic extension of data files can be changed.
Data files can be specified by file name or file number.
– file_name: file name. The value can be a file name or an absolute path. If
the value is a file name, the database generates a full path based on the
file name and the data directory in the database instance path specified
by the ALTER DATABASE statement. If the value is an absolute path, the
database uses it without additional processing. The maximum length of
file_name is 256 bytes.
– file_number: ID of a data file in the database. For details, see the ID
column in Data Dictionary and Views > Dynamic Performance Views >
DV_DATA_FILES in GaussDB 100 V300R001C00 Database Reference.
– autoextend_clause
Enables or disables automatic extension, and specifies the extension size
and upper limit.

▪ OFF
Disables automatic extension.

▪ ON
Enables automatic extension.
If automatic extension is enabled (ON), you can configure the
following parameters:
○ NEXT: extension size. If this parameter is not set, the default
value 16MB is used.
○ MAXSIZE: extension upper limit. The upper limit cannot exceed
the size of the current file. If this parameter is set to UNLIMITED
or not set, the upper limit 8TB is used. The maximum value of
the upper limit must be less than 8TB. If both MAXSIZE and
NEXT are set, the value of MAXSIZE must be no less than that
of NEXT.
UNLIMITED
The automatic extension has no upper limit.
– resize_clause
Changes the size of a data file. You can obtain the current size of a data
file based on the file name or ID identified by the FILE_NAME or ID
column in Data Dictionary and Views > Dynamic Performance Views >
DV_DATA_FILES in GaussDB 100 V300R001C00 Database Reference.
This statement cannot be executed in the READ ONLY mode under the
OPEN database state. It can be executed in other modes under the OPEN
state.
When reducing the file size, ensure it is not smaller than the minimum
size required by the database system. The minimum size required by the
SYSTEM tablespace and UNDO tablespace is 128 MB, and that of other
data files is 1 MB.
When reducing the file size, ensure that the storage area of valid data is
not damaged. Otherwise, the statement execution will fail.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 357


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

To obtain the number of pages occupied by valid data, see the value of
the HIGH_WATER_MARK column in Data Dictionary and Views >
Dynamic Performance Views > DV_DATA_FILES in GaussDB 100
V300R001C00 Database Reference. To calculate the required file size,
multiply the obtained value by the size of each page.

▪ integer [ K | M | G ]
Specifies the size of each data file.
K: The unit is KB.
M: The unit is MB.
G: The unit is GB.
● SWITCHOVER
Switches between the primary and standby database servers.
● FAILOVER
Promotes the standby database server to the primary.
● CANCEL RESTRICT
Cancels the RESTRICT state. After the database is upgraded, you need to
cancel the RESTRICT state.
Perform the cancellation after the execution of the ALTER SYSTEM INIT
DICTIONARY statement is complete.
● CONVERT TO
– [CASCADED] PHYSICAL STANDBY [MOUNT]
Changes the database role to standby (PHYSICAL STANDBY) or cascaded
standby (CASCADED PHYSICAL STANDBY). This operation can be
performed only in the MOUNT database state.
If MOUNT is specified, only the role is changed and the database status
is not changed. If MOUNT is not specified, the database automatically
changes to the READ ONLY mode under the OPEN state after the role is
changed.
– READONLY| READWRITE
Changes the database status. READWRITE and READONLY can be
switched online. In primary/standby deployment, such a switchover can
be performed only on the primary database.

▪ READWIRTE enables read and write. It is the default mode in the


OPEN database state.

▪ READONLY enables only read. In this mode, the database supports


only query.
● clear_logfile_clause
Clears and rebuilds the log file specified by file_id. If the database cannot be
started due to the damages of a log file header and the log file can be
cleared, you can use this clause to clear and rebuild the log file so that the
database can be started.
This operation can be performed in the MOUNT or OPEN database state.
– file_id: Specifies the ID of the log file to be cleared and rebuilt. Only log
files in the UNUSED or INACTIVE state are supported.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 358


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
● Change the database status.
-- Change the database status to MOUNT.
ALTER DATABASE MOUNT;
-- Change the database status from MOUNT to OPEN.
ALTER DATABASE OPEN;
-- Reset the database log sequence number to 1 in the MOUNT database state.
ALTER DATABASE OPEN RESETLOGS;
-- Change the database to read-only in the MOUNT database state.
ALTER DATABASE OPEN READ ONLY;
-- Change the database to readable/writable in the MOUNT database state.
ALTER DATABASE OPEN READ WRITE;
-- Change the database status from MOUNT to RESTRICT.
ALTER DATABASE OPEN RESTRICT;

● Add or delete log files.


-- Enable redo log archiving in the MOUNT database state.
ALTER DATABASE ARCHIVELOG;
-- Disable redo log archiving in the MOUNT database state. (This parameter cannot be set to this
value when the database is deployed in primary/standby mode.)
ALTER DATABASE NOARCHIVELOG;
-- In the OPEN database state, add a redo log file named test1 with the size 1 GB.
ALTER DATABASE ADD LOGFILE( 'test1' SIZE 1G);
-- In the OPEN database state, delete the redo log file test1.
ALTER DATABASE DROP LOGFILE( 'test1' );

● Delete archived log files.


-- Delete all archived logs that meet the deletion policy.
ALTER DATABASE DELETE ARCHIVELOG ALL;
-- Delete all archived logs that meet the deletion policy (regardless of whether they are backed up).
ALTER DATABASE DELETE ARCHIVELOG ALL FORCE;
-- Delete archived logs that meet the deletion policy and are generated before 2019-08-26 11:00:00.
ALTER DATABASE DELETE ARCHIVELOG UNTIL TIME '2019-08-26 11:00:00';
-- Delete the archived logs that meet the deletion policy (regardless of whether they are backed up)
and are generated before 2019-08-26 11:00:00.
ALTER DATABASE DELETE ARCHIVELOG UNTIL TIME '2019-08-26 11:00:00' FORCE;

● Change the protection mode of data in the standby database.


-- In the MOUNT database state, change the data protection mode to MAXIMIZE PROTECTION.
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PROTECTION;
-- Change the data protection mode to MAXIMIZE AVAILABILITY.
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE AVAILABILITY;
-- Change the data protection mode to MAXIMIZE AVAILABILITY.
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE AVAILABILITY;

● Change the data file attributes in the database.


-- Disable automatic extension for the data file whose file ID is 1.
ALTER DATABASE DATAFILE 1 AUTOEXTEND OFF;
-- Change the extension size of the data file whose file ID is 1 to 20 MB.
ALTER DATABASE DATAFILE 1 AUTOEXTEND ON NEXT 20M;
-- Change the extension upper limit of the data file whose file ID is 1 to 10 GB.
ALTER DATABASE DATAFILE 1 AUTOEXTEND ON MAXSIZE 10G;
-- Change the extension upper limit of the data file whose file ID is 1 to UNLIMITED.
ALTER DATABASE DATAFILE 1 AUTOEXTEND ON MAXSIZE UNLIMITED;

● Change the database role.


-- Change the database role to standby in the MOUNT database state.
ALTER DATABASE CONVERT TO PHYSICAL STANDBY;
-- Change the database role to cascaded-standby in the MOUNT database state.
ALTER DATABASE CONVERT TO CASCADED PHYSICAL STANDBY;
-- Change the database role to standby in the MOUNT database state and does not change the
status to OPEN.
ALTER DATABASE CONVERT TO PHYSICAL STANDBY MOUNT;
-- Change the database role to cascaded-standby in the MOUNT database state and does not change
the status to OPEN.
ALTER DATABASE CONVERT TO CASCADED PHYSICAL STANDBY MOUNT;

● Change the database status.


-- Change the database status to READWRITE.
ALTER DATABASE CONVERT TO READWRITE;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 359


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Change the size of each data file.


-- Change the size of each data file to 128 MB in the MOUNT database state.
ALTER DATABASE DATAFILE 'USER' RESIZE 128M;

● Delete the log file whose ID is 0.


ALTER DATABASE CLEAR LOGFILE 0;

3.13.6 ALTER INDEX


Description
ALTER INDEX modifies an index definition.

Precautions
● You can modify your own indexes without additional permissions. To modify
indexes of other users, the ALTER ANY INDEX system permission is required.
Common users cannot modify objects of system users.
● The specified index name must exist. Otherwise, an error will be reported.
● Profiles cannot be created during database restart or rollback.

Syntax
ALTER INDEX [ schema_name. ]index_name
{ rebuild_clauses
| rename_clauses
}

Parameter Description
● [schema_name.]index_name
Specifies the name of an index to be modified.
● rebuild_clauses
– REBUILD ONLINE
Creates or rebuilds an index online. The advantage of creating or
rebuilding an index online is that the time for adding exclusive locks to
tables is greatly reduced, thereby preventing online service blocking.
– REBUILD TABLESPACE tablespace_name
Copies index data to other tablespaces.
● rename_clauses
– RENAME TO [schema_name.] index_name_new
Specifies the name of an index to be renamed.

Examples
● Rebuild an index on the posts table online and rename the index.
-- Delete the posts table.
DROP TABLE IF EXISTS posts;
-- Create the posts table.
CREATE TABLE posts(post_id CHAR(2) NOT NULL, post_name CHAR(6) PRIMARY KEY, basic_wage INT,
basic_bonus INT);
-- Delete the idx_posts index.
DROP INDEX IF EXISTS idx_posts;
-- Create the idx_posts index.
CREATE INDEX idx_posts ON posts(post_id ASC, post_name) ONLINE;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 360


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Rebuild the idx_posts index online.


ALTER INDEX idx_posts REBUILD ONLINE;
-- Rename the index.
ALTER INDEX idx_posts RENAME TO idx_posts_temp;

● Rebuild the partitioned index online for the partitioned table education and
rename the index.
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the partitioned table education.
CREATE TABLE education(staff_id INT NOT NULL, highest_degree CHAR(8), graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70))
PARTITION BY LIST(highest_degree)
(
PARTITION doctor VALUES ('DOCTOR'),
PARTITION master VALUES ('MASTER'),
PARTITION undergraduate VALUES ('SCHOLAR')
);
-- Insert record 1 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'DOCTOR','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'DOCTOR','Northwest A&F University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'MASTER','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 4 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(15,'SCHOLAR','Xi'an University of Architecture and Technology','2017-07-06 12:00:00','NOT
211 OR 985');
-- Insert record 5 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(18,'MASTER','Xi'an University of Technology','2017-07-06 12:00:00','not 211 or 985');
-- Insert record 6 into the partitioned table education.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(20,'SCHOLAR','Capital Normal University','2017-07-06 12:00:00','211&985');
COMMIT;
-- Delete the idx_training index.
DROP INDEX IF EXISTS idx_training;
-- Create a partitioned index.
CREATE INDEX idx_training ON education(staff_id ASC, highest_degree) LOCAL (PARTITION doctor,
PARTITION master, PARTITION undergraduate);
-- Rebuild the partitioned index.
ALTER INDEX idx_training REBUILD ONLINE;
-- Rename the partitioned index.
ALTER INDEX idx_training RENAME TO idx_training_temp;

3.13.7 ALTER PROFILE

Description
ALTER PROFILE modifies a profile.

Precautions
● To run this statement, you must have the ALTER PROFILE system permission.
● The default profile can also be modified.
● PASSWORD_LIFE_TIME, PASSWORD_LOCK_TIME,
PASSWORD_GRACE_TIME, and PASSWORD_REUSE_TIME can be set to
scores (1 minute = 1/1440 days, and 1 second = 1/86400 days).
● Profiles cannot be created during database restart or rollback.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 361


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Syntax
ALTER PROFILE profile_name LIMIT password_parameters [ ... ]

password_parameters:
{ { FAILED_LOGIN_ATTEMPTS
| PASSWORD_LIFE_TIME
| PASSWORD_LOCK_TIME
| PASSWORD_GRACE_TIME
| PASSWORD_REUSE_TIME
| PASSWORD_REUSE_MAX
| SESSIONS_PER_USER
}
{ expr | UNLIMITED | DEFAULT }
}

Parameter Description
● profile_name
Specifies the name of a profile to be modified. If the profile name contains
spaces or special characters other than _#$, enclose the name with double
quotation marks ("") or backquotes (``).
● FAILED_LOGIN_ATTEMPTS
Specifies the maximum number of login attempts allowed before an account
is locked.
Default value: 10
● PASSWORD_LIFE_TIME
Specifies the maximum number of days that a password can be used.
Default value: 180
● PASSWORD_LOCK_TIME
Specifies the number of days an account will be locked after the specified
number of consecutive failed login attempts.
Default value: 1
● PASSWORD_GRACE_TIME
Specifies the number of days after the grace period begins during which a
warning is issued and login is allowed. If the database password is not
changed during this period, the password becomes invalid after the grace
period expires.
Default value: 7
● PASSWORD_REUSE_TIME
Specifies the number of days during which a password cannot be reused.
The value is a positive number. The integral part indicates the number of days
and its decimal part can be converted into hours, minutes, and seconds.
If the parameter value is changed to a smaller one, new passwords will be
checked based on the new parameter value.
If the parameter value is changed to a larger one (for example, changed from
a to b), the historical passwords before b days probably can be reused
because these historical passwords may have been deleted. New passwords
will be checked based on the new parameter value. The absolute time is used.
Historical passwords are recorded using absolute time and do not recognize
time changes.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 362


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● PASSWORD_REUSE_MAX
Specifies the number of password changes required before the current
password can be reused. If the parameter value is changed to a smaller one,
new passwords will be checked based on the new parameter value. If the
parameter value is changed to a larger one (for example, changed from a to
b), the historical passwords before the last b passwords probably can be
reused because these historical passwords may have been deleted. New
passwords will be checked based on the new parameter value.
PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME must be set in
conjunction with each other.
Set the two parameters as follows:
– If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to
UNLIMITED. The password can be reused without any restrictions.
– If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to
specified values, the password can be reused only when the conditions
specified by both the parameters are met.
– If either of PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME is
set to a specified value and the other is set to UNLIMITED, the password
cannot be reused. The value is a positive integer.
● SESSIONS_PER_USER
Specifies the number of connections of per user. The value must be less than
the maximum number of connections in the connection pool. This parameter
takes effect only after RESOURCE_LIMIT is enabled. To enable
RESOURCE_LIMIT, run ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;.
● UNLIMITED
Specifies no limitations.
● DEFAULT
Uses default values of the parameters.

Examples
Modify the pro_common profile.
-- Delete the pro_common profile.
DROP PROFILE pro_common CASCADE;
-- Create the pro_common profile.
CREATE PROFILE pro_common LIMIT PASSWORD_GRACE_TIME 10 PASSWORD_LOCK_TIME DEFAULT
PASSWORD_LIFE_TIME UNLIMITED;
-- Modify the pro_common profile to set PASSWORD_LIFE_TIME to 30 days.
ALTER PROFILE pro_common LIMIT PASSWORD_LIFE_TIME 30;
-- Delete the pro_common profile.
DROP PROFILE pro_common CASCADE;

3.13.8 ALTER SESSION


Description
ALTER SESSION modifies a session.

Precautions
Users do not need system permissions for executing ALTER SQL_MAP.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 363


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Syntax
ALTER SESSION
{ SET
{ COMMIT_WAIT_LOGGING = { WAIT | NOWAIT }
| COMMIT_MODE = { IMMEDIATE | BATCH }
| TIME_ZONE ='[ + | - ]hh:mm'
| nls_param ='nls_param_value'
| current_schema = schema_value}
}|
{ { ENABLE | DISABLE } { TRIGGERS | INTERACTIVE TIMEOUT | NOLOGGING | OPTINFO_LOG }
}

Parameter Description
● COMMIT_WAIT_LOGGING = (WAIT | NOWAIT)
Specifies whether the server process committing the transaction waits for the
log writer (LGWR) process to write redo logs into files.
Default value: WAIT
– WAIT
The server process waits for the redo logs to be written. In most cases,
this value is recommended.
– NOWAIT
The server process does not wait for the redo logs to be written. That is,
the server process commits a transaction no matter whether the redo
logs are written into files. This value may cause data loss, but improves
the transaction processing speed.
● COMMIT_MODE = {IMMEDIATE | BATCH}
Specifies whether the LGWR process writes redo logs in batches.
Default value: IMMEDIATE
– IMMEDIATE
Writes redo logs immediately for each transaction commit. In this case,
transaction throughput may be reduced due to forcible disk I/O.
– BATCH
Buffers the redo logs and writes them in bathes into files when the
number of redo logs reaches a specified value. In this case, buffered redo
logs may be lost when instance failures occur.
● TIME_ZONE = '[+|–]{hh}:{mm}'
Specifies the time zone of the current session. A character string in the format
'[+|–]{hh}:{mm}' is used to set the difference between the local time zone of
a session and the UTC (GMT) time. The plus sign (+) indicates that the local
time zone is earlier than the GMT and the minus sign (–) indicates that local
the time zone is later than the GMT. For example, the Beijing time is GMT + 8
and you can use +08:00 to indicate the difference.
You can use the SESSIONTIMEZONE keyword to view the time zone of the
current session.
The default value is the system time zone of the client where the session is
initiated.
The valid time zone ranges from –12:00 to [+]14:00.
● nls_param = 'nls_param_value'

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 364


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies the language in which month and day names and abbreviations are
returned.
The possible values are:
– NLS_DATE_FORMAT with default format of YYYY-MM-DD HH24:MI:SS
– NLS_TIMESTAMP_FORMAT with the default format of YYYY-MM-DD
HH24:MI:SS.FF
– NLS_TIMESTAMP_TZ_FORMAT with the default format of YYYY-MM-DD
HH24:MI:SS.FF TZH:TZM
– NLS_TIME_FORMAT with the default format of HH:MI:SS.FF AM
– NLS_TIME_TZ_FORMAT with the default format of HH:MI:SS.FF AM TZR
● current_schema = schema_value
Change the schema for the current session. The default value is the schema of
the login user.
● { ENABLE | DISABLE } { TRIGGERS | INTERACTIVE TIMEOUT | INTERACTIVE
TIMEOUT }
– ENABLE TRIGGERS: Triggers are valid for the SQL statements executed in
the current session.
– DISABLE TRIGGERS: Triggers are invalid for the SQL statements executed
in the current session.
– ENABLE INTERACTIVE TIMEOUT: Interactive timeout is enabled. By
default, a session is closed if this session has no SQL request within 30
minutes.
– DISABLE INTERACTIVE TIMEOUT: Interactive timeout is disabled.
– ENABLE NOLOGGING: In the current session, redo logs and undo logs
are not recorded during data insertion.
– DISABLE NOLOGGING: In the current session, redo logs and undo logs
are recorded during data insertion.
– ENABLE OPTINFO_LOG: In the current session, the optimizer log is
enabled to write logs generated by the execution plan to log/opt/
zengine.opt. By default, the system shuts down 2 minutes later. To start
it, run the command again.
– DISABLE OPTINFO_LOG: In the current session, the optimizer log is
disabled.

Examples
● Wait for redo information to be written into redo log files and then commit
the transaction.
ALTER SESSION SET COMMIT_WAIT_LOGGING=WAIT;

● Commit the transaction without waiting for redo information to be written


into redo log files.
ALTER SESSION SET COMMIT_WAIT_LOGGING=NOWAIT;

● The LGWR process writes redo logs immediately for each transaction commit.
ALTER SESSION SET COMMIT_MODE=IMMEDIATE;

● The LGWR process writes redo logs in batches.


ALTER SESSION SET COMMIT_MODE =BATCH;

● Set the time zone of the current session to GMT+8.


ALTER SESSION SET TIME_ZONE ='+8:00';

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 365


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Set the local language to NLS_DATE_FORMAT.


ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';

● Switch to user1 if any.


ALTER SESSION SET current_schema=user1;

● Make triggers valid for the SQL statements executed in the current session.
ALTER SESSION ENABLE TRIGGERS;

● Make triggers invalid for the SQL statements executed in the current session.
ALTER SESSION DISABLE TRIGGERS;

● Enable interactive timeout.


ALTER SESSION ENABLE INTERACTIVE TIMEOUT;

● Disable the idle detection function.


ALTER SESSION DISABLE INTERACTIVE TIMEOUT;

● Disable the recording of redo logs and undo logs during data insertion in the
current session.
ALTER SESSION ENABLE NOLOGGING;

● Enable the recording of redo logs and undo logs during data insertion in the
current session.
ALTER SESSION DISABLE NOLOGGING;

3.13.9 ALTER SQL_MAP

Description
ALTER SQL_MAP creates a SQL mapping.

Precautions
● Only mappings between DML statements can be created.
● Source and target SQL statements are compared by using hash values,
including letter cases (uppercase or lowercase) and spaces. Therefore, they
must be completely consistent. Otherwise, mapping will not be triggered.
● Users do not need system permissions for executing ALTER SQL_MAP.

Syntax
ALTER SQL_MAP {src_sql_id | (src_select)} REWRITE TO (dest_select)

Parameter Description
● src_select
Specifies a source SQL statement.
● src_sql_id
Specifies the unique ID of the source SQL. The value is the hash value of the
SQL text. For details, see Data Dictionary and Views > Dynamic
Performance Views > DV_SQLSV$SQLAREA in GaussDB 100 V300R001C00
Database Reference.
● dest_select
Specifies a target SQL statement.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 366


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
-- Enable the SQL mapping function.
ALTER SYSTEM SET enable_sql_map = true;
-- Create a SQL mapping.
ALTER SQL_MAP (select count(*) from SYS_DUMMY) REWRITE TO (select count(1) as cnt from
SYS_DUMMY);
-- Enter a source SQL statement, which will actually be mapped to the target SQL statement for execution.
select count(*) from SYS_DUMMY;

CNT
--------------------
1

1 rows fetched.
-- If another SQL statement of the same source is entered but has a different letter case, it will not be
mapped to the target statement.
select COUNT(*) from SYS_DUMMY;
COUNT(*)
--------------------
1

1 rows fetched.

3.13.10 ALTER SEQUENCE


Function
ALTER SEQUENCE modifies a sequence.

Precautions
● You can modify your own sequences without additional permissions.
● To modify sequences of other users, the ALTER ANY SEQUENCE system
permission is required. Common users cannot modify objects of system users.
● Sequences cannot be modified during database restart or rollback.

Syntax
ALTER SEQUENCE [ schema_name. ]sequence_name
{ INCREMENT BY bigint
| { MAXVALUE bigint | NOMAXVALUE }
| { MINVALUE bigint | NOMINVALUE }
| { CYCLE | NOCYCLE }
| { CACHE bigint | NOCACHE }
| { ORDER | NOORDER }
} [ ... ]

Parameter Description
● [ schema_name. ]
Specifies the name of a user whose sequence is to be modified. If this
parameter is not specified, the current login user is used by default.
● sequence_name
Specifies the name of a sequence to be modified. It is optionally schema-
qualified.
● INCREMENT BY bigint
Specifies a sequence step.
The value is an integer other than 0. The default value is 1.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 367


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– If the value is a positive integer, an incremental sequence is generated.


– If the value is a negative integer, a decremental sequence is generated.
● MAXVALUE bigint | NOMAXVALUE
MAXVALUE: maximum value of a sequence
NOMAXVALUE: A sequence does not have a maximum value.
If this clause is not declared or NOMAXVALUE is declared in the clause, the
default value is used.
– The default maximum value for an incremental sequence is 263–1.
– The default maximum value for a decremental sequence is –1.
● MINVALUE bigint | NOMINVALUE
MINVALUE: minimum value of a sequence
NOMINVALUE: A sequence does not have a minimum value.
If this clause is not declared or NOMINVALUE is declared in the clause, the
default value is used.
– The default minimum value for an incremental sequence is 1.
– The default minimum value for a decremental sequence is –263+1.
● CYCLE | NOCYCLE
CYCLE: A cycle is allowed when a sequence reaches its maximum or minimum
value. That is,
– When an incremental sequence reaches its maximum, the next data
generated is its minimum value.
– When a decremental sequence reaches its minimum, the next data
generated is its maximum value.
NOCYCLE: An error will be reported in the generation of the next data when
a sequence reaches its maximum or minimum value.
By default, NOCYCLE is specified.
● CACHE bigint | NOCACHE
CACHE bigint: number of sequence values reserved in the memory for fast
access. The minimum value (default value) is 1, indicating that only one value
can be generated at a time, that is, cache is not used. NOCACHE: Cache is
disabled.
● ORDER | NOORDER
ORDER: Sequence numbers are generated in order of request. If you want to
use sequence numbers as timestamps, this value is recommended. If sequence
numbers are used as primary key values, the order does not matter much.
NOORDER: Sequence numbers are generated not in order of request.

Examples
Modify the seq_auto_extend sequence.
-- Delete the seq_auto_extend sequence.
DROP SEQUENCE IF EXISTS seq_auto_extend;
-- Create the seq_auto_extend sequence starting with 10, and with INCREMENT BY set to 2, MAXVALUE
set to 200, and CYCLE specified.
CREATE SEQUENCE seq_auto_extend START WITH 10 MAXVALUE 200 INCREMENT BY 2 CYCLE;
-- Change INCREMENT BY to 4 and MAXVALUE to 400.
ALTER SEQUENCE seq_auto_extend MAXVALUE 400 INCREMENT BY 4 CYCLE;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 368


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.11 ALTER SYSTEM

Description
ALTER SYSTEM modifies database system parameters.

Precautions
To run this statement, you must have the ALTER SYSTEM system permission.

Syntax
ALTER SYSTEM
{ DUMP DATAFILE file_id PAGE page_id
| SWITCH LOGFILE
| SET parameter_name = parameter_value [ SCOPE = { MEMORY | PFILE | BOTH } ]
| LOAD DICTIONARY FOR [ schema_name.]object_name
| INIT DICTIONARY
| RELOAD HBA CONFIG
| REFRESH SYSDBA PRIVILEGE
| KILL SESSION 'session_id,serial'
| RESET STATISTIC
| CHECKPOINT
| { ADD | DELETE } LSNR_ADDR LISTENING_IP
| FLUSH {BUFFER | SQLPOOL}
}

Parameter Description
● DUMP DATAFILE file_id PAGE page_id
Specifies the data file page to be dumped.
– file_id
Specifies the file ID. The value is a positive integer within the range [0,
2147483648).
– page_id
Specifies the page number. The value is a positive integer within the
range [0, 2147483648).
● SWITCH LOGFILE
Switches log files.
● SET parameter_name = parameter_value [ SCOPE = { MEMORY | PFILE |
BOTH } ]
Sets system parameters. SCOPE is an optional parameter. It specifies where
parameter settings are to be written. PFILE or BOTH indicates that parameter
settings are written into the Zenith.ini configuration file. If SCOPE is not set,
the default value BOTH is used.
– MEMORY: Parameter settings are written into only memory and take
effect immediately but become invalid after a restart. MEMORY is
applicable to only dynamic system parameters.
– PFILE: Parameter settings are written into initial parameter files and take
effect after a restart. PFILE is applicable to both dynamic and static
system parameters. The settings of statistic system parameters can be
written into only initial parameter files.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 369


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– BOTH: Parameter settings are written into both initial parameter files and
memory, and take effect immediately. BOTH is applicable to only
dynamic system parameters.
If SCOPE is not set, the default value BOTH is used.
● LOAD DICTIONARY FOR [schema_name].object_name
Loads objects to the data dictionary.
● INIT DICTIONARY
Loads objects (such as system views, dynamic views, sequences, and roles)
except the system catalogs.
The prerequisites are that the database is in the RESTRICT mode and all
system catalogs are loaded by running the ALTER SYSTEM LOAD
DICTIONARY FOR [schema_name].object_name statement.
● RELOAD HBA CONFIG
Loads the zhba.conf file online.
● REFRESH SYSDBA PRIVILEGE
Updates the ciphertext and encryption key used for password-free login of
user SYSDBA online. The update does not affect the current client. The new
key is used for authenticating the password-free login of other clients.
● KILL SESSION 'session_id,serial'
Kills a session. session_id specifies the session ID, and serial specifies the
sequence number ID.
● RESET STATISTIC
Clears the statistics in the dynamic view DV_SYS_STATS.
● CHECKPOINT
Executes checkpoints for the current instance to ensure that all changes made
to the committed transactions are written into data files on the disk.
● { ADD | DELETE } LSNR_ADDR LISTENING_IP
Adds or deletes a listening IP address. The parameter value takes effect
immediately after being configured. Currently, zenith supports a maximum of
eight listening IP addresses.
An error is reported if the parameter is set to an NIC IP address that does not
exist.
When a listening IP address that is being used is deleted, the session
established through the IP address is disconnected and services are rolled
back.
● FLUSH BUFFER
Clears the database buffer.
● FLUSH SQLPOOL
Clears the SQLPOOL buffer.

Examples
● Switches log files.
ALTER SYSTEM SWITCH LOGFILE;

● Change the value of UNDO_RETENTION_TIME to 1200s. The setting takes


effect immediately.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 370


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Query for the value of UNDO_RETENTION_TIME.


SHOW PARAMETER UNDO_RETENTION_TIME
-- Change the value of UNDO_RETENTION_TIME.
ALTER SYSTEM SET UNDO_RETENTION_TIME=1200 SCOPE=MEMORY;

● Load the education table to the data dictionary.


-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70));
-- Load the education table to the data dictionary.
ALTER SYSTEM LOAD DICTIONARY FOR education;

● Load objects (such as system views, dynamic views, sequences, and roles)
except the system catalogs.
This operation can be performed only when the database is in the RESTRICT
mode and all system catalogs are loaded by running the ALTER SYSTEM
LOAD DICTIONARY FOR [schema_name].object_name statement.
ALTER SYSTEM INIT DICTIONARY;

● Loads the zhba.conf file online.


ALTER SYSTEM RELOAD HBA CONFIG;

● Updates the ciphertext and encryption key used for password-free login of
user SYSDBA online.
ALTER SYSTEM REFRESH SYSDBA PRIVILEGE;

● Clear the statistics in the dynamic view DV_SYS_STATS.


ALTER SYSTEM RESET STATISTIC;

● Set checkpoints for the current transaction.


ALTER SYSTEM CHECKPOINT;

3.13.12 ALTER SYSTEM KILL SESSION


Description
ALTER SYSTEM KILL SESSION kills a session.

Precautions
● To run this statement, you must have the ALTER SYSTEM system permission.
● The current session and reserved sessions cannot be killed.

Syntax
ALTER SYSTEM KILL SESSION 'session_id,serial#'

Parameter Description
● session_id
Specifies the ID of a session to be killed.
● serial#
Specifies the serial ID of a session to be killed.

Examples
-- Query the ID of the session to be killed.
SELECT * FROM DV_SESSIONS WHERE USERNAME='JIM';

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 371


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SID SPID SERIAL# USER# USERNAME


CURR_SCHEMA CLIENT_IP CLIENT_PORT SERVER_IP
SERVER_PORT SERVER_MODE OSUSER MACHINE
PROGRAM AUTO_COMMIT CLIENT_VERSION TYPE
LOGON_TIME STATUS LOCK_WAIT WAIT_SID EXECUTIONS SIMPLE_QUERIES
DISK_READS BUFFER_GETS CR_GETS
CURRENT_SQL SQL_EXEC_START SQL_ID
ATOMIC_OPERS REDO_BYTES COMMITS NOWAIT_COMMITS XA_COMMITS
ROLLBACKS XA_ROLLBACKS LOCAL_TXN_TIMES XA_TXN_TIMES PARSES
HARD_PARSES EVENT# EVENT SORTS
PROCESSED_ROWS IO_WAIT_TIME CON_WAIT_TIME CPU_TIME ELAPSED_TIME
ISOLEVEL MODULE VMP_PAGES LARGE_VMP_PAGES
------------ ----------- ------------ ------------ ----------------------------------------------------------------
---------------------------------------------------------------- -------------------- ----------- --------------------
----------- ----------- ---------------------------------------------------------------- ------------------------------
---------------------------------------------------------------- ----------- -------------- ---------- ----------------------
---------- --------- ------------ -------------------- -------------------- -------------------- --------------------
-------------------- ---------------------------------------------------------------- ----------------------
-------------------- -------------------- -------------------- -------------------- -------------------- --------------------
-------------------- -------------------- -------------------- -------------------- -------------------- --------------------
------------ ---------------------------------------------------------------- -------------------- --------------------
-------------------- -------------------- -------------------- -------------------- --------------------
---------------------------------------------------------------- -------------------- --------------------
74 66943 12 5 JIM
JIM 127.0.0.1 44705 127.0.0.1 10528
MIXTRUE gaussdba 127.0.0.1 [102501]/home/
gaussdb/app/bin/zsql TRUE 9 USER 2018-08-21 16:22:16 INACTIVE
N 1 0 0 2
0 0
0 0 0 0 0 0 0
0 1 1 1 message from client
0 1 0 0 1655 1655 1
ZSQL 0 0

1 rows fetched.

-- Kill the session.


ALTER SYSTEM KILL SESSION '74,12';

3.13.13 ALTER TABLESPACE

Description
ALTER TABLESPACE modifies a tablespace.

Precautions
● To run this statement, you must have the ALTER TABLESPACE system
permission.
● To add a data file, delete a data file, modify automatic extension, or rename a
tablespace, the database must be in the OPEN state.
● To modify a data file name, the database must be in the MOUNT state.
● AUTOOFFLINE can be set only for user tablespaces.

Syntax
ALTER TABLESPACE tablespace_name
{ datafile_tempfile_clauses
| RENAME TO new_tablespace_name
| SHRINK SPACE KEEP integer [ K | M | G | T ]
| AUTOOFFLINE [ ON | OFF ]
}

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 372


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● datafile_tempfile_clauses:
{ ADD DATAFILE {datafile_tempfile_spec [ , ... ]}
| DROP DATAFILE 'file_name'
| RENAME DATAFILE 'old_file_name' TO 'new_file_name'
| autoextend_clause
| OFFLINE DATAFILE 'file_name' [ , ... ]
}

– datafile_tempfile_spec:
file_name SIZE integer [ K | M | G ] [ autoextend_clause ]

▪ autoextend_clause:
AUTOEXTEND { OFF
| ON [ NEXT integer [ K | M | G] ]
}
[ MAXSIZE { integer [ K | M | G]
| UNLIMITED
}
]

Parameter Description
● tablespace_name
Specifies the name of a tablespace to be modified. If the tablespace does not
exist, an error will be reported.
● ADD DATAFILE
Adds a data file to a tablespace.
● DROP DATAFILE
Deletes data files from a tablespace. The data files must have never been
used (hwms is 0).
● autoextend_clause
Enables or disables automatic extension for a tablespace.
● RENAME DATAFILE
Changes a data file name in a tablespace. The name can be changed only in
the MOUNT database state. To change a data file name, the data file must
be closed. Currently, files will be closed without waiting for the database to be
in the restoration state.
● AUTOOFFLINE
Specifies whether automatic offline is enabled for tablespaces. If
AUTOOFFLINE is set to ON, automatic offline is enabled for user tablespaces.
When a file fails to be opened during database startup, the user tablespace is
automatically brought offline. If a user tablespace is faulty after the database
is started, the tablespace is not automatically brought offline.
If ALTER TABLESPACE tablespace_name AUTOOFFLINE ON has been set for
a user tablespace before it is damaged or faulty, the database can be started
in the MOUNT state. Otherwise, an error is reported and the database start
will fail.
● OFFLINE DATAFILE
Takes offline damaged data files. Files can be taken offline only in the
MOUNT database state. The data files can be taken offline as long as they
are not empty.
● datafile_tempfile_spec

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 373


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Multiple data files can be separated by commas (,). Currently, data files
cannot contain Chinese characters.
file_name
Specifies the absolute path (path and file name) of a new data file. If a
relative path is specified, the file is stored in the data directory under the data
directory by default.
SIZE integer[ K | M | G ]
Specifies the size of each data file.
K: The unit is KB.
M: The unit is MB.
G: The unit is GB.
The value range for the undo tablespace is [1 MB, 32 GB) and that for other
tablespaces is [1 MB, 8 TB].
autoextend_clause
If AUTOEXTEND is set to on, you can manually specify the extension size.
– If AUTOEXTEND is not set, extension is disabled by default.
– If AUTOEXTEND OFF is set, automatic extension is disabled.
– If AUTOEXTEND ON is set, you can set the following parameters:

▪ NEXT: extension size. If this parameter is not set, the default value
16MB is used.

▪ MAXSIZE: extension upper limit.


○ If this parameter is omitted or is set to UNLIMITED, the
maximum size of the undo tablespace is 32 GB, and that of
other tablespaces is 8 TB.
○ If this parameter is set to a value. This value cannot be greater
than 32 GB for the undo tablespace, and cannot be greater than
8 TB for other tablespaces.
○ If both MAXSIZE and NEXT are set, the value of MAXSIZE must
be no less than that of NEXT.
● RENAME TO new_tablespace_name
Changes a tablespace name.
● SHRINK SPACE KEEP integer [ K | M | G | T ]
Shrinks a tablespace. Temporary tablespaces and undo tablespaces can be
shrunk in the RESTRICT mode.
To shrink an UNDO tablespace, ensure there is no residual transaction.
K: The unit is KB.
M: The unit is MB.
G: The unit is GB.
T: The unit is TB.
The value range of the tablespace size is [1M, 8000T].

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 374


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
● Add a data file to the tbs_human tablespace.
-- Create the tbs_human tablespace:
CREATE TABLESPACE tbs_human DATAFILE 'dfile_tbs_01' SIZE 32M AUTOEXTEND ON NEXT 10M;
-- Add the data files privilege_dfile (32 MB), manager_dfile (32 MB), and section_dfile (32 MB) to
the tbs_human tablespace.
ALTER TABLESPACE tbs_human ADD DATAFILE 'privilege_dfile' SIZE 32M, 'manager_dfile' SIZE 32M,
'section_dfile' SIZE 32M;
● Delete the manager_dfile data file from the tbs_human tablespace.
ALTER TABLESPACE tbs_human DROP DATAFILE 'manager_dfile';
● Rename the privilege_dfile data file in the tbs_human tablespace to
new_privilege_dfile in the MOUNT database state.
-- Rename the privilege_dfile data file to new_privilege_dfile in the MOUNT database state.
ALTER TABLESPACE tbs_human RENAME DATAFILE 'privilege_dfile' TO 'new_privilege_dfile';
-- Change the database status to OPEN.
ALTER DATABASE OPEN;
● Take offline the damaged data file section_dfile in the tbs_human
tablespace in the MOUNT database state.
-- Take offline the damaged data file section_dfile in the tbs_human tablespace in the MOUNT
database state.
ALTER TABLESPACE tbs_human OFFLINE DATAFILE 'section_dfile';
-- Change the database status to OPEN.
ALTER DATABASE OPEN;
● Enable automatic extension for the tbs_human tablespace so that the
tablespace can be automatically expanded when it is full. You can specify the
extension size.
ALTER TABLESPACE tbs_human AUTOEXTEND ON NEXT 5M;
● Change the tablespace name tbs_human to data_tbs_human.
ALTER TABLESPACE tbs_human RENAME TO data_tbs_human;

3.13.14 ALTER TABLE


Function
ALTER TABLE changes the definition of a table by changing, adding, or deleting
columns and constraints. With ALTER TABLE, you can:
● Add, delete, modify, or rename columns.
● Add or delete constraints.
● Enable or disable constraints.
● Modify partition tablespaces.

Precautions
● To run this statement, you must have the ALTER ANY TABLE system
permission. Common users cannot modify objects of system users.
● An error message containing valid error information is returned if table name,
column name, or constraint name conflict occurs, the names are invalid, or
data conflicts with the verification.
● When you add a column to a table, ensure that there is no record in the table.
● When you modify a column, ensure that the all the values in this column are
NULL. If the values of a column are not NULL, you can only increase the
CHAR or VARCHAR size and cannot perform any operations for other data
types.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 375


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The UNIQUE INDEX, PRIMARY KEY, and FOREIGN KEY inline constraints
cannot be contained in a statement for adding or modifying a column.
● shrink_clause, row_movement_clause, and character sets support only SQL
parsing.
● ALTER TABLE does not support foreign tables.
● enable_disable_clause supports only the FOREIGN KEY and CHECK constraints.
● Tables cannot be modified during database restart or rollback.

Syntax
ALTER TABLE [ schema_name. ]table_name
{ alter_table_properties
| column_clauses
| references_clause
| constraint_clauses
| partition_clauses
| enable_disable_clause
| set_interval_clause
}
● alter_table_properties:
{ physical_attributes_clause
| RENAME TO new_table_name
| shrink_clause
| row_movement_clause
| AUTO_INCREMENT [ = ] value
| {ENABLE | DISABLE} ALL TRIGGERS
}
– physical_attributes_clause:
{ PCTFREE integer
| APPENDONLY { ON | OFF }
}
– shrink_clause:
SHRINK SPACE [ COMPACT ]
– row_movement_clause:
{ ENABLE | DISABLE } ROW MOVEMENT
● column_clauses:
{ add_column_clause
| modify_column_clause
| drop_column_clause
| rename_column_clause
}
– add_column_clause:
-- Add one column.
ADD [ COLUMN ] column_name datatype_name [ DEFAULT expr [ON UPDATE expr ] ]
[ COMMENT 'string' ] [ COLLATE collation_name ] [AUTO_INCREMENT] [ inline_constraint ]
-- Add multiple columns.
ADD ( [ COLUMN ] { column_name datatype_name [ DEFAULT expr [ON UPDATE expr ] ]
[ COMMENT 'string' ] [ COLLATE collation_name ] [AUTO_INCREMENT] [ inline_constraint ] }
[ , ... ] )

▪ inline_constraint:
{ [ NOT ] NULL
| CHECK( expr )
| WITH [ LOCAL ] TIME ZONE
| PRIMARY KEY
| UNIQUE
}
[ ... ]
– modify_column_clause:
-- Modify a column.
MODIFY ( { column_name [ new_datatype_name ] [ DEFAULT expr [ ON UPDATE expr ] ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 376


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

[ COMMENT string ]
[ COLLATE collation_name ]
[ inline_constraint ] } [ , ... ]
)
-- Shrink the space occupied by a LOB column.
MODIFY LOB(column_name) (SHRINK SPACE)
– drop_column_clause:
DROP [ COLUMN ] column_name
– rename_column_clause:
RENAME COLUMN old_name TO new_name
● references_clause:
If no column is specified for a parent table, the primary key of the parent
table is used by default. If the primary key of the parent table does not exist,
an error will be reported.
REFERENCES [ schema_name. ]object_table [( column_name )]
● constraint_clauses:
{ ADD out_of_line_constraint
| DROP CONSTRAINT [ IF EXISTS ] constraint_name
| RENAME CONSTRAINT old_constraint_name TO new_constraint_name
}
– out_of_line_constraint:
CONSTRAINT [ IF NOT EXISTS ] constraint_name
{ UNIQUE( column_name [ , ... ] ) [ constraint_state_clause ]
| PRIMARY KEY( column_name [ , ... ] ) [ constraint_state_clause ]
| CHECK( expr )
| FOREIGN KEY( column_name [ , ... ] ) references_clause_ex
}

▪ constraint_state_clause:
In constraint_state_clause, all the parameters except
using_index_clause are used for syntax compatibility and do not take
effect in the current version. In addition, you can set these
parameters in a random order. If you set a parameter for more than
one time, only the last setting takes effect.
[ NOT DEFERRABLE | DEFERRABLE ]
[ INITIALLY { IMMEDIATE | DEFERRED } ]
[ RELY | NORELY ]
[ VALIDATE | NOVALIDATE ]
[ ENABLE | DISABLE ]
[ using_index_clause ]
○ using_index_clause:
USING INDEX
[ INITRANS integer
| TABLESPACE tablespace_name
| LOCAL [ ( { PARTITION partition_name [ TABLESPACE tablespace_name
| INITRANS integer
| PCTFREE integer
]
} [ , ... ]
)
]
] [ ... ]

▪ references_clause_ex:
If no column is specified for a parent table, the primary key of the
parent table is used by default. If the primary key of the parent table
does not exist, an error will be reported.
REFERENCES [ schema_name. ]object_table_name [( column_name [ , ... ] )]
[ ON DELETE { CASCADE
| SET NULL

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 377


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

}
]

● partition_clauses:
{ add_partition_clause
| drop_partition_clause
| truncate_partition_clause
| coalesce_partition_clause
}

– add_partition_clause:
ADD PARTITION partition_name
{ VALUES LESS THAN ( { partition_value
| MAXVALUE
}[ , ... ]
)
| VALUES ( partition_value [ , ... ]
| DEFAULT )
}
[ TABLESPACE tablespace_name ]
[ PCTFREE integer ]

– drop_partition_clause:
DROP PARTITION partition_name

– truncate_partition_clause:
TRUNCATE PARTITION partition_name [ DROP STORAGE
| REUSE STORAGE
| PURGE
]

– coalesce_partition_clause:
COALESCE PARTITION

● enable_disable_clause:
{ ENABLE | DISABLE } [VALIDATE | NOVALIDATE] CONSTRAINT constraint_name

● set_interval:
SET INTERVAL([interval_value])

Parameter Description
● [ schema_name.]
Specifies the name of a user whose table is to be modified. If this parameter
is not specified, the current login user is used by default.
● table_name
Specifies the name of a table to be modified. The table must exist.
● alter_table_properties
Modifies table storage. For example, LOB_storage_clause specifies that LOB
columns are stored in a separate segment. You can specify inline or out-of-
line storage for a table. Currently, only out-of-line storage is supported.
– physical_attributes_clause
Specifies the physical attribute of a table.
PCTFREE integer
Specifies the percentage of space reserved for a block. If the percentage
of available space of a data block is less than this value, you can only
update data of this block and cannot insert data into it. The value range
is [8, 80] and the default value is 10.
APPENDONLY { ON | OFF }

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 378


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies whether to independently increase space for each thread to


improve the speed of concurrent data insertion into a table. The default
value is OFF.
Use APPENDONLY in a partitioned table only when necessary. Improper
use of APPENDONLY will cause serious space waste.
ON
During concurrent insertion, space is increased independently for each
thread.

▪ If APPENDONLY is set to ON for a partitioned table, properly


arrange the data to be concurrently inserted, ensuring that partition
switchover will not occur (that is, each thread can insert data to only
one partition).

▪ You are not advised to set APPENDONLY to ON for a hash


partitioned table.
OFF
During concurrent insertion, space is not increased independently for
each thread.
– RENAME TO new_table_name
Specifies a new table name.
– shrink_clause
Specifies a shrink clause.
SPACE
Shrinks space. The SELECT statement executed concurrently with ALTER
TABLE SHRINK SPACE may return an expected result because ALTER
TABLE SHRINK SPACE may segment the table and thereby change the
row IDs.
COMPACT
If you specify COMPACT, only segment space is defragmented and the
high water mark is not adjusted.
– row_movement_clause
Specifies a row movement clause.
{ ENABLE | DISABLE } ROW MOVEMENT
Enables or disables row movement.
– AUTO_INCREMENT [ = ] value
Specifies the start value of a sequence column. If this parameter is not
specified, the value 0 is used.
– {ENABLE | DISABLE} ALL TRIGGERS
Enables or disables triggers.
● column_clauses
Adds, deletes, or modifies a column.
– add_column_clause
Adds a column.
DEFAULT expr [ON UPDATE expr]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 379


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies an expression used to calculate the default value of a column. In


DDL, DEFAULT specifies a constant expression, the data type of this
constant will be checked for data compatibility.

▪ ON UPDATE expr specifies the default update value to be used if


DEFAULT is not set. It is compatible with the mainstream syntax in
the industry.

▪ The value contains a maximum of 1024 characters. If the length


exceeds the maximum, the error message "GS-00611, default value
string is too long, exceed 1024." is displayed.
COMMENT 'string'
Adds a comment for a column. You can view comments by querying the
USER_COL_COMMENTS system view.
COLLATE collation_name
Specifies a collation rule for a column.
The rule specifies how data is sorted and compared.
collation_name indicates a collation name. The value can be:

▪ UTF8_BIN: applicable to the UTF8 character set. All characters are


considered as binary strings and are compared from the most
significant bit to the least significant bit. The characters to be
compared are case-sensitive.

▪ UTF8_GENERAL_CI: applicable to the UTF8 character set. The


characters to be compared are case-insensitive.

▪ UTF8_UNICODE_CI: applicable to the UTF8 character set. The


characters to be compared are case-insensitive.

▪ GBK_BIN: applicable to the GBK character set. The characters to be


compared are case-sensitive.

▪ GBK_CHINESE_CI: applicable to the GBK character set. The


characters to be compared are case-insensitive.
inline_constraint
Adds a column constraint. It is included in the column definition.
Currently, the NULL, NOT NULL, UNIQUE, PRIMARY KEY, UNIQUE
INDEX, FOREIGN KEY, and CHECK constraints are supported.
– modify_column_clause
Modifies one or more specified columns, such as modifying the data type
of a column and shrinking the space occupied by a LOB column.
To change the data type of a column into an incompatible one, ensure
that the table is empty or all values in the column are NULL. To change
the data type of a column into a compatible one, ensure that the table is
not empty and not all values of the column are NULL. Currently, the
following data types are compatible for modification:

▪ Conversion between the VARCHAR type and the CHAR type (the
length must be no less than the length before the conversion).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 380


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Changes of VARCHAR, CHAR, and BINARY types into larger length.

▪ Changes of the NUMBER and DECIMAL types into a larger scale (the
values of scale, precision, and - scale must be no less than those
before the modification)
– drop_column_clause
Deletes a column.
– rename_column_clause
Renames a column.
● references_clause
Adds a FOREIGN KEY constraint. schema_name indicates the owner of the
referenced table, and object_table indicates the name of the referenced table.
column_name indicates the referenced column.
● constraint_clauses
Modifies a table constraint, including adding and deleting an inline or out-of-
line constraint.
– ADD out_of_line_constraint
Adds an out-of-line constraint.
IF NOT EXISTS
Does not throw an error if the out-of-line constraint already exists.
using_index_clause
Specifies an external index clause.
INITRANS integer
Initially allocated storage block space. integer specifies the space size.
TABLESPACE tablespace_name
Specifies a tablespace. tablespace_name specifies a tablespace name.
LOCAL
Creates a local index for a partitioned table.
ONLINE
Adds a constraint online.
CHECK( expr )
Specifies rules for checking values in a column. If NULL is inserted, TRUE
is returned.
references_clause_ex
Specifies a foreign key constraint clause.
ON DELETE { CASCADE | SET NULL }
Specifies how foreign key values in a child table are handled when
primary or unique values in the parent table are deleted.

▪ CASCADE
The foreign key values will be deleted.

▪ SET NULL
The foreign key values will be converted to NULL.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 381


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– DROP CONSTRAINT [ IF EXISTS ] constraint_name


Deletes a constraint. constraint_name specifies the name of the
constraint to be deleted.
IF EXISTS
Does not throw an error if the constraint does not exist.
– DROP primary_key_clauses
Deletes a primary key.
PRIMARY KEY [DROP|KEEP INDEX]
DROP
The index is deleted when the primary key is deleted.
KEEP
The index is not deleted when the primary key is deleted.
● partition_clauses
Specifies a partition clause.
– add_partition_clause
Adds a partition.
VALUE LESS THAN
Specifies the partition upper boundary.
partition_value
Specifies the values by which a table will be partitioned.
MAXVALUE
Specifies a MAXVALUE partition.
VALUE
Specifies partition values.
DEFAULT
Specifies a DEFAULT partition.
– drop_partition_clause
DROP PARTITION partition_name
Deletes a partition. partition_name specifies the name of a partition to be
deleted.
– truncate_partition_clause
Truncates a partition. partition_name specifies the name of a partition to
be truncated.
DROP STORAGE
Clears storage space.
REUSE STORAGE
Reuses storage space.
PURGE
Clears the recycle bin.
– coalesce_partition_clause
COALESCE PARTION

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 382


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Inserts the data of the last partition into its previous partition and deletes
the last partition.

▪ The COALESCE PARTION statement is valid only for hash tables. You
do not need to specify the partition name in this statement.

▪ If there is only one partition, an error will be returned after the


execution of COALESCE PARTION.
● enable_disable_clause
Enables or disables a constraint, and specifies whether to require that existing
records meet the constraint during and after its enabling or disabling.
– ENABLE enables a constraint.
– DISABLE disables a constraint.
– VALIDATE requires existing records to meet the constraint during and
after the constraint's enabling or disabling.
– NOVALIDATE does not require existing records to meet the constraint
during and after the constraint's enabling or disabling.
VALIDATE and NOVALIDATE do not take effect for new or updated records.
That is, the system checks whether new and updated records meet a
constraint after the constraint is enabled and does not check that after the
constraint is disabled regardless of VALIDATE and NOVALIDATE.
VALIDATE and NOVALIDATE take effect for existing records. That is, the
system checks whether existing records meet a constraint during and after the
constraint's enabling or disabling if VALIDATE is specified (an error will be
reported if they do not meet the constraint) and does not check that if
NOVALIDATE is specified.
If ENABLE is specified for a constraint but NOVALIDATE is not, VALIDATE is
used by default, which equals ENABLE VALIDATE. In this case, the system
checks whether existing records, new records, and updated records meet the
constraint. If ENABLE and NOVALIDATE are specified for a constraint, the
system checks whether new and updated records meet the constraint.
If DISABLE is specified for a constraint but VALIDATE is not, NOVALIDATE is
used by default, which equals DISABLE NOVALIDATE. In this case, the system
disables the constraint, deletes indexes from the constraint, and allows the
constrained records to be modified. If DISABLE and VALIDATE are specified
for a constraint, the system disables the constraint, deletes indexes from the
constraint, and does not allow the constrained records to be modified.
For details about { ENABLE | DISABLE } [VALIDATE | NOVALIDATE], see
Table 3-50.

Table 3-50 Keyword combination description

Keyword Combination Whether to Check Whether to Check


Existing Records New and Updated
Records

ENABLE VALIDATE yes yes

ENABLE NOVALIDATE no yes

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 383


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Keyword Combination Whether to Check Whether to Check


Existing Records New and Updated
Records

DISABLE VALIDATE yes no

DISABLE NOVALIDATE no no

● set_interval_clause
Sets the interval partition. This parameter is valid only for partitioned tables.
– SET INTERVAL() changes a range partitioned table to an interval
partitioned table.
– SET INTERVAL(interval_value) specifies the interval for an interval
partitioned table.
● rename_column_clause
Changes a table name. You can change the name of only the table in your
own schemas and cannot modify names of tables in the system tablespace.

Examples
● Add a column.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL, course_name VARCHAR(50), course_start_date
DATETIME, course_end_date DATETIME, exam_date DATETIME, score INT);
-- Add the full_masks column.
ALTER TABLE training ADD full_masks INT;

● Delete a column.
ALTER TABLE training DROP course_period;

● Change the data type of a column.


ALTER TABLE training MODIFY course_name VARCHAR(20);

● Add a constraint.
ALTER TABLE training ADD CONSTRAINT ck_training CHECK(staff_id>0);
ALTER TABLE training ADD CONSTRAINT uk_training UNIQUE(course_name);

● Rename a constraint.
ALTER TABLE training RENAME CONSTRAINT ck_training TO ck_new_training;
ALTER TABLE training RENAME CONSTRAINT uk_training TO uk_new_training;

● Delete a constraint.
ALTER TABLE training DROP CONSTRAINT uk_new_training;

● Rename a table.
ALTER TABLE training RENAME TO training_2018;

● Delete the partitions training3 and training4.


-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create a partitioned table training.
CREATE TABLE training(staff_id INT NOT NULL, course_name CHAR(20), course_period DATETIME,
exam_date DATETIME, score INT)
PARTITION BY RANGE(staff_id)
(
PARTITION training1 VALUES LESS THAN(100),
PARTITION training2 VALUES LESS THAN(200),
PARTITION training3 VALUES LESS THAN(300),
PARTITION training4 VALUES LESS THAN(MAXVALUE)
);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 384


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the training3 partition.


ALTER TABLE training DROP PARTITION training3;
-- Delete the training4 partition.
ALTER TABLE training DROP PARTITION training4;

● Add partitions training5 and training6.


-- Add the training5 partition.
ALTER TABLE training ADD PARTITION training5 VALUES LESS THAN(350);
-- Add the training6 partition.
ALTER TABLE training ADD PARTITION training6 VALUES LESS THAN(MAXVALUE);

3.13.15 ALTER USER


Description
ALTER USER modifies an existing database user.

Precautions
● To run this statement, you must have the ALTER USER system permission.
● If the specified user does not exist, the error message "user *name* does not
exist" is displayed.
● Profiles cannot be created during database restart or rollback.

Syntax
ALTER USER user_name
{ IDENTIFIED BY new_password REPLACE old_password
| PASSWORD EXPIRE
| ACCOUNT { LOCK | UNLOCK }
| PROFILE profile_name
| DEFAULT TABLESPACE tablespace_name
} [ ... ]

Parameter Description
● user_name
Specifies the name of a user to be modified.
● IDENTIFIED BY
Specifies a new password.
● new_password
Specifies the new password of a user.
The password must comply with the following requirements:
– Contain 8 to 64 characters.
– Start with a letter, number sign (#), or an underscore (_) if the password
is not enclosed in single quotation marks ('').
– Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
– Contain only the following four character types and at least three of
them:

▪ Digits

▪ Lowercase letters

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 385


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Uppercase letters

▪ Spaces or special characters (For details about the list of special


characters supported by GaussDB 100, see the table below.)
– Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
– Contain at least two characters different from the old password. For
example, abc contains one character different from abd and two
different from ABc.
– If the password contains the special character $, use the escape character
\ when connecting to the database through zsql. Otherwise, the login will
fail.
● old_password
Specifies the old password of a user. An old password is used for user identity
verification.
● PASSWORD EXPIRE
Enables you to manually expire a password. After a password is manually
expired, you are not allowed to log in using this password and the "the
password has expired" message is displayed.
● ACCOUNT { LOCK | UNLOCK }
– LOCK
Locks a user to disable the login of this user. If a user is locked, the
following message is displayed when the user attempts to log in:
the account is locked

– UNLOCK
Unlocks a user and allows this user to log in.
● profile_name
Specifies a profile referenced by a user.
The profile must be configured in advance. If no profile is specified, the
default profile is referenced by default.
● DEFAULT TABLESPACE
Specifies a user tablespace.
● tablespace_name
Specifies a tablespace name.

Table 3-51 Special characters

ID Chara ID Charac ID Charac ID Charact


cter ter ter er

1 ` 9 & 17 \ 25 "

2 ~ 10 * 18 | 26 ,

3 ! 11 ( 19 [ 27 <

4 @ 12 ) 20 { 28 .

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 386


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

ID Chara ID Charac ID Charac ID Charact


cter ter ter er

5 # 13 - 21 } 29 >

6 $ 14 _ 22 ] 30 /

7 % 15 = 23 : 31 ?

8 ^ 16 + 24 ' - -

Examples
● Create user user_test with the password gauss_123.
CREATE USER user_test IDENTIFIED BY gauss_123;

● Change the password of user user_test to database_123.


ALTER USER user_test IDENTIFIED BY database_123 REPLACE gauss_123;

● Manually lock user user_test.


ALTER USER user_test ACCOUNT LOCK;

● Manually unlock the user_test user.


ALTER USER user_test ACCOUNT UNLOCK;

● Manually expire a password.


ALTER USER user_test PASSWORD EXPIRE;

3.13.16 ANALYZE

Description
ANALYZE collects statistics about tables and indexes.

Precautions
● This statement can be executed only in the OPEN database state.
● User SYS and DBA can collect and delete the statistics about all users or
objects. Common users can collect statistics about themselves or their own
tables. The ANALYZE ANY permission can be used to collect statistics about
all users except SYS.

Syntax
ANALYZE { TABLE [ schema_name. ] table_name COMPUTE STATISTICS }

Parameter Description
● [schema_name.]table_name
Specifies the name of the table whose statistics are to be collected. The table
name cannot be the same as the names of tables of the current user.
● COMPUTE STATISTICS
Instructs the database to compute statistics and store them in the data
dictionary.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 387


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
Collect statistics about the education table of user gaussdba.
-- Delete the gaussdba.education table.
DROP TABLE IF EXISTS gaussdba.education;
-- Create the gaussdba.education table.
CREATE TABLE gaussdba.education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70));
-- Analyze the collected statistics about the gaussdba.education table.
ANALYZE TABLE gaussdba.education COMPUTE STATISTICS;

3.13.17 COMMENT ON

Description
COMMENT ON adds comments about a table, view, or column to the data
dictionary.

You can view comments by querying the USER_TAB_COMMENTS,


DBA_TAB_COMMENTS, USER_COL_COMMENTS, or DBA_COL_COMMENTS
system view.

Precautions
● You do not need to add comments to your own table. When you add
comments to a table of any user, the user who needs to execute the
statement has the COMMENT ANY TABLE permission.
● You can add comments about a table during table creation.
● Profiles cannot be created during database restart or rollback.

Syntax
COMMENT ON { TABLE [ schema_name. ] { table_name | view_name }
| COLUMN [ schema_name. ] { table_name. | view_name. } column_name
} IS 'string'

Parameter Description
● [ schema_name. ]
Username If this parameter is not specified, the current login user is used by
default.
● { table_name | view_name }
Specifies the name of a table or view to be commented.
● [schema_name.] { table_name. | view_name. } column_name
Specifies the name of a column to be commented.
● IS
Specifies comment content.
● string
Specifies comment content.
The content contains a maximum of 4000 bytes.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 388


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
● Create a table and add comments for the table.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL, course_name VARCHAR(50), course_start_date
DATETIME, course_end_date DATETIME, exam_date DATETIME, score INT);
-- Add comments about the training table.
COMMENT ON COLUMN training.staff_id IS 'id of staffs taking training courses';

● Add comments when creating a table.


-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege
(staff_id INT PRIMARY KEY COMMENT 'id of the staff granted privileges',
privilege_name VARCHAR(64) NOT NULL COMMENT 'partitioning key',
privilege_description VARCHAR(64),
privilege_approver VARCHAR(10));

3.13.18 COMMIT

Description
COMMIT changes all operations in the work units of the current transaction to be
permanent and ends the transaction.

Precautions
The commission of data operations (INSERT, DELETE, and UPDATE) in GaussDB
100 is disabled by default. When a session exits, COMMIT must be explicitly
specified. Otherwise, the record will be lost.

Syntax
COMMIT [ TRANSACTION | PREPARED transaction_id | FORCE xid ]

Parameter Description
● TRANSACTION
Increases readability of the statement. This is an optional keyword.
● PREPARED
Prepares for a two-phase transaction commit. This is an optional keyword.
● transaction_id
Specifies the identifier of a transaction to be committed.
● FORCE
Forcibly commits residual transactions in RESTRICT mode. This keyword is
optional. Forcible commission of residual two-phase transactions is not
supported.
● xid
Specifies the identifier of the residual transaction to be forcibly committed.
The identifier can be obtained from the DV_TRANSACTIONS view. The value is
in form of SEG_ID.SLOT.XNUM enclosed with single quotation marks ('').

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 389


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
Create the training table, insert data, and update the data. Then, commit the
transaction.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL, staff_name VARCHAR(16), course_name CHAR(20),
course_start_date DATETIME, course_end_date DATETIME, exam_date DATETIME, score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'LIPENG','JAVA','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(11,'CAOM','JAVA','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Update the staff_name and course_name columns in record 2.
UPDATE training SET staff_name='WANGPAN', course_name='INFORMATION SAFETY' WHERE staff_id=11;
-- Commit the transaction.
COMMIT;

3.13.19 CREATE DATABASE


Description
CREATE DATABASE creates a database and files that store the database, or
creates a database by using existing database files.

Precautions
● To run this statement, you must have the CREATE DATABASE system
permission.
● This statement is invoked by the system during database installation.
● This statement can be executed only in the NOMOUNT database state.
● If a database fails to be created, restart the system before you recreate it after
rectifying the faults.
● During database creation, you can run the post-processing SQL script
initdb_customized.sql created in the $GSDB_HOME/admin/scripts directory.
● The post-processing SQL script must be created by users and the script name
must be initdb_customized.sql.
● If the post-processing script exists in DATADIR/admin/scripts/ (created by
users) when the database is started by running python zctl.py -t start [-D
DATADIR] NOMOUNT, only the script in this path is executed. Otherwise, the
post-processing script in $GSDB_HOME/admin/scripts is executed.
● Generally, DATADIR is $GSDB_DATA.

Syntax
CREATE DATABASE database_name
{ USER SYS IDENTIFIED BY password
| CONTROLFILE ( file_name [ , ... ] )
| database_logging_clauses
| tablespace_clauses
} [ ...]
● database_logging_clauses:
{ [ ARCHIVELOG | NOARCHIVELOG ] LOGFILE ( { 'file_name' SIZE integer [ K | M | G | T | P | E ]
[ BLOCKSIZE { 512 | 4096 } ]
} [ , ... ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 390


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

)
}
● tablespace_clauses:
{ default_tablespace
| temp_tablespace
| undo_tablespace
| system_tablespace
| nologging_tablespace
| nologging_undo_tablespace
} [ ...]
– default_tablespace:
DEFAULT TABLESPACE DATAFILE { datafile_tempfile_spec [ , ... ] }
– temp_tablespace:
TEMPORARY TABLESPACE TEMPFILE { datafile_tempfile_spec [ , ... ] }
– undo_tablespace:
UNDO TABLESPACE DATAFILE { datafile_tempfile_spec [ , ... ] }
– system_tablespace:
SYSTEM TABLESPACE DATAFILE { datafile_tempfile_spec [ , ... ] }
– nologging_tablespace:
NOLOGGING TABLESPACE TEMPFILE { datafile_tempfile_spec [ , ... ] }
– nologging_undo_tablespace:
NOLOGGING UNDO TABLESPACE TEMPFILE { datafile_tempfile_spec [ , ... ] }

▪ datafile_tempfile_spec:
{ 'file_name' SIZE integer [ K | M | G | T | P | E ]
[ autoextend_clause ]
}

○ autoextend_clause:
AUTOEXTEND { OFF
| ON [ NEXT integer [ K | M | G | T | P | E ] ]
}
[ MAXSIZE { integer [ K | M | G ]
| UNLIMITED
}
]

Parameter Description
● database_name
Specifies the name of a database to be created. The database name must be
unique on the server and comply with the identifier rule.
● USER SYS IDENTIFIED BY password
Specifies the password of user SYS for accessing the new database.
● CONTROLFILE ( file_name [, ...] )
Specifies a control file name. At least two files are specified, and the file size
is fixed to 10 MB.
● database_logging_clauses:
Creates a log group and members in the group and specifies whether logs will
be archived.
The size of a log file block can only be 512 or 4096.
– ARCHIVELOG
Enables log archiving.
– NOARCHIVELOG
Disables log archiving.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 391


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– LOGFILE
Specifies a log file.
– SIZE integer [ K | M | G | T | P | E ]
Specifies the file size. The default unit is byte. K indicates KB, M indicates
MB, G indicates GB, T indicates TB, and E indicates EB.
At least three redo log files are specified. The minimum file size is 56 MB
+ 16 KB + LOG_BUFFER_SIZE.
– BLOCKSIZE { 512 | 4096 }
specifies the block size. The unit is byte. Currently, only 512 bytes and
4096 bytes are supported.
– tablespace_clauses
Specifies the path and size of a SYSTEM, UNDO, TEMP, or default
tablespace and specifies how segments and extents are managed. If no
tablespace is specified when you create a table, the default tablespace is
used.

▪ default_tablespace
Specifies a default tablespace. The size of a data file in the USER
tablespace ranges from 1 MB to 8 TB.

▪ temp_tablespace
Specifies a temporary tablespace. The size of a data file in the TEMP
tablespace ranges from 5 MB to 8 TB.

▪ undo_tablespace
Specifies an undo tablespace. The size of a data file in the UNDO
tablespace ranges from 128 MB to 32 GB.

▪ system_tablespace
Specifies a system tablespace. The size of a data file in the SYSTEM
tablespace ranges from 128 MB and to 8 TB.

▪ nologging_tablespace
Specifies a nologging tablespace. The size of a data file in the
TEMP2 tablespace ranges from 1 MB to 8 TB.

▪ nologging_undo_tablespace
Specifies a nologging undo tablespace. The size of a data file in the
TEMP2_UNDO tablespace ranges from 128 MB to 32 GB.

▪ datafile_tempfile_spec
Multiple data files can be separated by commas (,). Currently, data
files cannot contain Chinese characters.

▪ file_name
Specifies the absolute path (path and file name) of a new data file. If
a relative path is specified, the file is stored in the data directory
under the data directory by default.

▪ SIZE integer[ K | M | G ]
Specifies the size of each data file.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 392


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

K: The unit is KB.


M: The unit is MB.
G: The unit is GB.

▪ autoextend_clause
If AUTOEXTEND is set to ON, you can manually specify the
extension size.
If AUTOEXTEND is not set, automatic extension is disabled by
default.
If AUTOEXTEND OFF is set, automatic extension is disabled.
If AUTOEXTEND ON is set, you can set the following parameters:
○ NEXT: extension size. If this parameter is not set, the default
value 16MB is used.
○ MAXSIZE: extension upper limit. If this parameter is not set or is
set to UNLIMITED, the extension upper limit for the undo
tablespace is 32 GB and that for other tablespaces is 8 TB. If this
parameter is set, the value for the undo tablespace cannot be
greater than 32 GB and that for other tablespaces cannot be
greater than 8 TB. If both MAXSIZE and NEXT are set, the value
of MAXSIZE must be no less than that of NEXT.

Examples
● Create the human database.
CREATE DATABASE human CONTROLFILE
('cntl1', 'cntl2', 'cntl3')
LOGFILE
('log1' size 2G, 'log2' size 2G, 'log3' size 2G, 'log4' size 2G, 'log5' size 2G, 'log6' size 2G)
SYSTEM TABLESPACE DATAFILE 'system' size 1G
UNDO TABLESPACE DATAFILE 'undo' size 1G
DEFAULT TABLESPACE DATAFILE 'user1' size 1G autoextend on next 32M, 'user2' size 1G autoextend on
next 32M, 'user3' size 1G autoextend on next 32M, 'user4' size 1G autoextend on next 32M, 'user5' size 1G
autoextend on next 32M
TEMPORARY TABLESPACE TEMPFILE 'temp1' size 160M autoextend on next 32M, 'temp2' size 160M
autoextend on next 32M ARCHIVELOG;

● Create the post-processing script initdb_customized.sql.


DROP TABLE IF EXISTS TEST_INITDB_CUSTOMIZED
/
CREATE TABLE TEST_INITDB_CUSTOMIZED
(
UID BINARY_INTEGER NOT NULL,
ID BINARY_INTEGER NOT NULL,NAME VARCHAR(64) NOT NULL,
MINVAL BINARY_BIGINT,
CYCLE_FLAG BINARY_INTEGER,
DIST_DATA VARCHAR(1024))
/

3.13.20 CREATE INDEX

Description
CREATE INDEX creates an index on a specified table. Indexes are primarily used to
enhance database query performance (though inappropriate use may comprise
the performance).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 393


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● Indexes cannot be created on columns of CLOB, BlOB, or IMAGE type.
● To run this statement, you must have the CREATE INDEX or CREATE ANY
INDEX system permission. Common users cannot create objects of system
users.
● A maximum of 16 columns are allowed for a combination index and the total
length cannot exceed 3900 bytes. It is calculated based on data types with the
maximum length.
● Partitioned indexes can be created only on partitioned tables. The number of
partition indexes must be the same as that of partitioned tables. Otherwise,
an error is reported.
● Function-based indexes can be created for the UPPER and TO_CHAR
functions. The function parameter can only be one column, and the function-
based indexes cannot be converted into constraints.
● Profiles cannot be created during database restart or rollback.

Syntax
CREATE [ UNIQUE ] INDEX [IF NOT EXISTS ] [ schema_name. ]index_name ON table_index_clause
[ CRMODE { PAGE | ROW } ]

● table_index_clause:
[ schema_name. ]table_name ( { [function_name()]column_name [ ASC | DESC ] } [ ,... ] )
index_attributes
– index_attributes:
[
[ physical_attributes_clause ]
[ TABLESPACE {tablespace_name} ]
[index_partitioning_clauses]
[ ONLINE ]
]

▪ physical_attributes_clause:
INITRANS integer

▪ index_partitioning_clauses:
LOCAL [ ( { PARTITION partition_name [ TABLESPACE tablespace_name ]
[ INITRANS integer ]
[ PCTFREE integer ]
} [ , ... ]
)
]

Parameter Description
● UNIQUE
Creates a UNIQUE index. In this way, the system checks whether new values
are unique in the index column. Attempts to insert or update data which
would result in duplicate values in the index column will generate an error.
Currently, only B-tree supports UNIQUE.
● IF NOT EXISTS
Does not throw an error if the index already exists. Does not throw an error if
the index does not exist.
● [schema_name.]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 394


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies a schema name. This parameter can be omitted if the schema name
is the same as the schema name of the table.
● index_name
Specifies the name of an index to be created.
● table_name
Specifies the name of the table (optionally schema-qualified) where an index
is to be created.
● function_name()
Specifies the name of a function based on which an index is created.
● column_name
Specifies the name of a column on which an index is to be created.
● ASC
Specifies an ascending (default) sort order.
● DESC
Specifies a descending sort order.
Currently, only an ascending order is supported even if DESC is specified.
● INITRANS
Specifies the initial size of an index transaction.
The value ranges from 1 to 255.
● TABLESPACE tablespace_name
Specifies the tablespace for an index. If no tablespace is specified, the default
tablespace is used.
● index_partitioning_clauses
Specifies the partial index of a partitioned table.
● LOCAL
Specifies a local partitioned index. The index is equipartitioned with the table
and the index partitioning is automatically maintained when partitions are
dropped or truncated. This ensures that the index always remains
equipartitioned with the table.
● PCTFREE
Specifies how much space should be left in a database block for inserting
indexes. The unit is % and the value range is [8, 80].
● ONLINE
Creates an index online.
Generally, exclusive locks are added to a table for index creation (DDL) on this
table, preventing concurrent UPDATE, DELETE, and INSERT operations and
thereby decreasing throughout of system catalog transactions. Therefore,
online index creation and rebuilding are used, during which share locks are
added to the table (exclusive locks are temporarily used only at the beginning
and end of the creation or rebuilding), allowing concurrent UPDATE, DELETE,
and INSERT operations and thereby ensuring the proper running of online
services.
● CRMODE { PAGE | ROW }
Specifies the CR mode of an index. If this parameter is not specified, the CR
mode of the table is used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 395


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– CRMODE PAGE indicates the page-level MVCC.


– CRMODE ROW specifies the row-level MVCC.

Examples
● Create an index online on the posts table.
-- Delete the posts table.
DROP TABLE IF EXISTS posts;
-- Create the common table posts.
CREATE TABLE posts(post_id CHAR(2) NOT NULL, post_name CHAR(6) PRIMARY KEY, basic_wage INT,
basic_bonus INT);
-- Create the idx_posts index.
CREATE INDEX idx_posts ON posts(post_id ASC, post_name) ONLINE;

● Create a partition index on the partitioned table education.


-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the partitioned table education.
CREATE TABLE education(staff_id INT NOT NULL, highest_degree CHAR(8), graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70))
PARTITION BY LIST(highest_degree)
(
PARTITION doctor VALUES ('Doctor'),
PARTITION master VALUES ('Master'),
PARTITION undergraduate VALUES ('Bachelor')
);
-- Insert record 1 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (10, 'Doctor', 'Xidian University', '2017-07-06 12:00:00', '211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (11, 'Doctor', 'Northwest A&F University', '2017-07-06 12:00:00', '211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (12, 'Master', 'Northwestern Polytechnical University', '2017-07-06 12:00:00', '211&985');
-- Insert record 4 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (15, 'Bachelor', 'Xi'an University of Architecture and Technology', '2017-07-06 12:00:00', 'not
211 or 985');
-- Insert record 5 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (18, 'Master', 'Xi'an University of Technology', '2017-07-06 12:00:00', '211&985');
-- Insert record 6 into the education table.
INSERT INTO education(staff_id, highest_degree, graduate_school, graduate_date, education_note)
VALUES (20, 'Bachelor', 'Beijing Normal University', '2017-07-06 12:00:00', '211&985');
-- Commit the transaction.
COMMIT;
-- Create a partitioned index.
CREATE INDEX idx_training ON education(staff_id ASC, highest_degree) LOCAL (PARTITION doctor,
PARTITION master, PARTITION undergraduate);
-- Create a function-based index.
CREATE INDEX idx_func ON education(upper(graduate_school));
CREATE INDEX idx_func_1 ON education(to_char(staff_id));

3.13.21 CREATE PROFILE

Description
CREATE PROFILE creates a profile to associate with a user.

Precautions
● To run this statement, you must have the CREATE PROFILE system
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 396


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The default profile is automatically created.


● You are not allowed to create or delete the default profile.
● If parameters in password_parameter are not set during profile creation, the
default values are used.
● PASSWORD_LIFE_TIME, PASSWORD_LOCK_TIME,
PASSWORD_GRACE_TIME, and PASSWORD_REUSE_TIME can be set to
scores (1 minute = 1/1440 days, and 1 second = 1/86400 days).
● The value of a resource item parameter ranges from 0 to 2147483647.
● Profiles cannot be created during database restart or rollback.

Syntax
CREATE PROFILE profile_name LIMIT password_parameters [ ... ]

password_parameters:
{ { FAILED_LOGIN_ATTEMPTS
| PASSWORD_LIFE_TIME
| PASSWORD_LOCK_TIME
| PASSWORD_GRACE_TIME
| PASSWORD_REUSE_TIME
| PASSWORD_REUSE_MAX
| SESSIONS_PER_USER
}
{ expr | UNLIMITED | DEFAULT }
}

Parameter Description
● profile_name
Profile name
If the profile name contains spaces or special characters other than _#$,
enclose the name with double quotation marks ("") or backquotes (``).
● LIMIT
Specifies resource limitations in a profile for a user.
● FAILED_LOGIN_ATTEMPTS
Specifies the maximum number of login attempts allowed before an account
is locked.
Default value: 10
● PASSWORD_LIFE_TIME
Specifies the maximum number of days that a password can be used.
The default value is 180 (unit: day).
● PASSWORD_LOCK_TIME
Specifies the number of days an account will be locked after the specified
number of consecutive failed login attempts.
The default value is 1 (unit: day).
● PASSWORD_GRACE_TIME
Specifies the grace period (days), that is, the duration from the time when the
database sends a warning to the time when the password becomes invalid. If
the database password is not changed during this period, the password
becomes invalid after the grace period expires.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 397


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The default value is 7 (unit: day).


● PASSWORD_REUSE_TIME
Specifies the number of days during which a password cannot be reused.
● PASSWORD_REUSE_MAX
– Specifies the number of last passwords that cannot be reused.
– PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX must be set in
conjunction with each other.
Set the two parameters as follows:

▪ If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set


to UNLIMITED. The password can be reused without any restrictions.

▪ If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set


to specified values, the password can be reused only when the
conditions specified by both the parameters are met.

▪ If either of PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME


is set to a specified value and the other is set to UNLIMITED, the
password cannot be reused.
● UNLIMITED
Specifies no limitations.
● DEFAULT
Uses default values of the parameters.

Examples
Create the pro_common profile.
-- Create the pro_common profile.
CREATE PROFILE pro_common LIMIT PASSWORD_GRACE_TIME 10 PASSWORD_LOCK_TIME DEFAULT
PASSWORD_LIFE_TIME UNLIMITED;
-- Delete the profile.
DROP PROFILE pro_common CASCADE;

3.13.22 CREATE ROLE

Description
CREATE ROLE creates a database role.

A role is a set of permissions (system permissions and object permissions). To


facilitate user operations, the following system roles are created by default after
the database is created:

DBA: Has all system permissions and cannot be deleted.

RESOURCE: Has the permission to create stored procedures, functions, triggers,


tables, and sequences.

CONNECT: Has the permission to connect to the database.

STATISTICS: Has the permission to create, delete, and view WSR snapshots and
generate WSR reports, but does not have the permission to set WSR parameters.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 398


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● To run this statement, you must have the CREATE ROLE system permission.
● A role name cannot be the same as any existing user name or role name in
the database. Otherwise, an error message will be displayed.

Syntax
CREATE ROLE role_name [ IDENTIFIED BY password [ ENCRYPTED ]]

Parameter Description
● role_name
Specifies the name of a role to be created.
If the role name contains spaces or special characters other than _#$, enclose
the name with double quotation marks ("") or backquotes (``).
● IDENTIFIED BY
Specifies the password for a role to be created.
● password
This is a reserved parameter.
● ENCRYPTED
Specifies that the password is ciphertext. In this case, the password will not be
verified.
Roles created in this mode use plaintext passwords for login. Therefore, you
are not advised to specify ENCRYPTED when creating a role.

Examples
Create the developers role.
-- Delete the developers role.
DROP ROLE developers;
-- Create the developers role.
CREATE ROLE developers;

3.13.23 CREATE SEQUENCE


Description
CREATE SEQUENCE adds a sequence generator to the current database.
The current user is the owner of the generator.

Precautions
● Sequence values are generated based on BIGINT. Therefore, the value of a
sequence is an integer with a maximum of eight bytes (-263 to 263-1). If the
minimum or maximum value specified for a sequence exceeds the range, the
system uses the upper or lower boundary of the range as the minimum or
maximum of this sequence.
● Sequences do not apply to concurrent-session scenarios because sequences
may not be generated in order due to concurrency.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 399


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● To run this statement, you must have the CREATE SEQUENCE, CREATE ANY
SEQUENCE, or ALL PRIVILEGES system permission.
● After a sequence is created, you can use the NEXTVAL and CURRVAL functions
to obtain values of the sequence. Common users cannot create objects of
system users.

Syntax
CREATE SEQUENCE [ schema_name. ]sequence_name
[ INCREMENT BY bigint
| START WITH bigint
| { MAXVALUE bigint | NOMAXVALUE }
| { MINVALUE bigint | NOMINVALUE }
| { CYCLE | NOCYCLE }
| { CACHE bigint | NOCACHE }
| { ORDER | NOORDER }
] [ ... ]

Parameter Description
● [ schema_name. ]
Username If this parameter is not specified, the current login user is used by
default.
● sequence_name
Specifies the name of a sequence to be created. It is optionally schema-
qualified.
● INCREMENT BY bigint
Specifies a sequence step.
The value is an integer other than 0. The default value is 1.
– If the value is a positive integer, an incremental sequence is generated.
– If the value is a negative integer, a decremental sequence is generated.
● START WITH bigint
Specifies the start value of a sequence.
start: start value of a sequence.
– The default start value of an incremental sequence is its MINVALUE.
– The default start value of a decremental sequence is its MAXVALUE.
● MAXVALUE bigint | NOMAXVALUE
MAXVALUE: maximum value of a sequence
NOMAXVALUE: A sequence does not have a maximum value.
If this clause is not declared or NOMAXVALUE is declared in the clause, the
default value is used.
– The default maximum value for an incremental sequence is 263-1.
– The default maximum value for a decremental sequence is -1.
● MINVALUE bigint | NOMINVALUE
MINVALUE: minimum value of a sequence.
NOMINVALUE: A sequence does not have a minimum value.
If this clause is not declared or NOMINVALUE is declared in the clause, the
default value is used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 400


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– The default minimum value for an incremental sequence is 1.


– The default minimum value for a decremental sequence is -263+1.
● CYCLE | NOCYCLE
CYCLE: A cycle is allowed when a sequence reaches its maximum or minimum
value. That is,
– When an incremental sequence reaches its maximum, the next data
generated is its minimum value.
– When a decremental sequence reaches its minimum, the next data
generated is its maximum value.
NOCYCLE: An error will be reported in the generation of the next data when
a sequence reaches its maximum or minimum value.
By default, NOCYCLE is specified.
● CACHE bigint | NOCACHE
– CACHE bigint specifies how many values of the sequence the database
preallocates and keeps in memory for faster access. The default value is
20, and the minimum value is 1. If the rounded up ((MAXVALUE –
MINVALUE)/INCREMENT) is smaller than CACHE bigint, the following
error message is displayed:
ERR_SEQ_INVALID: number to CACHE must be less than one cycle

– NOCACHE indicates that cache is disabled.


● ORDER | NOORDER
– ORDER: Sequence numbers are generated in order of request. If you want
to use sequence numbers as timestamps, this value is recommended. If
sequence numbers are used as primary key values, the order does not
matter much.
– NOORDER: Sequence numbers are generated not in order of request. By
default, NOORDER is specified.

Examples
Create the seq_auto_extend sequence.
-- Delete the seq_auto_extend sequence.
DROP SEQUENCE IF EXISTS seq_auto_extend;
-- Create the seq_auto_extend sequence starting with 10, and with INCREMENT BY set to 2, MAXVALUE
set to 200, and CYCLE specified.
CREATE SEQUENCE seq_auto_extend START WITH 10 MAXVALUE 200 INCREMENT BY 2 CYCLE;

3.13.24 CREATE SYNONYM

Description
CREATE SYNONYM creates a synonym.

Precautions
● When creating a synonym, specify the object for which the synonym is to be
created.
● The specified object must exist.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 401


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● You can create a synonym only for a table or view. When you create a
synonym for other objects, the error message "synonym object %s.%s is not
table or view type" is displayed.
● If an object is modified or deleted, an error will be reported when its synonym
is used.
● You can query the MY_SYNONYMS and ADM_SYNONYMS views to view
synonyms.
● To run this statement, you must have the CREATE SYNONYM, CREATE ANY
SYNONYM, or ALL PRIVILEGES permission. Common users cannot create
objects of system users.
● If you specify a schema name when creating a public synonym, an error will
be displayed indicating the inconsistency.
● To create a public synonym, you must have the CREATE PUBLIC SYNONYM
system permission. Otherwise, an error will be reported.

Syntax
CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM [ schema_name. ]synonym_name FOR
[ schema_name. ]object_name

Parameter Description
● OR REPLACE
Replaces a synonym if it exists when you create it.
● [ schema_name. ]
Specifies a user name. If this parameter is not specified, the current login user
is used by default.
● PUBLIC
Creates a public synonym. Other users can access the synonym without being
authorized but the system still checks the specified object.
You can create a synonym with the same name as a public synonym.
● synonym_name
Specifies the name of a synonym to be deleted. Specify the name by following
the database object naming convention.
● object_name
Specifies the name of an object for which a synonym is to be created. Specify
the name by following the database object naming convention. The number
of synonyms that can be created for a table or view is not limited.
The value is a table or view name.

Examples
● Create a public synonym and a private synonym for the privilege_view view.
-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege(staff_id INT PRIMARY KEY, privilege_name VARCHAR(64) NOT NULL,
privilege_description VARCHAR(64), privilege_approver VARCHAR(10));
-- Create the view privilege_view.
CREATE OR REPLACE VIEW privilege_view AS SELECT staff_id, privilege_name from privilege;
-- Create a public synonym for the privilege_view view.
CREATE OR REPLACE PUBLIC SYNONYM pri_vi for privilege_view;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 402


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create a private synonym for the privilege_view view.


CREATE OR REPLACE SYNONYM pri_vi for privilege_view;

● Create a public synonym and a private synonym for the privilege table.
-- Create a public synonym for the privilege table.
CREATE OR REPLACE PUBLIC SYNONYM pri for privilege;
-- Create a private synonym for the privilege table.
CREATE OR REPLACE SYNONYM pri for privilege;

3.13.25 CREATE TABLE


Function
CREATE TABLE creates a table.

Precautions
● To create a table for the current user, you must have the CREATE TABLE
system permission. To create a table for other users, you must have the
CREATE ANY TABLE system permission. Common users cannot create objects
of system users.
● Ensure that the storage space is sufficient.
● You must specify a table name and column names (including the data type
and size of each column).
● An incremental sequence supports only the INT and BIGINT data types. Only
one incremental sequence can be created in a table, and the sequence
column must be the primary key or unique index of this table.
● Currently, character sets and row_movement_clause support only SQL parsing.
● If no column is specified when a foreign key is created, the primary key of the
parent table is used by default. If the parent table has no primary key, an
error will be reported.
● In a temporary table, a BLOB column is defined as RAW(8000) and a CLOB
column is defined as VARCHAR(8000 BYTE).
● A local temporary table supports only ON COMMIT PRESERVE ROWS and
the table name must start with a number sign (#). In addition,
LOCAL_TEMPORARY_TABLE_ENABLED=TRUE must be set to specify whether
to enable local temporary tables.
● A global temporary table can be a transaction- or session-level temporary
table.
– ON COMMIT PRESERVE ROWS: If a session ends, the temporary table
data is deleted but the table structure remains.
– ON COMMIT DELETE ROWS: If a transaction ends, the temporary table
data is deleted but the table structure remains.
– If the ON COMMIT {DELETE | PRESERVE} ROWS clause is not specified,
a transaction-level temporary table is created by default.

Syntax
[ON COMMIT {DELETE | PRESERVE} ROWS] can be used only for temporary
tables.
TABLESPACE tablespace_name cannot be used for temporary tables.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 403


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

CREATE [[ GLOBAL ] TEMPORARY ] TABLE [ IF NOT EXISTS ][ schema_name.] table_name


{ relational_properties
| [ ( column_name [ DEFAULT expr [ ON UPDATE expr ] ] [ AUTO_INCREMENT ] [COMMENT 'string']
[COLLATE collation_name] [inline_constraint] | out_of_line_constraint ) ] AS query
}
[ ON COMMIT { DELETE | PRESERVE } ROWS ]
[ physical_properties ]
[ TABLESPACE tablespace_name ]
[ table_properties ]
[ CRMODE { PAGE | ROW } ]
[ NOLOGGING]

● relational_properties:
AUTO_INCREMENT and DEFAULT cannot be used together.
( {column_name datatype_name [ DEFAULT expr [ ON UPDATE expr ] ] [ AUTO_INCREMENT ]
[ COMMENT 'string' ] [ COLLATE collation_name ] [ inline_constraint ]} [, ... ] )

– inline_constraint:
references_clause cannot be used for temporary tables.
PRIMARY KEY and UNIQUE cannot be used together.
[ CONSTRAINT constraint_name ] { [ NOT ] NULL
| UNIQUE
| PRIMARY KEY
| CHECK( expr )
| references_clause
}[...]

▪ references_clause:
REFERENCES [ schema_name. ]object_table [( column_name )] [ON DELETE { CASCADE |
SET NULL } ]

– out_of_line_constraint:
[ CONSTRAINT constraint_name ] { UNIQUE( column_name [ , ... ] ) [ using_index_clause ]
| PRIMARY KEY( column_name [ , ... ] ) [ using_index_clause ]
| CHECK( expr )
| FOREIGN KEY( column_name [ , ... ] ) references_clause_ex
}[ ,...]

▪ using_index_clause:
USING INDEX [ INITRANS integer
| TABLESPACE tablespace_name
| LOCAL [ ( { PARTITION partition_name [ TABLESPACE tablespace_name
| INITRANS integer
| PCTFREE integer
]
} [ , ... ]
)
]
] [ ...]

▪ references_clause_ex:
REFERENCES [ schema_name. ]object_table_name [( column_name [ , ... ] )]
[ ON DELETE { CASCADE | SET NULL } ]

● AS query:
SELECT [SQL_CALC_FOUND_ROWS] [ DISTINCT ] expression
[ [ AS ] name ] [ , ... ]
[ FROM table_reference [ [AS] alias ] [ , ... ] ]
[ WHERE { condition | [ NOT ] EXISTS ( correlated subquery ) } ]
[ [START WITH condition ] CONNECT BY [ NOCYCLE ] [ PRIOR ] condition ]
[ GROUP BY { column_name | number } [ , ... ] ]
[ HAVING condition [ , ... ] ]
[ { UNION [ ALL ] } select ]
[ ORDER BY { column_name | number } [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] [ , ... ] ]
[ LIMIT [ offset_expr, ] count_expr | LIMIT count_expr OFFSET offset_expr | OFFSET offset_expr
[ LIMIT count_expr ] ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 404


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● physical_properties:
{ segment_attributes_clause
}

– segment_attributes_clause:
TABLESPACE tablespace_name cannot be used for temporary tables.
{ physical_attributes_clause
| TABLESPACE tablespace_name
} [ ... ]

▪ physical_attributes_clause:
{ PCTFREE integer
| INITRANS integer
| MAXTRANS integer
} [ ...]

● table_properties:
[ column_properties ]
[ AUTO_INCREMENT [ = ] value ]
[ AS subquery]

– column_properties:
[ LOB_storage_clause ]
[ APPENDONLY { ON | OFF } ]

▪ LOB_storage_clause:
LOB ( LOB_item ) STORE AS { [ ( LOB_parameters ) ] }

○ LOB_parameters:
[ TABLESPACE tablespace_name
| { ENABLE | DISABLE } STORAGE IN ROW
][ ... ]

Parameter Description
● GLOBAL
Creates a global table.
● TEMPORARY
Creates a temporary table.
● IF NOT EXISTS
Does not throw an error if a table already exists.
● [schema_name.]table_name
Specifies the name of a table to be created. The table name must be unique
for a user. The name of a local temporary table must start with a number sign
(#). When creating a local temporary table, set
LOCAL_TEMPORARY_TABLE_ENABLED to TRUE and do not specify GLOBAL.
● relational_properties
Specifies table properties, including column names, data types, inline
constraints, and out-of-line constraints.
● DEFAULT expr [ON UPDATE expr]
Specifies an expression used to calculate the default value of a column. In
DDL, DEFAULT specifies a constant expression, the data type of this constant
will be checked for data compatibility.
– ON UPDATE expr specifies the default update value to be used if
DEFAULT is not set. It is compatible with the mainstream syntax in the
industry.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 405


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– The expression contains a maximum of 1024 characters. If the length


exceeds the maximum, the error message "GS-00611, default value string
is too long, exceed 1024." is displayed.
● AUTO_INCREMENT
Specifies an auto-increment column.
– If NULL is inserted into an auto-increment column, GaussDB 100
automatically generates the next sequence value. The sequence increases
from 1.
– The effect of inserting 0 into an auto-increment column is the same as
that of inserting NULL. However, you are not advised to insert 0. NULL is
recommended.
– If AUTO_INCREMENT does not generate a sequence value, the effect is
the same as that of inserting NULL.
– If a value is specified for AUTO_INCREMENT, a record will be inserted in
either of the following ways:

▪ If the inserted value is the same as an existing number, an error


message will be displayed because the values in the
AUTO_INCREMENT column must be unique.

▪ If the inserted value is greater than the existing numbers, the value is
inserted into the column and the next number increments from this
new value. That is, a sequence can increment, skipping some
numbers.
– If an increment sequence is updated by using the UPDATE statement and
a generated value duplicates with the existing number, an error will be
reported. If the value is greater than the existing number, the existing
number is replaced with the value and the sequence proceeds with
incrementing from this value.
– To prevent overflow, you are advised to set the maximum value of a
sequence to 0x7FFFFFFFFFFFFFFF.
● COMMENT 'string'
Adds a comment for a column. You can view comments by querying the
USER_COL_COMMENTS system view.
● COLLATE collation_name
Specifies a collation rule for a column. The rule specifies how data is sorted
and compared.
collation_name can be set to the following parameters:
– UTF8_BIN: applicable to the UTF8 character set. All characters are
considered as binary strings and are compared from the most significant
bit to the least significant bit. The characters to be compared are case-
sensitive.
– UTF8_GENERAL_CI: applicable to the UTF8 character set. The characters
to be compared are case-insensitive.
– UTF8_UNICODE_CI: applicable to the UTF8 character set. The characters
to be compared are case-insensitive.
– GBK_BIN: applicable to the GBK character set. The characters to be
compared are case-sensitive.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 406


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– GBK_CHINESE_CI: applicable to the GBK character set. The characters to


be compared are case-insensitive.
● inline_constraint
Adds a column constraint. It is included in the column definition. Currently,
the NULL, NOT NULL, UNIQUE, PRIMARY KEY, UNIQUE INDEX, FOREIGN KEY,
and CHECK constraints are supported.
● out_of_line_constraint
Adds a table constraint. It is included as a separate line in the table
definition . Currently, UNIQUE, PRIMARY KEY, and CHECK constraints are
supported.
● [ NOT ] NULL
Specifies whether a column can hold NULL values.
– NOT NULL: The column cannot hold NULL values.
– NULL: The column can hold NULL values.
● UNIQUE
Specifies that values in a column must be unique. NULL values are allowed.
The UNIQUE constraint can be added to multiple columns in a table.
● PRIMARY KEY
Specifies a primary key including one or more columns that uniquely identify
a row in the table. NULL values are not allowed. Only one primary key can be
created for a table.
● CHECK( expr )
Specifies rules for checking values in a column. If NULL is inserted, TRUE is
returned.
● ON DELETE { CASCADE | SET NULL }
Specifies how foreign key values in a child table are handled when primary or
unique values in the parent table are deleted.
– CASCADE
The foreign key values will be deleted.
– SET NULL
The foreign key values will be converted to NULL.
● FOREIGN KEY
Specifies a foreign key.
● INITRANS integer
Specifies the initial size of the transaction table in a block header.
● TABLESPACE tablespace_name
Specifies a tablespace.
● LOCAL
Creates local indexes. It is a default attribute.
● PARTITION partition_name
Specifies a partitioned table.
● SQL_CALC_FOUND_ROWS
Obtains the total number of rows returned by a statement. It is equivalent to
select count(*) from and is used for paged queries.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 407


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● DISTINCT
Deduplicates column data. Single- or multi-column deduplication is
supported.
● [AS] name
Specifies the alias of a column to be printed.
● FROM table_reference [ [AS] alias ] [ , ... ]
Specifies a table to be queried.
– table_reference
Specifies the referenced table in a query. If it is a temporary table that
contains LOB columns, inline storage and out-of-line storage cannot be
used.
– [AS] alias
Specifies the alias of a table to be queried, facilitating join queries.
● WHERE { condition | [ NOT ] EXISTS ( correlated subquery )
Specifies conditions used for filtering rows.
correlated subquery
Specifies a correlated subquery.
● START WITH condition CONNECT BY [ NOCYCLE ] [ PRIOR ] condition
Specifies a clause for querying tree-structured data. If a table contains tree-
structured data, you can use this clause to query data.
– START WITH
Specifies the row that is the root of a tree-structured data query.
– CONNECT BY
Specifies the relationship between parent rows and child rows of a tree-
structured data query. It is used in conjunction with PRIOR.
– NOCYCLE
Instructs the database to return rows from a query even if CONNECT BY
LOOP exists in the data.
– PRIOR
PRIOR is a unary operator and has the same precedence as the unary +
and - arithmetic operators. The PRIOR keyword can be on either side of
the equal sign (=). If PRIOR is placed together with the parent ID, the
query traverses data in the direction of parent nodes. If it is placed
together with the child ID, the query traverses data in the direction of
child nodes.
● GROUP BY { column_name | number } [ , ... ]
Groups data based on attributes. Data is sorted before being grouped.
– column_name
Specifies the column based on which data is grouped.
– number
Specifies the sequence number of column_name in the table.
● HAVING condition [ , ... ]
Specifies the conditions used for filtering the result set returned by GROUP
BY.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 408


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● { UNION [ ALL ] } select


Merges the result sets of two or more SELECT statements. If the keyword ALL
is not specified, duplicate rows will be excluded from the returned result.
ALL
All rows in the table meeting the conditions will be returned.
● ORDER BY { column_name | number } [ ASC | DESC ] [ NULLS FIRST |
NULLS LAST ] [ , ... ]
Specifies the sorting condition (column_name or number). If [NULLS FIRST |
NULLS LAST] is not specified, NULLS LAST is used in ASC mode and NULLS
FIRST is used in DESC mode by default.
– column_name
Specifies the name of the column to be sorted.
– number
Specifies the sequence number of a sorted column.
– ASC
Sorts data in ascending order.
– DESC
Sorts data in descending order.
– NULLS FIRST
Specifies that NULL values are placed before non-NULL values in an ORDER
BY column.
– NULLS LAST
Specifies that NULL values are placed after non-NULL values in an ORDER BY
column.
● LIMIT [ offset_expr, ] count_expr | LIMIT count_expr OFFSET offset_expr |
OFFSET offset_expr [ LIMIT count_expr ]
COUNT and OFFSET specify conditions for returning a subset of the result
set.
– offset_expr
Specifies the start position of a result subset. For example, if there are
100 records in the result set and offset_expr=10 is set, the result
returning will start from the 10th record.
– count_expr
Specifies the number of records to be returned. For example, if there are
100 records in the result set and count_expr=40 is set, 40 of the 100
records will be returned.
– OFFSET
Specifies a keyword indicating the start position of data.
● PCTFREE integer
Specifies the percentage of space reserved for a block. If the percentage of
available space of a data block is less than this value, you can only update
data of this block and cannot insert data into it. The value range is [8, 80]
and the default value is 8.
● INITRANS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 409


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies the number of transaction slots in the initial data block.


● MAXTRANS
Specifies the maximum number of transaction slots in an initial data block.
● table_properties
Specifies table attributes.
● AUTO_INCREMENT [=] value
Specifies a start value for an incremental sequence.
If no value is specified, the sequence increments from 1.
● APPENDONLY { ON | OFF }
– APPENDONLY ON indicates that a new page will be used for when
different threads insert data into the same table even though there are
pages that are not full. In this case, the page lock waiting duration is
shortened but the page space is wasted.
– APPENDONLY OFF indicates that data will be inserted into pages that
are not full when different threads insert data into the same table. In this
case, the page lock waiting duration is long.
If this parameter is not specified, the default value OFF is used.
● AS subquery
Specifies a subquery. When a table is created, the rows returned by the
subquery are inserted into the table.
● LOB_storage_clause
– LOB ( LOB_item ) STORE AS { [ ( LOB_parameters ) ]
Specifies that LOB columns are stored in a separate segment. You can
specify inline or out-of-line storage for a table. Currently, only out-of-line
storage is supported.
– LOB_item
Specifies the name of a LOB column.
– LOB_parameters
Specifies storage parameters for a LOB column.
{ENABLE | DISABLE } STORAGE IN ROW
Specifies whether to enable inline storage or out-of-line storage.

▪ ENABLE
Inline storage is used.

▪ DISABLE
Out-of-line storage is used.
● CRMODE { PAGE | ROW }
Specifies the CR mode of a table. If this parameter is not specified, the CR
mode of the current instance is used.
– CRMODE PAGE indicates the page-level MVCC.
– CRMODE ROW specifies the row-level MVCC.
● NOLOGGING
Specifies that a table is a nologging table. Different from a common table, a
nologging table does not record logs for better performance. As a result, a

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 410


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

nologging table cannot be restored by replaying redo logs after a database


restart. Usually, a nologging table is used to store temporary data.
– After the database is restarted, the definition of a nologging table is
retained and the table data is cleared.
– A nologging table does not support flashback, recycle bin, and two-phase
commit.
– The definition of a nologging table supports primary/standby replication.
Table data is not replicated.
– The definition of a nologging table supports backup and restoration.
Table data is not backed up.
– A nologging table supports MVCC, rollback, DDL, and DML.
– A nologging table can be stored only in a nologging tablespace.
– By default, a nologging table and its indexes are stored in temp2. You
can specify a nologging tablespace for a nologging table and its indexes.
– If the NOLOGGING keyword is not specified when you create a table but
the table is stored in a nologging tablespace, this table is a nologging
table.
– All partitions in a nologging partitioned table must be stored in
nologging tablespaces.
– In the dba_tables view, table_type of a nologging table is NOLOGGING.

Examples
● Create a global session-level temporary table sections.
-- Delete the sections table.
DROP TABLE IF EXISTS sections;
-- Create the sections table.
CREATE GLOBAL TEMPORARY TABLE sections
(
section_id NUMBER(4) not null,
section_name VARCHAR2(30),
manager_id NUMBER(6),
place_id NUMBER(4)
) ON COMMIT PRESERVE ROWS;
-- Insert record 1.
insert into sections (section_id, section_name, manager_id, place_id)
values (10, 'Administration', 200, 1700);
-- Insert record 2.
insert into sections (section_id, section_name, manager_id, place_id)
values (20, 'Marketing', 201, 1800);
-- Insert record 3.
insert into sections (section_id, section_name, manager_id, place_id)
values (30, 'Purchasing', 114, 1700);
-- Commit the transaction.
COMMIT;
-- Display place_id in DISTINCT mode.
SELECT DISTINCT place_id FROM sections;
● Create the education table.
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70));
● -- Create the training table.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 411


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

(
staff_id INT NOT NULL,
course_name VARCHAR(50),
course_start_date DATETIME,
course_end_date DATETIME,
exam_date DATETIME,
score INT
);

● Create the privilege table.


-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege(staff_id INT PRIMARY KEY, privilege_name VARCHAR(64) NOT NULL,
privilege_description VARCHAR(64), privilege_approver VARCHAR(10));

● Create a temporary table that contains BLOB and CLOB columns defined as
RAW(8000) and VARCHAR(8000), respectively.
-- Delete the STAFFS table.
CREATE GLOBAL TEMPORARY TABLE STAFFS
(
staff_id INT NOT NULL,
course_name BLOB,
COMMENT CLOB
);
-- Query the STAFFS table.
DESC STAFFS;
Name Null? Type
----------------------------------- -------- ------------------------------------
STAFF_ID NOT NULL BINARY_INTEGER
COURSE_NAME RAW(8000)
COMMENT VARCHAR(8000 BYTE)

3.13.26 CREATE TABLESPACE

Description
CREATE TABLESPACE creates a tablespace.

Precautions
● To run this statement, you must have the CREATE TABLESPACE system
permission.
● Do not set the data file path to the run log directory, log archiving directory,
or any directory that may be cleared.
● AUTOOFFLINE can be set only for user tablespaces.

Syntax
CREATE TABLESPACE tablespace_name [ EXTENTS integer ]
DATAFILE { datafile_tempfile_spec [, ... ] } [NOLOGGING] [autooffline_clause]

● datafile_tempfile_spec:
'file_name' SIZE integer [ K | M | G ] [ autoextend_clause ]

– autoextend_clause:
AUTOEXTEND { OFF
| ON [ NEXT integer [ K | M | G ] ]
[ MAXSIZE integer [ K | M | G ] | UNLIMITED ]
}

● autooffline_clause clause:
AUTOOFFLINE [ ON | OFF ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 412


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Parameter Description
● tablespace_name
Specifies a tablespace name. The value must be different from existing
tablespace names. Otherwise, an error is reported.
EXTENTS
Specifies the number of pages in an extent.
The value must be integral power of 2 within the range [8, 8192]. If EXTENTS
is not specified, an extent contains 8 pages by default.
Increasing the number of pages in a single extent can improve I/O
performance. However, if there are small tables in the tablespace and the
table data volume does not reach the size of an extent, space will be wasted.
● DATAFILE
Specifies table files.
● datafile_tempfile_spec
Multiple data files can be separated by commas (,). Data files cannot contain
Chinese characters.
– file_name
Specifies the absolute path (path and file name) of a new data file. If a
relative path is specified, the file is stored in the data directory under the
data directory by default.
– SIZE integer[ K | M | G ]
Specifies the size of each data file.
K: The unit of the file size is KB.
M: The unit of the file size is MB.
G: The unit of the file size is GB.
The value range for the undo tablespace is [1 MB, 32 GB) and that for
other tablespaces is [1 MB, 8 TB].
– autoextend_clause
If AUTOEXTEND is set to on, you can manually specify the extension size.

▪ If AUTOEXTEND is not set, automatic extension is disabled by


default.

▪ If AUTOEXTEND OFF is set, automatic extension is disabled.

▪ If AUTOEXTEND ON is set, you can set the following parameters:


○ NEXT: extension size. If this parameter is not set, the default
value 16MB is used.
○ MAXSIZE: extension upper limit.
If this parameter is omitted or is set to UNLIMITED, the
maximum size of the undo tablespace is 32 GB, and that of
other tablespaces is 8 TB.
If this parameter is set to a value. This value cannot be greater
than 32 GB for the undo tablespace, and cannot be greater than
8 TB for other tablespaces.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 413


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

If both MAXSIZE and NEXT are set, the value of MAXSIZE must be
no less than that of NEXT.
● NOLOGGING
Specifies that a tablespace is a nologging tablespace. Tables in this tablespace
are nologging tables. A nologging table can be stored only in a nologging
tablespace.
– CREATE DATABASE creates tablespaces temp2 and temp2_undo by
default to store common data and undo data of nologging tables,
respectively.
– Globally, tmp2_undo is the only tablespace to store undo data of
nologging tables. This tablespace cannot be deleted or renamed.
– You can create multiple tablespaces for storing data of nologging tables.
– You can use DV_TABLESPACES to display nologging tablespaces. The
value in the temporary column for nologging tablespaces is true.
● autooffline_clause
Specifies whether automatic offline is enabled for tablespaces. If
AUTOOFFLINE is set to ON, automatic offline is enabled for user tablespaces.
When a file fails to be opened during database startup, the user tablespace is
automatically brought offline. If a user tablespace is faulty after the database
is started, the tablespace is not automatically brought offline.

Examples
● Create the vedio_space tablespace with the size of 32 MB.
CREATE TABLESPACE vedio_space DATAFILE 'vedio_dfile1' SIZE 32M;
● Create the image_space tablespace. An extent contains 128 pages. Create the
image_space tablespace with the size of 32 MB. When the tablespace is full,
it can automatically extend. You can specify the extension size.
CREATE TABLESPACE image_space EXTENTS 128 DATAFILE 'image_dfile1' SIZE 32M AUTOEXTEND ON
NEXT 10M;

3.13.27 CREATE TABLE PARTITION


Description
CREATE TABLE PARTITION creates a partitioned table.
Partitioning refers to splitting a large logical table into smaller physical pieces
based on specific rules. In this case, the logic table is called a partitioned cable,
and a physical piece is called a partition. A partitioned table is a logical table that
does not store data. Data is stored in partitions. Common users cannot create
objects of system users.

Context
GaussDB 100 supports range partitioning, hash partitioning, list partitioning, and
interval partitioning.
● In range partitioning, a table is partitioned based on ranges defined by values
in one or more columns, with no overlap between the ranges of values
assigned to different partitions. Each range has a dedicated partition for data
storage.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 414


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

In range partitioning, table is partitioned based on partition key values. If a


record can be mapped to a partition, it is inserted into the partition; if it
cannot, an error message is returned. Range partitioning is the most
commonly used partitioning policy.
● In hash partitioning, the database maps rows to the partition keys specified
by users based on the hash algorithm. The storage destination of a row is
determined by the internal hash function of the database. The hash algorithm
is used to evenly distribute rows on devices.
● In list partitioning, a table is partitioned based on a specific value in a
specified column.
● Interval partitioning is an extension of range partitioning and instructs the
database to automatically create partitions of a specified interval when data
inserted into the table exceeds all of the existing range partitions.
Partitioning can provide several benefits:
● Query performance can be improved dramatically in certain situations,
especially when a row with a higher access rate is located in a separate
partition or a few partitions. In this case, partitioning can reduce the data to
be searched and improve data access efficiency.
● When queries or updates access a large percentage of a single partition,
performance can be improved by taking advantage of sequential scan of that
partition instead of partitions scattered across the whole table.
● If a large number of records to be loaded or deleted are located on a single
partition, you can load or delete the records simply by loading or deleting
that partition, improving the performance.

Precautions
● To create a table for the current user, you must have the CREATE TABLE
system permission. To create a table for other users, you must have the
CREATE ANY TABLE system permission. Common users cannot create objects
of system users.
Restrictions on creating a partitioned table are as follows:
● A partition key contains a maximum of 16 columns.
● Partition keys support the following data types: INT, INTEGER, BIGINT,
NUMBER, DECIMAL, REAL, DOUBLE, NUMERIC, VARCHAR, VARCHAR2, CHAR,
BINARY, RAW, VARBINARY, DATE, DATETIME, and TIMESTAMP.
● Currently, range partitioning, list partitioning, hash partitioning, and interval
partitioning are supported.
● A maximum of 4,194,304 interval partitions are supported. If the total
number of interval partitions exceeds 4194304, an error is reported.

Syntax
CREATE TABLE [ IF NOT EXISTS ][ schema_name. ]table_name
[ relational_properties ]
[ physical_properties ]
[ TABLESPACE tablespace_name]
[ table_properties ]
● relational_properties:
AUTO_INCREMENT and DEFAULT cannot be used together.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 415


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

{ column_name datatype_name [DEFAULT expr [ ON UPDATE expr ]] [ AUTO_INCREMENT ]


[ COMMENT 'string' ] [ COLLATE collation_name ]
[ inline_constraint ] | [ out_of_line_constraint ]
} [ , ... ]

– inline_constraint:
PRIMARY KEY and UNIQUE cannot be used together.
[ CONSTRAINT constraint_name ] { [ NOT ] NULL
| UNIQUE
| PRIMARY KEY
| CHECK( expr )
| references_clause
}[...]

▪ references_clause:
REFERENCES [ schema_name. ]object_table_name ( column_name )
[ ON DELETE { CASCADE | SET NULL } ]

– out_of_line_constraint:
[ CONSTRAINT constraint_name ] { UNIQUE( column_name [ , ... ] ) [ using_index_clause ]
| PRIMARY KEY( column_name [ , ... ] ) [ using_index_clause ]
| CHECK( expr )
| FOREIGN KEY( column_name [ , ... ] ) references_clause_ex
}

▪ using_index_clause:
USING INDEX
[ INITRANS integer
| TABLESPACE tablespace_name
| LOCAL [ ( { PARTITION partition_name [ TABLESPACE tablespace_name
| INITRANS integer
| PCTFREE integer
]
} [ , ... ]
)
]
] [ ...]

▪ references_clause_ex:
REFERENCES [ schema_name. ]object_table_name ( column_name [ , ... ] ) [ ON DELETE
{ CASCADE | SET NULL } ]

● physical_properties:
{ segment_attributes_clause

– segment_attributes_clause:
{ physical_attributes_clause
| TABLESPACE tablespace_name
} [ ... ]

▪ physical_attributes_clause:
[ { PCTFREE integer
| INITRANS integer
} [ ...]
]

● table_properties:
[ column_properties ]
[ table_partitioning_clauses ]
[ AUTO_INCREMENT [ = ] value ]

– column_properties:
[ LOB_storage_clause ]
[ APPENDONLY { ON | OFF } ]

▪ LOB_storage_clause:
LOB ( LOB_item ) STORE AS { LOB_segname [ ( LOB_parameters ) ] }

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 416


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

○ LOB_parameters:
[ TABLESPACE tablespace_name
| { ENABLE | DISABLE } STORAGE IN ROW
] [ ... ]

– table_partitioning_clauses:
{ range_partitioning
| list_partitioning
| hash_partitioning
| interval_partitioning
}

▪ range_partitioning:
PARTITION BY RANGE ( partition_key [ , ... ] )
( { PARTITION partition_name VALUES LESS THAN ( { partition_value
| MAXVALUE
} [ , ... ]
)
[ TABLESPACE tablespace_name ]
[physical_attributes_clause]
} [ , ... ]
)

▪ list_partitioning:
PARTITION BY LIST ( partition_key [ , ... ] )
( { PARTITION partition_name VALUES ( partition_value [ , ... ]
|[ DEFAULT ]
)
[ TABLESPACE tablespace_name ]
[ physical_attributes_clause ]
} [ , ... ]
)

▪ hash_partitioning:
PARTITION BY HASH ( partition_key [ , ... ] )
{ ( { PARTITION partition_name
[ TABLESPACE tablespace_name ]
[ physical_attributes_clause ]
} [ , ... ]
)
| PARTITIONS partition_count [ STORE IN (tablespace_name [ , ... ]) ]
}

▪ interval_partitioning:
PARTITION BY RANGE ( partition_key ) INTERVAL ( interval_value )
( { PARTITION partition_name VALUES LESS THAN
( partition_value )
[ TABLESPACE tablespace_name ]
[ physical_attributes_clause ]
} [ , ... ]
)

Parameter Description
● IF NOT EXISTS
Does not throw an error and replaces the existing table if a table already
exists.
● [schema_name.]table_name
Specifies the name of a table to be partitioned. The table name must be
unique for a user.
● tablespace_name
Specifies the tablespace of a range partition.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 417


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

This parameter specifies the tablespace of a range partition in a partitioned


table.
● relational_properties
Specifies table properties, including column names, data types, inline
constraints, and out-of-line constraints.
● DEFAULT expr [ON UPDATE expr]
Specifies an expression used to calculate the default value of a column. In
DDL, DEFAULT specifies a constant expression, the data type of this constant
will be checked for data compatibility.
– ON UPDATE expr specifies the default update value to be used if
DEFAULT is not set.
– The expression contains a maximum of 1024 characters. If the length
exceeds the maximum, the error message "GS-00611, default value string
is too long, exceed 1024." is displayed.
● AUTO_INCREMENT
Enables auto increment.
– If NULL is inserted into an auto-increment column, GaussDB 100
automatically generates the next sequence value. The sequence increases
from 1.
– The effect of inserting 0 into an auto-increment column is the same as
that of inserting NULL. However, you are not advised to insert 0. NULL is
recommended.
– If AUTO_INCREMENT does not generate a sequence value, the effect is
the same as that of inserting NULL.
– If a sequence value is generated by AUTO_INCREMENT for a record and
is to be inserted into the table, the following conditions may occur: if the
value is the same as the existing number, an error message is displayed
due to value duplication; if the value is greater than the existing number,
the existing number is replaced with the value and the sequence proceeds
with incrementing from this value. That is, a sequence can increment,
skipping some numbers.
– If an increment sequence is updated by using the UPDATE statement and
a generated value duplicates with the existing number, an error will be
reported. If the value is greater than the existing number, the existing
number is replaced with the value and the sequence proceeds with
incrementing from this value.
– To prevent overflow, you are advised to set the maximum value of a
sequence to 0x7FFFFFFFFFFFFFFF.
● COMMENT 'string'
Adds a comment for a column. You can view comments by querying the
USER_COL_COMMENTS system view.
● COLLATE collation_name
Specifies a collation rule for a column.
The rule specifies how data is sorted and compared.
collation_name can be set to the following parameters:
– UTF8_BIN: applicable to the UTF8 character set. All characters are
considered as binary strings and are compared from the most significant

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 418


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

bit to the least significant bit. The characters to be compared are case-
sensitive.
– UTF8_GENERAL_CI: applicable to the UTF8 character set. The characters
to be compared are case-insensitive.
– UTF8_UNICODE_CI: applicable to the UTF8 character set. The characters
to be compared are case-insensitive.
– GBK_BIN: applicable to the GBK character set. The characters to be
compared are case-sensitive.
– GBK_CHINESE_CI: applicable to the GBK character set. The characters to
be compared are case-insensitive.
● inline_constraint
Adds a column constraint. It is included in the column definition. Currently,
the NULL, NOT NULL, UNIQUE, PRIMARY KEY, UNIQUE INDEX, FOREIGN KEY,
and CHECK constraints are supported.
● [ NOT ] NULL
Specifies whether a column can hold NULL values.
– NOT NULL: The column cannot hold NULL values.
– NULL: The column can hold NULL values.
● UNIQUE
Specifies that values in a column must be unique. NULL values are allowed.
The UNIQUE constraint can be added to multiple columns in a table.
● PRIMARY KEY
Specifies a primary key including one or more columns that uniquely identify
a row in the table. NULL values are not allowed. Only one primary key can be
created for a table.
● CHECK( expr )
Specifies rules for checking values in a column.
● references_clause
Adds a FOREIGN KEY constraint. schema_name indicates the owner of the
referenced table, and object_table indicates the name of the referenced table.
column_name indicates the referenced column.
If no column is specified for a parent table, the primary key of the parent
table is used by default. If the primary key of the parent table does not exist,
an error will be reported.
● ON DELETE { CASCADE | SET NULL }
Specifies how foreign key values in a child table are handled when primary or
unique values in the parent table are deleted.
– CASCADE
The foreign key values will be deleted.
– SET NULL
The foreign key values will be converted to NULL.
● out_of_line_constraint
Adds a table constraint. It is included as a separate line in the table
definition . Currently, UNIQUE, PRIMARY KEY, and CHECK constraints are
supported.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 419


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● FOREIGN KEY
Specifies a foreign key.
● TABLESPACE tablespace_name
Specifies a tablespace.
● LOCAL
Creates local indexes. It is a default attribute.
● PCTFREE integer
Specifies the percentage of space reserved for a block. If the percentage of
available space of a data block is less than this value, you can only update
data of this block and cannot insert data into it. The value range is [8, 80]
and the default value is 10.
● INITRANS
Specifies the number of transaction slots in an initial data block.
● table_properties
Specifies table attributes.
● AUTO_INCREMENT [=] value
Specifies a start value for an incremental sequence.
If no value is specified, the sequence increments from 1.
● APPENDONLY { ON | OFF }
– APPENDONLY ON indicates that a new page will be used for when
different threads insert data into the same table even though there are
pages that are not full. In this case, the page lock waiting duration is
shortened but the page space is wasted.

▪ If APPENDONLY is set to ON for a partitioned table, properly


arrange the data to be concurrently inserted, ensuring that partition
switchover will not occur (that is, each thread can insert data to only
one partition).

▪ You are not advised to set APPENDONLY to ON for a hash


partitioned table.
– APPENDONLY OFF indicates that data will be inserted into pages that
are not full when different threads insert data into the same table. In this
case, the page lock waiting duration is long.
If this parameter is not specified, the default value OFF is used.
Use APPENDONLY in a partitioned table only when necessary. Improper use
of APPENDONLY will cause serious space waste.
● LOB_storage_clause
– LOB ( LOB_item ) STORE AS { [ ( LOB_parameters ) ]
Specifies that LOB columns are stored in a separate segment. You can
specify inline or out-of-line storage for a table. Currently, only out-of-line
storage is supported.
– LOB_item
Specifies the name of a LOB column.
– LOB_parameters
Specifies storage parameters for a LOB column.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 420


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

{ENABLE | DISABLE } STORAGE IN ROW


Specifies whether to enable inline storage or out-of-line storage.

▪ ENABLE
Inline storage is used.

▪ DISABLE
Out-of-line storage is used.
● range_partitioning
Creates range partitions.
● partition_key
Specifies the list columns contained in a partition key. The length of each
column cannot exceed 2000 bytes.
Partition keys support the following data types:
INT, INTEGER, BIGINT, NUMBER, DECIMAL, REAL, DOUBLE, NUMERIC,
VARCHAR, VARCHAR2, CHAR, BINARY, RAW, VARBINARY, DATE, DATETIME,
and TIMESTAMP
● PARTITION
Specifies a partitioned table.
● partition_name
Specifies the name of a range partition to be created.
● VALUES LESS THAN
Specifies the upper boundary of a range partition.
● partition_value
Specifies the upper boundary of a range partition.
This parameter is mandatory for each partition.
The data type of an upper boundary must be the same as that of the
partition key.
In a partition list, partitions are arranged in ascending order of upper
boundary values. Therefore, a partition with a certain upper boundary value is
placed before another partition with a larger upper boundary value.
● MAXVALUE
Specifies a keyword.
This parameter is used for range partitioning. MAXVALUE specifies the upper
boundary of the last range partition.
In interval partitioning, MAXVALUE cannot be used to specify the upper
boundary of the last range partition.
● list_partitioning
Creates list partitions based on a partitioning key. A partition contains a
maximum of 500 lists.
DEFAULT
Specifies a default partition used for storing default values.
● hash_partitioning
Creates hash partitions. Hash partitions are created on a specified column.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 421


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

STORE IN
Specifies a tablespace for storing hash partitions.
● interval_partitioning
Creates interval partitions.

Examples
● Create the hash partition table employment_history.
-- Delete the employment_history table.
DROP TABLE IF EXISTS employment_history;
-- Create the hash partition table employment_history.
create table employment_history
(
staff_id NUMBER(6),
start_date DATE,
end_date DATE,
employment_id VARCHAR2(10),
section_id NUMBER(4)
) PARTITION BY HASH(start_date) PARTITIONS 2;

● Create the list partition table education.


-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the list partition table education.
CREATE TABLE education(staff_id INT NOT NULL, highest_degree CHAR(8), graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70))
PARTITION BY LIST(highest_degree)
(
PARTITION doctor VALUES ('DOCTOR'),
PARTITION master VALUES ('MASTER'),
PARTITION undergraduate VALUES ('SCHOLAR')
);

● Create the range partition table training.


-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the range partition table training.
CREATE TABLE training(staff_id INT NOT NULL, course_name CHAR(20), course_start_date
DATETIME, course_end_date DATETIME, exam_date DATETIME, score INT)
PARTITION BY RANGE(staff_id)
(
PARTITION training1 VALUES LESS than(100),
PARTITION training2 VALUES LESS than(200),
PARTITION training3 VALUES LESS than(300),
PARTITION training4 VALUES LESS than(MAXVALUE)
);

3.13.28 CREATE USER


Description
CREATE USER creates a database user.

Precautions
● To run this statement, you must have the CREATE USER system permission.
● The user name cannot be the same as an existing user name or role name in
the database. Otherwise, the error message "user *name* already exists" is
displayed.
● When creating a user, you need to specify the user name and password.
● SYS and PUBLIC are preset users and cannot be created.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 422


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– SYS is used to initially create database instances.


– Permissions of user PUBLIC are automatically granted to all users of the
database. For example, if you grant the SELECT permission for the t1
table to user PUBLIC (GRANT SELECT ON user1.t1 TO PUBLIC;), all
users can access the t1 table; if you grant the DBA permission to user
PUBLIC (GRANT DBA TO PUBLIC;), all users have the DBA permission.

Syntax
CREATE USER user_name
IDENTIFIED BY password
[ DEFAULT TABLESPACE tablespace_name
| PASSWORD EXPIRE
| ACCOUNT { LOCK | UNLOCK }
| PROFILE profile_name
| ENCRYPTED
] [ ... ]

Parameter Description
● user_name
Username
– A user name cannot contain spaces or the following special characters:
semicolon (;), vertical line (|), backquote (`), dollar sign ($), bit operator
(&), greater than (>), less than (<), double quotation mark ("), single
quotation mark ('), and exclamation point (!), space, and copyright
symbol (©). In addition, enclosing them in double quotation marks or
backquotes is also forbidden.
– If a user name contains special characters other than the preceding
special characters, enclose the name with double quotation marks ("") or
backquotes (``).
– Since SYSDBA and CLSMGR are database keywords, users with these
names cannot log in to the database. Such users are not recommended.
● IDENTIFIED BY
Specifies a password for the user to be created.
● password
Specifies the password of the user to be created.
The password must comply with the following requirements:
– Contain 8 to 64 characters.
– Start with a letter, number sign (#), or an underscore (_) if the password
is not enclosed in single quotation marks ('').
– Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
– Contain only the following four character types and at least three of
them:

▪ Digits

▪ Lowercase letters

▪ Uppercase letters

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 423


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Spaces or special characters (For details about the list of special


characters supported by GaussDB 100, see the table below.)
– Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
– If the password contains the special character $, use the escape character
\ when connecting to the database through zsql. Otherwise, the login will
fail.
● DEFAULT TABLESPACE tablespace_name
Specifies a default private tablespace for a user.
The specified tablespace must exist.
● PASSWORD EXPIRE
Enables you to manually expire a password. After a password is manually
expired, you are not allowed to log in using this password and the "the
password has expired" message is displayed.
● ACCOUNT { LOCK | UNLOCK }
Enables you to manually lock a user. After a user is locked, you are not
allowed to log in as this user and the "the account is locked" message is
displayed.
● profile_name
Profile name
The profile must be configured in advance. If no profile is specified, the
default profile is referenced by default.
● ENCRYPTED
Specifies that the password is ciphertext. In this case, the password will not be
verified.
Users created in this mode use plaintext passwords for login. Therefore, you
are not advised to specify ENCRYPTED when creating a user.

Table 3-52 Special characters

ID Chara ID Charac ID Charac ID Charact


cter ter ter er

1 ` 9 & 17 \ 25 "

2 ~ 10 * 18 | 26 ,

3 ! 11 ( 19 [ 27 <

4 @ 12 ) 20 { 28 .

5 # 13 - 21 } 29 >

6 $ 14 _ 22 ] 30 /

7 % 15 = 23 : 31 ?

8 ^ 16 + 24 ' - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 424


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
Create user jessica and specify PASSWORD EXPIRE.
CREATE USER jessica IDENTIFIED BY database_123 PASSWORD EXPIRE;

3.13.29 CREATE VIEW

Function
CREATE VIEW creates a view.

A view is a virtual table, not a base table. Only view definition is stored in the
database and view data is not. The data is stored in a base table. If data in the
base table changes, the data queried from the view changes accordingly. In this
sense, a view is like a window through which users can know their interested data
and data changes in the database.

Precautions
To run this statement, you must have the CREATE VIEW or CREATE ANY VIEW
system permission. Common users cannot create objects of system users.

Syntax
CREATE [ OR REPLACE ] VIEW [ schema_name. ]view_name [ ( alias [ ,... ] ) ] AS subquery

Parameter Description
● [OR REPLACE]
Updates a view if the view to be created exists.
● [schema_name.] view_name
Specifies the name of a view to be created.
● [( alias [ ,... ])]
Specifies aliases of columns in a view. If no alias is specified, the column
aliases are automatically derived from the subquery result.
● AS subquery
Specifies a subquery.

Examples
● Create the view privilege_view.
-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege(staff_id INT PRIMARY KEY, privilege_name VARCHAR(64) NOT NULL,
privilege_description VARCHAR(64), privilege_approver VARCHAR(10));
-- Create the view privilege_view.
CREATE OR REPLACE VIEW privilege_view AS SELECT staff_id, privilege_name from privilege;

● Create the view privilege_view with column alias specified.


CREATE OR REPLACE VIEW privilege_view(staff, privilege, description, approver) AS SELECT * FROM
privilege;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 425


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.30 DELETE
Description
DELETE deletes records from a table.

Precautions
● To run this statement, you must have the DELETE permission for the table or
have the DELETE ANY TABLE system permission.
● The commit of the DELETE transaction is disabled by default. Before the
session exits, you need to explicitly commit the transaction. Otherwise, records
will be lost.

Syntax
Delete records from a table.
DELETE FROM [ schema_name. ]table_name
[ WHERE condition ]
[ ORDER BY { column_name [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] } [ , ... ] ]
[ LIMIT [ start, ] count
| LIMIT count OFFSET start
| OFFSET start[ LIMIT count ] ]

Delete records that match those in another table.


DELETE table_ref_list FROM join_table

or
DELETE FROM table_ref_list USING join_table
● table_ref_list:
[ schema_name.]table_name
● join_table:
table_reference [LEFT [OUTER] | RIGHT [OUTER] | INNER ] JOIN table_reference ON conditional_expr
table_reference:
{ [ schema_name. ]table_name [ [AS] alias ]
| [ schema_name. ]view_name [ [AS] alias]
| ( select query ) [ [AS] alias ]
| join_table
}

Parameter Description
● [ schema_name. ]table_name
Specifies the name of a table whose data is to be deleted.
● condition
Specifies the condition for deleting data.
● ORDER BY
Specifies a column based on which a result set is sorted.
● ASC | DESC
Specifies whether the ordering sequence is ascending or descending.
● NULLS FIRST | NULLS LAST
Specifies the position of NULL values in the ORDER BY column. FIRST
indicates that NULL values are placed before non-NULL values and LAST

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 426


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

indicates that NULL values are placed after non-NULL values. If this
parameter is not specified, NULLS LAST is used in ASC mode and NULLS
FIRST is used in DESC mode by default.
● start,count
count specifies the maximum number of rows to return, while start specifies
the number of rows to skip before the first row is returned. When both are
specified, rows specified by start will be skipped before rows specified by
count are returned.
● table_ref_list
Specifies tables whose data is to be deleted. Temporary tables are not
supported in the list.
● table_reference
Specifies a table or view to be queried, or a subquery.
● join_table
Specifies a set of tables for join query.
– LEFT [OUTER] JOIN returns all records from the left table and the
matched records from the right table. The result is NULL from the right
side, if there is no match.
– RIGHT [OUTER] JOIN returns all records from the right table and the
matched records from the left table. The result is NULL from the left side,
when there is no match.
– INNER JOIN returns records that have matching values in both tables.
– conditional_expr
Specifies the conditions for joining two tables.
– table_reference
Specifies tables whose data is to be deleted.
– table_name
Specifies the name of a table whose data is to be deleted.
– view_name
Specifies the name of a view whose data is to be deleted.
– select query
Specifies a subquery whose returned result is to be deleted.

Examples
● Batch delete the records with the same staff_id values from the training and
education tables.
-- Delete the education and training tables.
DROP TABLE IF EXISTS education;
DROP TABLE IF EXISTS training;
-- Create the education and training tables.
CREATE TABLE education(staff_id INT, first_name VARCHAR(20));
CREATE TABLE training(staff_id INT, first_name VARCHAR(20));
-- Insert data.
INSERT INTO education VALUES(1, 'ALICE');
INSERT INTO education VALUES(2, 'BROWN');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(3, 'BOB');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 427


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Batch delete the records with the same staff_id values from the training and education tables.
DELETE training FROM education JOIN training ON education.staff_id = training.staff_id;
Alternatively,
DELETE FROM training USING education JOIN training ON training.staff_id = education.staff_id;

● Delete the INFORMATION SAFETY training record where staff_id=10 from


the training table.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'INFORMATION SAFETY','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',
95);
-- Insert record 3 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'MASTER ALL KINDS OF THINKING METHONDS','2017-07-15 12:00:00','2017-07-20
12:00:00','2017-07-25 12:00:00',97);
-- Delete the INFORMATION SAFETY training record where course_name='INFORMATION SAFETY'
and staff_id=10 from the training table.
DELETE FROM training WHERE course_name='INFORMATION SAFETY' AND staff_id=10;
-- Commit the transaction.
COMMIT;

● Delete all data from the training table.


-- Delete all records from the training table.
DELETE FROM training;
-- Commit the transaction.
COMMIT;

3.13.31 DROP INDEX


Description
DROP INDEX deletes an index.

Precautions
● You can modify your own indexes without additional permissions.
● To delete indexes of other users, the DROP ANY INDEX system permission is
required. Common users cannot delete objects of system users.
● Profiles cannot be created during database restart or rollback.

Syntax
DROP INDEX [ IF EXISTS ] [ schema_name. ]index_name [ ON [schema_name.]table_name ]

Parameter Description
● IF EXISTS
Does not throw an error if the index does not exist.
● [schema_name.] index_name
Specifies the name of an index to be deleted.
● ON [ schema_name. ] table_name
Specifies a table whose index is to be deleted.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 428


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
Delete an index.
DROP INDEX IF EXISTS idx_training;

3.13.32 DROP PROFILE


Description
DROP PROFILE deletes a profile.

Precautions
● To run this statement, you must have the DROP PROFILE system permission.
● If a profile is referenced by a user, the profile cannot be deleted. In this case,
you need to specify CASCADE in the statement to delete the profile.
● If the profile to be deleted does not exist, the deletion fails.
● After the profile referenced by a user is deleted by running the statement with
CASCADE specified, the default profile is automatically referenced by the user.
● The default profile cannot be deleted.
● Profiles cannot be created during database restart or rollback.

Syntax
DROP PROFILE profile_name [ CASCADE ]

Parameter Description
● profile_name
Specifies the name of a profile to be deleted.
● CASCADE
Deletes a profile that has been referenced by a user. If you do not specify
CASCADE for such a profile, this profile will fail to be deleted. After the
profile is deleted, GaussDB 100 assigns DEFAULT PROFILE to the user.

Examples
Delete the pro_common profile.
-- Create the pro_common profile.
CREATE PROFILE pro_common LIMIT PASSWORD_GRACE_TIME 10 PASSWORD_LOCK_TIME DEFAULT
PASSWORD_LIFE_TIME UNLIMITED;
-- Delete the pro_common profile.
DROP PROFILE pro_common CASCADE;

3.13.33 DROP ROLE


Function
DROP ROLE deletes a role from the database.
If the role does not exist, an error message is displayed. After a role is deleted, all
the permissions of this role are revoked from users and other roles.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 429


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● To delete a role by running this statement, you must meet one of the
following conditions: you have the DROP ANY ROLE system permission; you
are the creator of this role; or this role has been granted to you, with WITH
ADMIN OPTION specified.
● The role name must exist. Otherwise, an error will be reported.
● 数据库重启回滚期间不支持该操作。

Syntax
DROP ROLE role_name

Parameter Description
role_name
Specifies the name of a role to be deleted.

Examples
Delete the developers role.
-- Create the developers role.
CREATE ROLE developers;
-- Delete the developers role.
DROP ROLE developers;

3.13.34 DROP SEQUENCE


Description
DROP SEQUENCE deletes a sequence.

Precautions
● You can delete your own sequences without additional permissions.
● To delete sequences of other users, the DROP ANY SEQUENCE system
permission is required. Common users cannot delete objects of system users.
● Profiles cannot be created during database restart or rollback.

Syntax
DROP SEQUENCE [ IF EXISTS ] [ schema_name. ]sequence_name

Parameter Description
● IF EXISTS
Does not throw an error if a sequence to be deleted does not exist.
● [schema_name.] sequence_name
Specifies the name of a sequence to be deleted.

Examples
Delete the seq_auto_extend sequence.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 430


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DROP SEQUENCE IF EXISTS seq_auto_extend;

3.13.35 DROP SQL_MAP

Description
DROP SQL_MAP deletes an SQL mapping.

Precautions
Users do not need system permissions for executing ALTER SQL_MAP.

Syntax
DROP SQL_MAP [ IF EXISTS ] (src_select)

Parameter Description
● IF EXISTS
Specifies that deleting a SQL mapping can succeed even if it does not exist.
● src_select
Specifies a source SQL statement.

Examples
Enable the SQL mapping function.
alter system set enable_sql_map = true;

ALTER SQL_MAP creates a SQL mapping.


ALTER SQL_MAP (select count(*) from SYS_DUMMY) REWRITE TO (select count(1) as cnt from
SYS_DUMMY);

Enter a source SQL statement, which will actually be mapped to the target SQL
statement for execution.
select count(*) from SYS_DUMMY;
CNT
--------------------
1

1 rows fetched.

Delete the SQL mapping.


DROP SQL_MAP (select count(*) from SYS_DUMMY);

Enter the source SQL statement again. No mapping will be performed.


select count(*) from SYS_DUMMY;
COUNT(*)
--------------------
1

1 rows fetched

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 431


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.36 DROP SYNONYM


Description
DROP SYNONYM deletes a synonym.

Precautions
● You can delete synonyms under your own schemas without additional
permissions. To delete synonyms under a schema of other users, the DROP
ANY SYNONYM system permission is required. To delete a public synonym,
the DROP PUBLIC SYNONYM permission is required. Currently, you can
delete only schemas under your own and PUBLIC schemas. Common users
cannot delete objects of system users.
● When deleting a synonym, specify its name. If IF EXISTS is not specified in the
statement, an error will be reported if the synonym to be deleted does not
exist.
● Deleting a synonym has no impact on the associated object of this synonym.
If a user is deleted, all the synonyms of this user are also deleted.
● Profiles cannot be created during database restart or rollback.

Syntax
DROP [ PUBLIC ] SYNONYM [ IF EXISTS ] [ schema_name. ]synonym_name [ FORCE ]

Parameter Description
● PUBLIC
Deletes public synonyms. You can reference information about creating a
synonym.
● [IF EXISTS]
Does not throw an error if the synonym to be deleted does not exist.
● [schema_name.]synonym_name
Specifies the name of a synonym to be deleted. Specify the name by following
the database object naming convention.
● FORCE
Forcibly deletes synonyms.

Examples
● Delete a public synonym pri_vi.
DROP PUBLIC SYNONYM IF EXISTS pri_vi FORCE;

● Delete a private synonym pri_vi.


DROP SYNONYM IF EXISTS pri_vi;

3.13.37 DROP TABLE


Description
DROP TABLE deletes a table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 432


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● You can delete your own tables without additional permissions. To delete
tables of other users, the DROP ANY TABLE system permission is required.
Common users cannot delete objects of system users.
● If the recycle bin is enabled, the table is moved to the recycle bin rather than
being removed immediately from the database after this statement is
executed. In this case, you can run the FLASHBACK statement to roll back the
table.
Tables in the SYSTEM tablespace are immediately removed from the database
rather than being moved to the recycle bin. In addition, such tables cannot be
rolled back by running the FLASHBACK statement.
By default, the recycle bin is enabled in GaussDB 100. If the recycle bin is not
enabled, run the ALTER SYSTEM SET RECYCLEBIN = TRUE statement to
enable it.
● Profiles cannot be created during database restart or rollback.

Syntax
DROP [TEMPORARY] TABLE [ IF EXISTS ] [ schema_name. ]table_name [CASCADE CONSTRAINTS][ PURGE ]

Parameter Description
● TEMPORARY
Deletes a temporary table. The value must be a name of a temporary table.
● IF EXISTS
Does not throw an error if the table to be deleted does not exist.
● [schema_name.]table_name
Specifies the name of a table to be deleted.
● CASCADE CONSTRAINTS
If the table to be deleted is referenced by a foreign key of another table, an
error will be reported when you delete this parent table. In this case, you can
specify CASCADE CONSTRAINTS in the statement to delete the parent table
and the foreign key.
● PURGE
Removes a table from the recycle bin.

Examples
● Delete the privilege table, moving it to the recycle bin.
DROP TABLE IF EXISTS privilege;
● Delete the privilege table, removing it from the recycle bin.
DROP TABLE IF EXISTS privilege PURGE;
● Delete the privilege temporary table, moving it to the recycle bin.
DROP TEMPORARY TABLE privilege;

3.13.38 DROP TABLESPACE


Description
DROP TABLESPACE deletes a tablespace.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 433


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● To run this statement, you must have the DROP TABLESPACE system
permission.
● To delete offline tablespaces, the database must be in the OPEN state.
● The SYSTEM, undo, and temporary tablespaces cannot be deleted.
● In the MOUNT database state, you need to manually delete a tablespace on
the primary and standby nodes because the primary node does not
synchronize the deletion to other nodes.

Syntax
DROP TABLESPACE tablespace_name [ INCLUDING CONTENTS [ { AND | KEEP } DATAFILES ] ]

Parameter Description
● tablespace_name
Tablespace name
● INCLUDING CONTENTS {AND | KEEP} DATAFILES
Specifies whether to delete data files when a tablespace is deleted.
– AND
Deletes data files when a tablespace is deleted.
– KEEP
Does not delete data files when a tablespace is deleted.
● DATAFILES
Specifies data files.

● If this parameter is not specified, an error will be reported when you delete a
tablespace containing objects such as tables, indexes, and LOB or when you delete
the default tablespace.
● If INCLUDING CONTENTS AND DATAFILES is specified, a tablespace is deleted
together with objects in it. However, an error message will be reported when you
delete the default tablespace or a tablespace whose objects are associated with
objects in another tablespace. For example, the foreign key, some partitions, or
index of another tablespace is in the tablespace to be deleted.

Examples
● Delete a tablespace and its data files in the OPEN database state.
-- Create the human_space3 tablespace in the OPEN database state.
CREATE TABLESPACE human_space3 DATAFILE 'human_dfile3' SIZE 32M AUTOEXTEND ON NEXT 10M;
-- Delete the human_space3 tablespace and its data files in the OPEN database state.
DROP TABLESPACE human_space3 INCLUDING CONTENTS AND DATAFILES;

● Delete a tablespace and retain its data files in the OPEN database state.
-- Create the human_space4 tablespace in the OPEN database state.
CREATE TABLESPACE human_space4 DATAFILE 'human_dfile4' SIZE 32M;
-- Delete the human_space4 tablespace and retain its data files in the OPEN database state.
DROP TABLESPACE human_space4 INCLUDING CONTENTS KEEP DATAFILES;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 434


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.39 DROP USER

Description
DROP USER deletes an existing database user.

Precautions
● To run this statement, you must have the DROP USER system permission.
● If the specified user does not exist and if exists is not specified, the following
error message is displayed: "user name does not exist".
● Profiles cannot be created during database restart or rollback.
● A user has a maximum of 50,000 objects. Before deleting a user, you are
advised to delete objects of the user first.
● Perform DROP USER only when absolutely necessary. Deleted objects cannot
be restored even if the execution of DROP USER is interrupted.

Syntax
DROP USER [ if exists ] user_name [ CASCADE ]

Parameter Description
● user_name
Specifies the name of a user to be deleted.
● if exists
Does not throw an error if the user to be deleted does not exist. If the
specified user does not exist, the system returns a message indicating that the
operation is successful. If the user exists, the system deletes the user.
● CASCADE
– If CASCADE is not specified and a user has database objects that are not
deleted, the following error message is displayed when the user is
deleted:
GS-00815, user objects is being used, can not drop

– If CASCADE is specified, the database objects of a user are forcibly


deleted when the user is deleted, such as tables, indexes, constraints
(including foreign keys that reference the tables), triggers, sequences,
views (excluding objects of other users referenced in the views), functions
or stored procedures, and tables in the recycle bin.

Examples
Delete user zwx003 and forcibly delete the database objects of this user.
-- Create user zwx003 with the password database_123 specified.
CREATE USER zwx003 IDENTIFIED BY database_123;
-- Delete user zwx003 and forcibly delete the database objects of this user.
DROP USER zwx003 CASCADE;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 435


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.40 DROP VIEW


Function
DROP VIEW deletes a view.

Precautions
● 用户能删除自己的视图,删除其他用户的视图,需要DROP ANY VIEW权限,普通
用户不可以删除系统用户对象。
● 数据库重启回滚期间不支持该操作。

Syntax
DROP VIEW [ IF EXISTS ] [ schema_name. ]view_name

Parameter Description
● IF EXISTS
Does not throw an error if the view to be deleted does not exist.
● [schema_name.] view_name
Specifies the name of a view to be deleted.

Examples
Delete the privilege_view view.
-- Delete the privilege table.
DROP TABLE IF EXISTS privilege;
-- Create the privilege table.
CREATE TABLE privilege(staff_id INT PRIMARY KEY, privilege_name VARCHAR(64) NOT NULL,
privilege_description VARCHAR(64), privilege_approver VARCHAR(10));
-- Create the privilege_view view.
CREATE OR REPLACE VIEW privilege_view AS SELECT staff_id, privilege_name from privilege;
-- Delete the privilege_view view.
DROP VIEW IF EXISTS privilige_view;

3.13.41 EXPLAIN PLAN


Function
EXPLAIN PLAN displays the execution plan of a DML SQL statement to help
analyze whether the plan is optimal.

Precautions
EXPLAIN displays only DML execution plans.

Syntax
EXPLAIN [ PLAN FOR ] statement

Parameter Description
● PLAN FOR

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 436


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

This parameter is optional. It is used to enhance the statement readability.


● statement
Specifies the SQL statement to explain.

Examples
View a DML execution plan.
-- Delete the posts table.
DROP TABLE IF EXISTS posts;
-- Create the posts table.
CREATE TABLE posts(post_id CHAR(2) NOT NULL, post_name CHAR(16) NOT NULL, basic_wage INT,
basic_bonus INT);
-- Insert record 1 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('A','GENERAL MANAGER',
50000,5000);
-- Insert record 2 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('B','PROJECT MANAGER',
10000,5000);
-- Insert record 3 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('C','STAFF',3000,1000);
-- Commit the transaction.
COMMIT;
-- View the execution plan.
EXPLAIN SELECT * FROM posts WHERE post_id='A';

3.13.42 FLASHBACK TABLE

Description
FLASHBACK TABLE restores an earlier state of a table in the event of human or
application error.

The time in the past to which the table can be flashed back is dependent on the
amount of undo data in the system. In addition, GaussDB 100 cannot restore a
table to an earlier status across any DDL operations that change the structure of
the table.

Precautions
● To run this statement, you must have the FLASHBACK permission. To flash
back tables of other users, the FLASH ANY TABLE permission is required.
● You can flash back tables from the undo data or recycle bin.
– The undo data records the new and updated data objects. TO SCN expr
and TO TIMESTAMP expr flash back objects from undo data.
– The recycle bin records the objects deleted by DROP. TO BEFORE DROP
flashes back objects from the recycle bin.
● By default, GaussDB 100 does not forcibly convert the DATE type and this
type needs to be converted by using functions.
● Profiles cannot be created during database restart or rollback.

Syntax
FLASHBACK TABLE [ schema_name. ]table_name TO { SCN expr | TIMESTAMP expr | BEFORE { DROP
[ RENAME TO table_name ] | TRUNCATE FORCE } }

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 437


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Parameter Description
● schema_name
Specifies a schema containing the table to be flashed back. If this parameter
is not specified, the current schema is used.
● table_name
Specifies one or more tables to be flashed back.
This statement is subject to the following restrictions:
– Table flashback is invalid for the following objects: materialized views,
system catalogs, foreign tables, or individual table partitions or
subpartitions.
– The following DDL operations change the table structure. Therefore, do
not use TO SCN or TO TIMESTAMP for flashback.

▪ Upgrade, move, or truncate tables.

▪ Add table constraints or tables; delete or modify columns; change


the encryption key of a column.

▪ Add, delete, merge, split, combine, or truncate partitions or


subpartitions (except adding a range partition).
● TO SCN
Specifies the system change number (SCN) corresponding to the point in time
to which you want to return the table. expr must evaluate to a number
representing a valid SCN.
● expr
Specifies a valid SCN.
● TO TIMESTAMP
Specifies a timestamp value corresponding to the point in time to which you
want to return the table. The result of expr must be a valid past timestamp
(convert a string to a time type using the TO_TIMESTAMP function). The
table will be flashed back to a time within approximately 3 seconds of the
specified timestamp.
Note: The specified time point must be earlier than the table creation time.
Otherwise, an error is reported.
● TO BEFORE DROP
Retrieves from the recycle bin a table that has been deleted, along with all
possible dependent objects. The table must have resided in a locally managed
tablespace other than the SYSTEM tablespace.
You can specify either the original user-specified name of the table or the
system-generated name assigned to the object when it was deleted.
– System-generated recycle bin object names are unique. Therefore, if you
specify the system-generated name, the database retrieves that specified
object. To see the contents of your recycle bin, run select * from
SYS_RECYCLEBIN;.
– If you specify the user-specified name and the recycle bin contains more
than one object of that name, the database retrieves the object that was
moved to the recycle bin most recently. If you want to retrieve an older
version of the table, then do one of these things:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 438


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Specify the system-generated recycle bin name of the table you want
to retrieve.

▪ Run FLASHBACK TABLE ... TO BEFORE DROP statements until you


retrieve the table you want.
● RENAME TO
Specifies a new name for the table being retrieved from the recycle bin.
● TRUNCATE FORCE
Flashes back to the point in time before the TRUNCATE operation.

Examples
-- Create the human_bonus tablespace.
CREATE TABLESPACE human_bonus DATAFILE 'bonus2018' SIZE 32M;
-- Delete the bonus_2018 table.
DROP TABLE IF EXISTS bonus_2018;
-- Create the bonus_2018 table.
CREATE TABLE bonus_2018(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER) TABLESPACE human_bonus;
-- Insert record 1 into the bonus_2018 table.
INSERT INTO bonus_2018(staff_id, staff_name, job, bonus) VALUES(20,'LIMING','developer',5000);
-- Insert record 2 into the bonus_2018 table.
INSERT INTO bonus_2018(staff_id, staff_name, job, bonus) VALUES(21,'LIYU','tester',7000);
-- Insert record 3 into the bonus_2018 table.
INSERT INTO bonus_2018(staff_id, staff_name, job, bonus) VALUES(22,'WANGQIMING','developer',8000);
-- Commit the transaction.
COMMIT;
-- Delete data from the bonus_2018 table.
TRUNCATE TABLE bonus_2018;
-- Flash back to one minute ago (the time point must be one minute ago or earlier than the time when the
table was created. Otherwise, an error is reported).
FLASHBACK TABLE bonus_2018 TO TIMESTAMP SYSTIMESTAMP-1/1440;
-- Query data in the bonus_2018 table.
SELECT * FROM bonus_2018;
-- Delete the bonus_2018 table.
DROP TABLE IF EXISTS bonus_2018;
-- Query data in the bonus_2018 table.
SELECT * FROM bonus_2018;
-- Flash back the bonus_2018 table to the time point before the DROP operation.
FLASHBACK TABLE bonus_2018 TO BEFORE DROP;
-- Query data in the bonus_2018 table.
SELECT * FROM bonus_2018;

3.13.43 GRANT

Description
GRANT grants system permissions or roles to users or other roles.

SYS permissions not granted to a user or roles of the user cannot be granted to
other users or roles by the user.

Precautions
● To grant a system permission, you must meet one of the following
requirements:
– This system permission has been granted to you, with WITH ADMIN
OPTION specified.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 439


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– You have the GRANT ANY PRIVILEGE system permission.


● To grant a role, you must meet one of the following requirements:
– This role has been granted to you, with WITH ADMIN OPTION specified.
– You have the GRANT ANY ROLE system permission.
– You are the creator of this role.
● When you grant the permissions for your own objects to other users, the
GRANT-related permissions are not required.

Syntax
GRANT { ALL [ PRIVILEGES ]
|{ system_privilege_name | role_name } [ , ... ] } TO grantee [ WITH ADMIN OPTION ]

● grantee:
{ user_name | role_name } [ , ... ] }
GRANT { object_privilege_name | ALL [PRIVILEGES] } [, ...] ON [schema_name.]object_name TO grantee
[ WITH GRANT OPTION ]

● object_privilege_name:
{ SELECT | UPDATE | DELETE | INSERT | ALTER | INDEX | EXECUTE | READ | REFERENCES } [, ... ]

● grantee:
{ user_name | role_name } [ , ... ]

Parameter Description
● system_priviege_name
Specifies a system permission to be granted. The following table lists the
supported roles and system permissions. Y indicates that a role or user has
the permission, and - indicates that a role or user does not have the
permission.

Table 3-53 System permission matrix


System Permission Whether the Whether
Role Has This the User
Permission Has This
Permission

Operat Required Permission DB RES CO SYS PUB


ion Permission Description A OU NN LIC
Type RC ECT
E

Creatin CREATE To create a Y - Y Y -


ga SESSION session for
connec connecting to
tion the database,
you must have
the CREATE
SESSION
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 440


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin CREATE USER To create a user, Y - - Y -


ga you must have
user the CREATE
USER
permission.

Creatin CREATE ROLE To create a role, Y - - Y -


ga you must have
role the CREATE
ROLE
permission.

Creatin CREATE To create a Y - - Y -


ga TABLESPACE tablespace, you
tablesp must have the
ace CREATE
TABLESPACE
permission.

Creatin CREATE To create a table Y Y - Y -


ga TABLE in your own
table schema, you
CREATE ANY must have either -
TABLE of the CREATE
TABLE or
CREATE ANY
TABLE
permission. To
create a table in
other schemas,
you must have
the CREATE
ANY TABLE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 441


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin CREATE ANY To create an Y - - Y -


g an INDEX index in your
index own schema,
either of the
following
conditions must
be met:
● The to-be-
indexed table
is in the
schema.
● You have the
CREATE ANY
INDEX
permission.
To create an
index in other
schemas, you
must have
the CREATE
ANY INDEX
permission.

Creatin CREATE To create a Y Y - Y -


ga SEQUENCE sequence in your
sequen own schema,
ce CREATE ANY either of the -
SEQUENCE following
conditions must
be met:
● You have the
CREATE
SEQUENCE
permission.
● You have the
CREATE ANY
SEQUENCE
permission.
To create a
sequence in
other
schemas, you
must have
the CREATE
ANY
SEQUENCE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 442


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin CREATE VIEW To create a view Y - - Y -


ga CREATE ANY in your own
view VIEW schema, either
of the following
conditions must
be met:
● You have the
CREATE
VIEW
permission.
● You have the
CREATE ANY
VIEW
permission.
To create a
view in other
schemas, you
must have
the CREATE
ANY VIEW
permission.

Creatin CREATE Currently, only Y - - Y -


ga DATABASE user SYS can
databa create one
se database in the
NOMOUNT
database state.
Other users are
not allowed to
create a
database.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 443


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin CREATE ● To create a Y - - Y -


ga SYNONYM synonym in
synony CREATE ANY your own
m SYNONYM schema, you
must have
CREATE any of the
PUBLIC three
SYNONYM permissions.
● To create a
synonym in a
schema of
other users,
you must
have the
CREATE_ANY
SYNONYM
permission.
● To create a
public
synonym, you
must have
the CREATE
PUBLIC
permission.
SYNONYM
permission

Creatin CREATE ● To create a Y Y - Y -


ga PROCEDURE function or
functio stored
n or CREATE ANY procedure in -
stored PROCEDURE your own
proced schema, you
ure can use either
of the
permissions.
● To create a
function or
stored
procedure in
a schema of
other users,
you must
have the
CREATE_ANY
PROCEDURE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 444


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Deletin DROP USER To delete a user, Y - - Y -


ga you must have
user the DROP USER
permission.

Deletin DROP To delete a Y - - Y -


ga TABLESPACE tablespace, you
tablesp must have the
ace DROP
TABLESPACE
permission.

Deletin DROP ANY To delete a table Y - - Y -


ga TABLE from your own
table schema, no
additional
permissions are
required. To
delete a table
from a schema
of other users,
you must have
the DROP ANY
TABLE
permission.

Deletin DROP ANY To delete an Y - - Y -


g an INDEX index from your
index own schema, no
additional
permissions are
required. To
delete an index
from a schema
of other users,
you must have
the DROP ANY
INDEX
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 445


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Deletin DROP ANY To delete a Y - - Y -


ga SEQUENCE sequence from
sequen your own
ce schema, no
additional
permissions are
required. To
delete a
sequence from a
schema of other
users, you must
have the DROP
ANY SEQUENCE
permission.

Deletin DROP ANY To delete a view Y - - Y -


ga VIEW from your own
view schema, no
additional
permissions are
required. To
delete a view
from a schema
of other users,
you must have
the DROP ANY
VIEW
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 446


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Deletin DROP ANY To delete a Y - - Y -


ga SYNONYM synonym from
synony DROP PUBLIC your own
m SYNONYM schema, no
additional
permissions are
required. To
delete a
synonym from a
schema of other
users, you must
have the DROP
ANY SYNONYM
permission. To
delete a public
synonym, you
must have the
DROP PUBLIC
SYNONYM.
Currently, only
public synonyms
can be deleted
from the system.

Deletin DROP ANY To delete a role Y - - Y -


ga ROLE from your own
role schema, no
additional
permissions are
required. To
delete a role
from other
schemas, this
role must have
been granted to
you, with WITH
GRANT OPTION
specified, or you
have the DROP
ANY ROLE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 447


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Lockin LOCK ANY To lock a table Y - - Y -


ga TABLE or view in your
table own schema, no
additional
permissions are
required. To lock
a table or view
in a schema of
other users, you
must have the
LOCK ANY
TABLE
permission.

Clearin DROP ANY To delete all Y - - Y -


ga TABLE records from a
table table, run the
TRUNCATE
TABLE
statement. To
clear a table in
your own
schema, no
additional
permissions are
required. To
clear a table in a
schema of other
users, you must
have the DROP
ANY TABLE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 448


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Flashin FLASHBACK To flash back a Y - - Y -


g back ANY TABLE table in your
a table own schema,
you must have
the permissions
same as those
required for
deleting tables.
To flash back a
table in a
schema of other
users, you must
have the
FLASHBACK
ANY TABLE
permission.
Different
additional
requirements are
required based
on where data is
flashed back
from (SCN,
TIMESTAMP,
BEFORE).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 449


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Removi DROP ANY You can purge Y - - Y -


ng TABLE tables (PURGE
objects DROP ANY TABLE), indexes
INDEX (PURGE INDEX),
tablespaces
DROP (PURGE
TABLESPACE TABLESPACE),
PURGE and recycle bins
DBA_RECYCLE (PURGE
BIN RECYCLEBIN).
To purge an
object (table or
index) in your
own schema, no
additional
permissions are
required. To
purge an object
in a schema of
other users, you
must have the
required
permissions: to
purge a table,
you must have
the DROP ANY
TABLE
permission; to
purge an index,
you must have
the DROP ANY
INDEX
permission; to
purge a recycle
bin, you must
have the PURGE
DBA_RECYCLEBI
N permission; to
purge a
tablespace, you
must have the
DROP
TABLESPACE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 450


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Deletin DROP ANY To delete a Y - - Y -


ga PROCEDURE function or
functio stored procedure
n or from your own
stored schema, no
proced additional
ure permissions are
required.
To delete a
function or
stored procedure
from a schema
of other users,
you must have
the DROP ANY
PROCEDURE
permission.

Modify ALTER If all the Y - - Y -


ing SESSION parameters are
session related to the
param current session,
eters you can modify
these
parameters
without
additional
permissions. The
ALTER SESSION
permission is
reserved.

Modify ALTER To modify a Y - - Y -


ing a TABLESPACE tablespace, you
tablesp must have the
ace ALTER
TABLESPACE
permission.

Modify ALTER To modify Y - - Y -


ing SYSTEM system
system parameters, you
param must have the
eters ALTER SYSTEM
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 451


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Modify ALTER To modify a Y - - Y -


ing a DATABASE database, you
databa must have the
se ALTER
DATABASE
permission.

Modify ALTER USER To modify a user, Y - - Y -


ing a you must have
user the ALTER USER
permission. A
common user
can change only
their own
passwords
regardless of
whether they
have this
permission. A
user with the
DBA role cannot
change the
password of
other users with
the DBA role
even if being
granted with this
permission.

Modify ALTER ANY To modify a Y - - Y -


ing a TABLE table in your
table own schema, no
additional
permissions are
required. To
modify a table in
a schema of
other users, you
must have the
object
permission for
this table or
have the ALTER
ANY TABLE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 452


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Modify ALTER ANY To modify an Y - - Y -


ing an INDEX index in your
index own schema, no
additional
permissions are
required.
To modify an
index in a
schema of other
users, you must
have the ALTER
ANY INDEX
permission.

Modify ALTER ANY To modify a Y - - Y -


ing a SEQUENCE sequence in your
sequen own schema, no
ce additional
permissions are
required. To
modify a
sequence in a
schema of other
users, you must
have the object
permission for
this sequence or
have the ALTER
ANY SEQUENCE
permission.

Queryi SELECT ANY To query a Y - - Y -


ng a SEQUENCE sequence in your
sequen own schema, no
ce additional
permissions are
required.
To query a
sequence in a
schema of other
users, you must
have the object
permission for
this sequence or
have the SELECT
ANY SEQUENCE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 453


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Granti GRANT ANY To grant a Y - - Y -


ng PRIVILEGE system
permis GRANT ANY permission, you
sions ROLE must meet one
of the following
GRANT ANY requirements:
OBJECT
PRIVILEGE ● This system
permission
has been
granted to
you, with
WITH
ADMIN
OPTION
specified.
● You have the
GRANT ANY
PRIVILEGE
system
permission.
To grant a role,
you must meet
one of the
following
requirements:
● This role has
been granted
to you, with
WITH
ADMIN
OPTION
specified.
● You have the
GRANT ANY
ROLE system
permission.
● You are the
creator of this
role.
A user who has
the GRANT ANY
OBJECT
PRIVILEGE
system
permission can
grant

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 454


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

permissions for
objects of any
user to other
users.

Revoki GRANT ANY To revoke a Y - - Y -


ng a PRIVILEGE system
permis GRANT ANY permission, you
sion ROLE must meet one
of the following
requirements:
● This system
permission
has been
granted to
you, with
WITH
ADMIN
OPTION
specified.
● You have the
GRANT ANY
PRIVILEGE
system
permission.
To revoke a role,
you must meet
one of the
following
requirements:
● This role has
been granted
to you, with
WITH
ADMIN
OPTION
specified.
● You have the
GRANT ANY
ROLE system
permission.
● You are the
creator of this
role.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 455


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Modify ALTER To modify a Y - - Y -


ing a PROFILE profile, you must
profile have the ALTER
PROFILE
permission.

Creatin CREATE To create a Y - - Y -


ga PROFILE profile, you must
profile have the
CREATE
PROFILE
permission.

Deletin DROP To delete a Y - - Y -


ga PROFILE profile, you must
profile have the DROP
PROFILE
permission.

Readin READ ANY A user with Y - - Y -


g any TABLE either of the
table SELECT ANY permissions can
or view TABLE query data in
data any table or
view. If the FOR
UPDATE clause
is included, only
users with the
SELECT ANY
TABLE
permission can
query the data.

Adding COMMENT To add Y - - Y -


comme ANY TABLE comments on
nts your own table,
no additional
permissions are
required. To add
comments on a
table of other
users, you must
have the
COMMENT ANY
TABLE
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 456


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Updati UPDATE ANY A user with this Y - - Y -


ng TABLE permission can
table update data in
data any user table.

Inserti INSERT ANY A user with this Y - - Y -


ng TABLE permission can
data insert data into
any user table.

Deletin DELETE ANY A user with this Y - - Y -


g table TABLE permission can
data delete data from
any user table.

Backup SYSBACKUP To perform Y - - Y -


SYSDBA backup, you
must have the
SYSBACKUP or
SYSDBA
permission.

Restor SYSDBA To perform Y - - Y -


ation restoration, you
must have the
SYSDBA
permission.

Stoppi SYSDBA To stop a Y - - Y -


ng a database, you
databa must have the
se SYSDBA
permission.

Rebuil SYSDBA To rebuild a Y - - Y -


da standby server,
standb you must have
y the SYSDBA
server permission.

Verifyi SYSDBA To verify the Y - - Y -


ng the validity of a
validity physical backup
of a set, you must
physica have the
l SYSDBA
backup permission.
set

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 457


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Analyzi ANALYZE ANY To analyze your Y - - Y -


ng a own table, no
table additional
permissions are
required. To
analyze a table
of other users
(except SYS),
you must have
the ANALYZE
ANY permission.
To analyze a
table of SYS, you
must have the
DBA
permissions.

Modify ALTER ANY To modify your Y - - Y -


ing a TRIGGER own trigger, no
trigger additional
permissions are
required. To
modify a trigger
defined by other
users, you must
have the ALTER
ANY TRIGGER
permission.

Creatin CREATE To create your Y Y - Y -


ga TRIGGER own trigger, you
trigger must have the
CREATE ANY CREATE -
TRIGGER TRIGGER
permission.
To create a
trigger for other
users, you must
have the
CREATE ANY
TRIGGER
permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 458


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Deletin DROP ANY To delete your Y - - Y -


ga TRIGGER own trigger, no
trigger additional
permissions are
required.
To delete a
trigger of other
users, you must
have the DROP
ANY TRIGGER
permission.

Executi EXECUTE ANY To execute your Y - - Y -


ng a PROCEDURE own stored
stored procedure, no
proced additional
ure permissions are
required.
To execute a
stored procedure
of other users,
you must have
the object
permission for
this stored
procedure or
have the
EXECUTE ANY
PROCEDURE
system
permission.

Modify ALTER ANY Reserved Y - - Y -


ing a PROCEDURE permission
stored
proced
ure

Modify ALTER ANY Reserved Y - - Y -


ing a MATERIALIZE permission
materi D VIEW
alized
view

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 459


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin CREATE ANY Reserved Y - - Y -


ga MATERIALIZE permission
materi D VIEW
alized CREATE
view MATERIALIZE
D VIEW

Deletin DROP ANY Reserved Y - - Y -


ga MATERIALIZE permission
materi D VIEW
alized
view

Modify ALTER ANY Reserved Y - - Y -


ing a ROLE permission
role

Creatin CREATE Reserved Y - - Y -


ga DISTRIBUTE permission
distrib RULE
ution
rule

Archivi FLASHBACK Reserved Y - - Y -


ng ARCHIVE permission
flashba ADMINISTER
ck

Rewriti GLOBAL Reserved Y - - Y -


ng a QUERY permission
global REWRITE
query

Manag MANAGE Reserved Y - - Y -


ing TABLESPACE permission
tablesp
aces

Refresh ON COMMIT Reserved Y - - Y -


ing a REFRESH permission
materi
alized
view

Using UNLIMITED Reserved Y - - Y -


an TABLESPACE permission
unlimit
ed
tablesp
ace

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 460


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

System Permission Whether the Whether


Role Has This the User
Permission Has This
Permission

Creatin UNDER ANY Reserved Y - - Y -


ga VIEW permission
view

Perfor SYSOPER Reserved Y - - Y -


ming permission
operati
ons as
a
system
operat
or

Creatin CREATE This is a reserved Y - - Y -


ga NODE permission. To
node create a cluster
node, you must
have the
CREATE NODE
permission.

Deletin DROP NODE This is a reserved Y - - Y -


ga permission and
node is required when
you delete a
node from a
cluster.

Modify ALTER NODE This is a reserved Y - - Y -


ing a permission and
node is required for
modifying a
node in a cluster.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 461


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

User SYS has all the permissions in the table.


● Permissions for synonyms: The permissions for a synonym are the same as those for the
object that the synonym represents. That is, if a permission for a synonym is granted to
a user, this user will also have this permission for the object that the synonym
represents. Similarly, if a permission for an object is granted to a user, this user will also
have this permission for the synonym (if any) of the object. When accessing a synonym,
the system checks whether the user has the permission for the object represented by the
synonym.
● Permission granting through roles:
● If a role is granted to a user/role, the user/role will have all the permissions of the
role (including system permissions and object permissions).
● If a role is removed from a user/role, all the permissions of the role will be
removed from the user/role. If a user/role has a permission and inherits the same
permission from another role. After the role is removed, the user/role still has the
permission.
● Deleting an object
● If a table, view, sequence, or stored procedure is deleted, the permissions for these
objects will be removed from users and roles.
● Deleting a user or a role
● If a user is deleted, all objects of the user are deleted. In addition, the permissions
for these objects granted to other users, and the permissions granted by the user
to other users and roles are also removed.
● If a role is deleted, all permissions granted to the role are removed. In addition, this
role is removed from users and other roles.
● Permission requirements for creating and accessing a view:
● To create a view, you must have the CREATE VIEW (create your own view) or
CREATE ANY VIEW (create a view for other users) permission. The owner (current
user or other users) of the view must have the SELECT or READ permission for the
objects accessed in the view.
● To access a view, you must have the SELECT, SELECT ANY TABLE, READ, or READ
ANY TABLE permission for the view. The owner (current user or other users) of the
view must have the SELECT or READ permission for the objects accessed in the
view.
● Permission requirements for objects that depend on a stored procedure, UDF, or trigger
● When you create a stored procedure, UDF, or trigger, the system does not check
whether you have the permissions for their dependers.
● When you execute a stored procedure, invoke a UDF, or execute a trigger, the
system checks whether you have the permission to access their dependers.
● When you create a trigger on a table of another user, you must have the CREATE
ANY TRIGGER permission.
● Rule for checking object permissions: All objects have all the permissions of the object.
● SELECT: To query your own object, no additional permissions are required. To
query an object of other users, you must have the SELECT object permission for
the object or have the SELECT ANY TABLE system permission.
● UPDATE: To update your own object, no additional permissions are required. To
update an object of other users, you must have the UPDATE object permission for
the object or have the UPDATE ANY TABLE system permission.
● DELETE: To delete your own object, no additional permissions are required. To
delete an object of other users, you must have the DELETE object permission for
the object or have the DELETE ANY TABLE system permission.
● INSERT: To insert data to your own object, no additional permissions are required.
To insert data to an object of other users, you must have the INSERT object
permission for the object or have the INSERT ANY TABLE system permission.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 462


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● ALTER: To modify your own object, no additional permissions are required. To


modify an object of other users, you must have the ALTER object permission for
the object or have the ALTER ANY { TABLE | SEQUENCE } system permission.
● INDEX: To create an index on an object, you must have the INDEX permission for
the object.
● EXECUTE: To execute a stored procedure or invoke a UDF or system package
function, you must have the EXECUTE permission for the object. Currently, the
system packages include DBMS_UTILITY, DBMS_STATS, DBMS_STANDARD,
DBMS_SQL, DBMS_RANDOM, DBMS_RAFT, DBMS_OUTPUT, DBMS_LOB, and
DBMS_JOB. By default, system administrators and DBA have the permission to
execute all advanced packages. To invoke the DBMS_JOB package as a common
user, you must be granted with the EXECUTE permission by a system administrator.
By default, all users have the permission to invoke the other system packages.
● READ: This permission is used to access an object. The permission is similar to the
SELECT permission, except that the SELECT not READ permission is required if the
FOR UPDATE clause is used. In other cases, the SELECT is the same as READ.
● REFERENCES: To create a foreign key, you must have the REFERENCES permission
for the referenced object.
● If you are not user SYS, do not create objects in the schema of user SYS or operate
objects of user SYS even if you have the following permissions. You can operate an
object of user SYS only after user SYS grants the permission for this object to you.
CREATE ANY TABLE
CREATE ANY INDEX
CREATE ANY SEQUENCE
CREATE ANY VIEW
CREATE ANY SYNONYM
CREATE ANY PROCEDURE
DROP ANY TABLE
DROP ANY INDEX
DROP ANY SEQUENCE
DROP ANY VIEW
DROP ANY SYNONYM
LOCK ANY TABLE
DROP ANY TABLE
DROP ANY PROCEDURE
ALTER ANY TABLE
ALTER ANY INDEX
ALTER ANY SEQUENCE
UPDATE ANY TABLE
INSERT ANY TABLE
DELETE ANY TABLE
ANALYZE ANY
ALTER ANY TRIGGER
CREATE ANY TRIGGER
DROP ANY TRIGGER
EXECUTE ANY PROCEDURE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 463


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

NOTICE

The following operations have great impact on the system. Perform them only
when absolutely necessary.
CREATE ANY TABLE
CREATE ANY INDEX
CREATE ANY SEQUENCE
CREATE ANY VIEW
CREATE ANY SYNONYM
CREATE ANY PROCEDURE
DROP ANY TABLE
DROP ANY INDEX
DROP ANY SEQUENCE
DROP ANY VIEW
DROP ANY SYNONYM
LOCK ANY TABLE
DROP ANY TABLE
DROP ANY PROCEDURE
ALTER ANY TABLE
ALTER ANY INDEX
ALTER ANY SEQUENCE
UPDATE ANY TABLE
INSERT ANY TABLE
DELETE ANY TABLE
ANALYZE ANY
ALTER ANY TRIGGER
CREATE ANY TRIGGER
DROP ANY TRIGGER
EXECUTE ANY PROCEDURE

● role_name
Specifies a role name. For details, see the description about the ROLE
statement. If a role is granted to a user/role, the user/role will have all the
system permissions of the role. Role granting in a circle is not allowed. For
example, grant role1 to role2, role2 to role3, and finally role3 to role1.
There are four default roles in the system: DBA, RESOURCE, CONNECT, and
STATISTICS. For details about permissions of the roles, see Data Dictionary
and Views > User Views > ROLE_SYS_PRIVS in GaussDB 100 V300R001C00
Database Reference. The DBA role has all system permissions. Grant the DBA
role to a common user only when absolutely necessary.
● ALL [ PRIVILEGES ]
Specifies all system permissions. PRIVILEGES can be omitted.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 464


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● [ schema_name. ]
Specifies a user name. If this parameter is not specified, the current login user
is used by default.
● WITH ADMIN OPTION
If WITH ADMIN OPTION is specified in the statement, then:
– grantee has the permission to grant the system permission or role to
other users or roles (that is, transfer the grant permission). If a
permission is revoked, the permission to grant this permission to other
users is not revoked.
– grantee has the permission to revoke system permissions or roles from
itself.
– Once being specified, WITH ADMIN OPTION can be revoked only by
running the REVOKE statement. If WITH ADMIN OPTION is revoked, the
permissions in the same statement as WITH ADMIN OPTION are also
revoked.
● object_privilege_name: Specifies an object permission name. Each object has
an independent permission set. Currently, the following object types are
supported: tables, views, sequences, stored procedures, functions, triggers, and
advanced system packages.
The following table lists the objects and object permissions. Y indicates that
an object permission is supported; - indicates that an object permission is not
supported; Reserved indicates a reserved object permission. An owner has all
permissions for its objects. System administrators (user SYS and role DBA)
have all the object permissions in the table.

Table 3-54 Object permission matrix

Object Whether This Object Permission Is Supported


Type
SELE UPD INSE DELE INDE REA REFE ALTE EXEC
CT ATE RT TE X D REN R UTE
CES

Table Y Y Y Y Y Y Y Y -

View Y Rese Rese Rese - Y Rese - -


rved rved rved rved

Sequence Y - - - - - - Y -

Stored - - - - - - - - Y
procedur
e

Trigger - - - - - - - - -

Function - - - - - - - - Y

Advance - - - - - - - - Y
d system
package

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 465


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– When the GRANT ALL PRIVILEGES command is used to grant the


permission of an object to a user, the system determines the permission
set to be granted or reclaimed based on the object type.
– When the object permission is granted to the PUBLIC user, all users in the
system have the rights granted to the object, including the users added
after the authorization operation. Before pressing this button, ensure that
the OS has the NMI processing program. Otherwise, the OS may crash.
● ALL [ PRIVILEGES ]
Specifies all permissions for an object. PRIVILEGES can be omitted.
● grantee
Specifies a grantee. The grantee can be a user or a role. A maximum of 63
users or roles can be specified at a time. If grantee is set to PUBLIC, the
specified permission is granted to all users, including new users added after
the permission granting. Therefore, set grantee to PUBLIC only when
absolutely necessary.
● WITH GRANT OPTION
– If WITH GRANT OPTION is specified for a user, the user can grant the
obtained permissions to other users or roles, and the permission
cancellation is cascaded.
– Once being specified, WITH ADMIN OPTION can be revoked only by
running the REVOKE statement. If WITH ADMIN OPTION is revoked, the
permissions in the same statement as WITH ADMIN OPTION are also
revoked.

Examples
● Create user joe and grant the CREATE SESSION permission to joe.
-- Delete user joe.
DROP USER joe CASCADE;
-- Create user joe with the password database_123 specified.
CREATE USER joe IDENTIFIED BY database_123;
-- Grant the CREATE SESSION permission to user joe.
GRANT CREATE SESSION TO joe;

● Create user jim, user glow, and role testers, and grant the testers role to
users jim and glow.
-- Delete the testers role.
DROP ROLE testers;
-- Create the testers role.
CREATE ROLE testers;
-- Grant the permissions CREATE SESSION, CREATE USER, CREATE ROLE, and CREATE TABLE to the
testers role.
GRANT CREATE SESSION, CREATE USER, CREATE ROLE, CREATE TABLE TO testers;
-- Delete user jim.
DROP USER jim CASCADE;
-- Create user jim with the password database_123 specified.
CREATE USER jim IDENTIFIED BY database_123;
-- Delete user glow.
DROP USER glow CASCADE;
-- Create user glow with the password database_123 specified.
CREATE USER glow IDENTIFIED BY database_123;
-- Grant the testers role to users jim and glow.
GRANT testers TO jim, glow;

● Create the employees table and user jim, and grant the permission for the
table to jim.
-- Delete the employees table.
DROP TABLE IF EXISTS employees;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 466


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

- Create the employees table.


CREATE TABLE employees
( employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL,
email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL,
phone_number VARCHAR2(20),
hire_date DATE DEFAULT SYSDATE CONSTRAINT emp_hire_date_nn NOT NULL,
job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL,
salary NUMBER(8,2) CONSTRAINT emp_salary_nn NOT NULL,
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
department_id NUMBER(4),
dn VARCHAR2(300),
CONSTRAINT emp_email_uk UNIQUE (email)
);
-- Delete user jim.
DROP USER jim CASCADE;
-- Create user jim with the password gauss_123 specified.
CREATE USER jim IDENTIFIED BY gauss_123;
-- Grant the permission to insert data to the employees table to user jim.
GRANT INSERT ON employees TO jim;

3.13.44 INSERT
Description
INSERT inserts data into a table.

You can use INSERT to insert data in following ways:

● Create a row of records and insert them into a table.


● Create one or more rows of records based on the result set returned by
SELECT and insert the records into a table.
● Insert records into a table. If primary key conflicts are reported, update the
columns reported in the conflicts.

Precautions
● To run this statement, you must have the INSERT permission for the table or
have the INSERT ANY TABLE system permission. Common users are not
allowed to insert objects of user SYS.
● The commit of the INSERT transaction is disabled by default. Before the
session exits, you need to explicitly commit the transaction. Otherwise, records
will be lost.
● If INSERT...SELECT is used, the number of columns in select_list must be the
same as that of columns to be inserted.
● The data size of a single record must be less than 64000 bytes.

Syntax
● Create a record and insert it into a table.
INSERT [hint_info] [IGNORE] [ INTO ] [ schema_name. ]table_name [ ( column_name [ , ... ] ) ]
VALUES ( expression [ , ... ] )

● Insert records generated by the return result of the SELECT clause into a
table.
INSERT [IGNORE] [ INTO ] [ schema_name. ]table_name [table_alais][ ( column_name
[ , ... ] ) ]select_clause

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 467


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– select_clause
SELECT [ DISTINCT ] select_list FROM table_list [ where_clause ] [ group_by_clause ]
[ order_by_clause ] [ limit_clause ]

● Insert a record and update the value that would cause a duplicate value in the
primary key column.
INSERT [ INTO ] [ schema_name. ]table_name [ ( column_name [ , ... ] ) ] VALUES ( expression
[ , ... ] ) ON DUPLICATE KEY UPDATE {column_name = expression} [ , ... ]

Parameter Description
● IGNORE
Ignores records that cause the error of repeated keywords. This parameter
cannot be used together with ON DUPLICATE KEY UPDATE.
● table_name
Specifies the name of a table into which data is inserted.
● column_name
Specifies the names of columns into which data is inserted.
If data is to be inserted into all columns of a table, column names can be
omitted in the INSERT statement.
Value range: an existing column name
● expression
Specifies a value to be inserted or an expression evaluating to values to be
inserted.
● select_clause
Specifies the SELECT clause that generates the records to be inserted. For
details, see SELECT parameters in this document.
● select_list
Specifies the column to be queried.
● table_list
Specifies the tables to be queried, which can be tables, views, or a subquery.
● DISTINCT
Returns only one copy of each set of duplicate rows selected.
Value range: existing column name or column expression
● where_clause
Specifies the conditions that the query result set must satisfy.
● group_by_clause
Specifies the grouping rules that the query result set must satisfy.
● order_by_clause
Specifies the sorting rules that the query result set must satisfy.
● limit_clause
Specifies the boundary for the query result set.
● ON DUPLICATE KEY UPDATE
Updates the value that would cause a duplicate value in the primary key
column. The system traverses each column based on the index creation
sequence to search for duplicate data. For example, if indexes are created on

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 468


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

the f3, f2, and f1 columns of the t1 table in sequence, GaussDB 100 traverses
f3, f2, and f1 in sequence to search for duplicate data.

Examples
Insert data to the training table.
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT NOT NULL PRIMARY KEY,course_name CHAR(50),course_start_date
DATETIME, course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(11,'information safety','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Insert record 3 into the training table.
INSERT INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(12,'master all kinds of thinking methonds','2017-07-15 12:00:00','2017-07-20 12:00:00','2017-07-25
12:00:00',97);
-- Commit the transaction.
COMMIT;
-- Insert record 5 into the training table with ON DUPLICATE KEY UPDATE specified. In this case, values
that would cause a duplicate value in the primary key column will be updated.
INSERT INTO TRAINING
VALUES (12,'INFORMATION234','2018-06-20 12:00:00','2018-06-25 12:00:00','2018-06-26 12:00:00',94)
ON DUPLICATE KEY UPDATE
STAFF_ID=STAFF_ID,COURSE_NAME='INFORMATION234',COURSE_START_DATE='2018-06-20 12:00:00',
COURSE_END_DATE='2018-06-25 12:00:00',
EXAM_DATE='2018-06-23 12:00:00',SCORE=88;
-- Commit the transaction.
COMMIT;

3.13.45 LOCK TABLE


Description
LOCK locks a table.

Precautions
● The user who executes the statement must have the LOCK ANY TABLE
permission.
● The LOCK TABLE statement must be executed in a transaction. Locks are
automatically released when the transaction is committed or rolled back. If
[NOWAIT | WAIT integer] is not specified, the transaction waits until locks
are released.

Syntax Structure
LOCK TABLE { [ schema_name. ]table_name } [ , ... ]
IN lockmode MODE [ NOWAIT | WAIT integer ]

lockmode:
{ SHARE | EXCLUSIVE }

Parameter Description
● [ schema_name. ]

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 469


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Username. If this parameter is not specified, the current login user is used by
default.
● table_name
Specifies the name (optionally schema-qualified) of a table to be locked.
Tables are locked one-by-one in the order specified in the LOCK TABLE
statement.
Value range: an existing table name
● NOWAIT
Does not wait for a lock to be released. If the lock cannot be released
immediately, the LOCK TABLE statement exists and throws an error.
● WAIT
Waits for a lock to be released.
● integer
Specifies the wait timeout duration. 0 indicates that the timeout duration is
unlimited. That is, a transaction waits until the required lock is released.
● SHARE
Permits concurrent queries and DML operations on the locked table but
prohibits DDL operations on it.
SHARE in a statement explicitly requests for a share lock. DML statements
implicitly request for share locks.
● EXCLUSIVE
Permits concurrent queries on the locked table but prohibits any other activity
on it.
In this mode, only reads from the table can proceed in parallel with a
transaction holding this lock. EXCLUSIVE in a statement explicitly requests for
an exclusive lock. DDL statements implicitly request for exclusive locks and
certain operations implicitly request for exclusive locks on system catalogs.

Examples
Lock the bonus_2017 table.
-- Delete the bonus_2017 table.
DROP TABLE IF EXISTS bonus_2017;
-- Create the bonus_2017 table.
CREATE TABLE bonus_2017(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Lock the bonus_2017 table.
LOCK TABLE bonus_2017 IN SHARE MODE;
-- Insert data into the bonus_2017 table.
INSERT INTO bonus_2017(staff_id, staff_name, job, bonus) VALUES(23,'limingwang','developer',5000);
-- Insert data into the bonus_2017 table.
INSERT INTO bonus_2017(staff_id, staff_name, job, bonus) VALUES(24,'liyuyu','tester',7000);
-- Insert data into the bonus_2017 table.
INSERT INTO bonus_2017(staff_id, staff_name, job, bonus) VALUES(25,'wangqizhi','developer',8000);
-- Commit the transaction.
COMMIT;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 470


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.13.46 MERGE
Description
MERGE selects rows from one or more sources for update or insertion into a table
or view.
You can specify conditions to determine whether to update or insert into the
target table or view.

Precautions
● If an ambiguous column exists in the ON, INSERT WHERE, or UPDATE
WHERE clause, specify which table this column belongs to.
● ROWNUM cannot be used in the ON, INSERT WHERE, or UPDATE WHERE
clause.

Syntax Structure
MERGE INTO [ schema_name. ] table_name
USING { [ schema_name. ] table_name
| [ schema_name. ] view_name
| select_query } [ alias ]
ON ( condition )
{ WHEN MATCHED THEN UPDATE SET column_name = expression [ , ... ] [ WHERE ( condition ) ]
|WHEN NOT MATCHED THEN INSERT ( column_name [ , ... ] ) VALUES ( expression [ , ... ] ) [ WHERE
( condition )]
}[ ... ]

Parameter Description
● INTO table_name
Specifies the target table or view to be updated or inserted into.
● USING
Specifies the source of the data to be updated or inserted. The source can be
a table, view, or the result of a subquery.
view_name
Specifies the name of a view.
select_query
Specifies a subquery.
● alias
Specifies a temporary table alias for the target table so that it can be
referenced by other queries. An alias is used for brevity or to eliminate
ambiguity for self-joins. When an alias is provided, it completely hides the
actual name of the table or function.
● ON (condition)
Specifies a condition upon which the MERGE operation either updates or
inserts. For each row in the target table for which the search condition is true,
the database updates the row with corresponding data from the source table.
If the condition is not true for any rows, the database inserts into the target
table based on the corresponding source table row.
condition

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 471


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies a condition upon which the MERGE operation either updates or


inserts.
– WHEN MATCHED THEN UPDATE SET column_name = expression [ , ... ]
[ WHERE ( condition )]
Updates the target table using rows in the source table if the rows meet
the merge conditions.
column_name
Specifies a column name.
expression
Specifies an expression.
– WHEN NOT MATCHED THEN INSERT ( column_name [ , ... ] ) VALUES
( expression [ , ... ] ) [ WHERE ( condition )]
Inserts rows in the source table into the target table if the rows do not
meet the merge conditions.
column_name
Specifies a column name.
expression
Specifies an expression.

Examples
Select rows from the new_bonuses_depa1 table to update data in the
bonuses_depa1 table.
-- Delete the bonuses_depa1 table.
DROP TABLE IF EXISTS bonuses_depa1;
-- Delete the new_bonuses_depa1 table.
DROP TABLE IF EXISTS new_bonuses_depa1;
-- Create the bonuses_depa1 table.
CREATE TABLE bonuses_depa1(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Create the new_bonuses_depa1 table.
CREATE TABLE new_bonuses_depa1(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30),
bonus NUMBER);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer',5000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(24,'limingying','tester',7000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(29,'liuxue','tester',8000);
-- Insert data into the bonuses_depa1 table.
INSERT INTO bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document developer',
11000);
-- Commit the transaction.
COMMIT;
-- Query data in the bonuses_depa1 table.
SELECT * FROM bonuses_depa1;

STAFF_ID STAFF_NAME JOB BONUS


------------ -------------------------------------------------- ------------------------------
----------------------------------------
23 wangxia developer 5000
24 limingying tester 7000
25 liulili quality control 8000
29 liuxue tester 8000
21 caoming document developer 11000

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 472


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

5 rows fetched.
-- Insert record 1 into the new_bonuses_depa1 table.
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(23,'wangxia','developer',7000);
-- Insert record 2 into the new_bonuses_depa1 table.
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(27,'wangxuefen','document
developer',7000);
-- Insert record 3 into the new_bonuses_depa1 table.
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(28,'denghui','quality control',
8000);
-- Insert record 4 into the new_bonuses_depa1 table.
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(25,'liulili','quality control',
10000);
-- Insert record 5 into the new_bonuses_depa1 table.
INSERT INTO new_bonuses_depa1(staff_id, staff_name, job, bonus) VALUES(21,'caoming','document
developer',12000);
-- Commit the transaction.
COMMIT;
-- Query data in the new_bonuses_depa1 table.
SELECT * FROM new_bonuses_depa1;

STAFF_ID STAFF_NAME JOB BONUS


------------ -------------------------------------------------- ------------------------------
----------------------------------------
23 wangxia developer 7000
27 wangxuefen document developer 7000
28 denghui quality control 8000
25 liulili quality control 10000
21 caoming document developer 12000

5 rows fetched.
-- Select rows from the new_bonuses_depa1 table to update data in the bonuses_depa1 table.
MERGE INTO bonuses_depa1 BD1 USING new_bonuses_depa1 NBD1 ON (BD1.staff_id = NBD1.staff_id)
WHEN MATCHED THEN UPDATE SET BD1.bonus = NBD1.bonus
WHEN NOT MATCHED THEN INSERT (staff_id, staff_name, job, bonus) VALUES (NBD1.staff_id,
NBD1.staff_name, NBD1.job, NBD1.bonus);
-- Query data in the bonuses_depa1 table.
SELECT * FROM bonuses_depa1;

STAFF_ID STAFF_NAME JOB BONUS


------------ -------------------------------------------------- ------------------------------
----------------------------------------
23 wangxia developer 7000
24 limingying tester 7000
25 liulili quality control 10000
29 liuxue tester 8000
21 caoming document developer 12000
27 wangxuefen document developer 7000
28 denghui quality control 8000

7 rows fetched.

3.13.47 PURGE

Description
PURGE removes a table, index, or tablespace from the recycle bin.

Precautions
● You can purge tables (PURGE TABLE), indexes (PURGE INDEX), tablespaces
(PURGE TABLESPACE), and recycle bins (PURGE RECYCLEBIN).
● You can purge your own objects (table/index) without additional permissions.
● To purge objects of other users, the following permissions are required:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 473


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– To purge tables of other users, you must have the DROP ANY TABLE
permission.
– To purge indexes of other users, you must have the DROP ANY INDEX
permission.
– To purge the recycle bin, you must have the PURGE DBA_RECYCLEBIN
permission.
– To purge tablespaces, you must have the DROP TABLESPACE permission.
● Profiles cannot be created during database restart or rollback.

Syntax
PURGE { TABLE [schema_name.]table_name
| INDEX index_name
| TABLESPACE tablespace_name
| RECYCLEBIN
}

Parameter Description
● [ schema_name. ]
Username. If this parameter is not specified, the current login user is used by
default.
● TABLE [schema_name.]table_name
Specifies the name of a table to be removed from the recycle bin.
● INDEX index_name
Specifies the name of an index to be removed from the recycle bin.
● TABLESPACE tablespace_name
Specifies the name of a tablespace to be removed from the recycle bin. Value
range: view or table name
● RECYCLEBIN
Removes all objects from the recycle bin.

Examples
Remove the subsidies_dep1_2018 table from the recycle bin.
-- Delete the human_subsidies_2018 tablespace in the MOUNT database state.
DROP TABLESPACE human_subsidies_2018;
-- Create the human_subsidies_2018 tablespace in the OPEN database state.
CREATE TABLESPACE human_subsidies_2018 DATAFILE 'subsidies2018' SIZE 32M;
-- Delete the subsidies_dep1_2018 table.
DROP TABLE IF EXISTS subsidies_dep1_2018;
-- Create the subsidies_dep1_2018 table.
CREATE TABLE subsidies_dep1_2018(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30),
subsidies NUMBER) TABLESPACE human_subsidies_2018;
-- Delete the subsidies_dep1_2018 table.
DROP TABLE IF EXISTS subsidies_dep1_2018;
-- Query the recycle bin.
SELECT * FROM SYS.SYS_RECYCLEBIN;

ID NAME USER# ORG_NAME


--------------------- ------------ -------------------------------
509171 BIN$2048$7C4F3==$0 0 SUBSIDIES_DEP1_2018

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 474


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Remove the subsidies_dep1_2018 table from the recycle bin.


PURGE TABLE subsidies_dep1_2018;

3.13.48 REALEASE SAVEPOINT


Function
RELEASE SAVEPOINT removes an existing savepoint.

Precautions
● An error is reported if you remove a nonexistent savepoint.

● When a savepoint is removed, savepoints later than this savepoint are also
removed.

Syntax
RELEASE SAVEPOINT savepoint_name;

Parameter Description
● savepoint_name
Specifies the name of a savepoint to be removed.

Examples
-- Define a savepoint sp1.
SAVEPOINT sp1;
-- Delete the TEST table.
DROP TABLE IF EXISTS TEST;
-- Create the TEST table.
CREATE TABLE TEST(ID INT NOT NULL);
INSERT INTO TEST VALUES(1);
-- Define a savepoint sp2.
SAVEPOINT sp2;
INSERT INTO TEST VALUES(2);
-- Remove the savepoint sp1.
RELEASE SAVEPOINT sp1;

After RELEASE SAVEPOINT sp1 is executed, sp1 and sp2 are removed.

3.13.49 REPLACE
Description
REPLACE inserts data into a table or replaces existing data in a table. If the data
to be inserted has the primary key or unique key conflicts with the existing data,
the REPLACE statement deletes the existing data and then inserts the new data.

You can use REPLACE in following ways:

● Create a row of records and insert them into a table.


● Create one or more rows of records based on the result set returned by
SELECT and insert the records into a table.
● Specify column values, which is similar to INSERT. If no value is specified for a
column, the default value of this column is used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 475


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Precautions
● To execute this statement, you must have the DELETE and INSERT
permissions for the table.
● If no primary key conflict occurs, data is inserted directly. Otherwise, the data
is deleted and then inserted. If the number of affected rows is 1, data is
directly inserted. If the value of affected rows is 2, data is deleted and then
inserted.
● The commit of the REPLACE transaction is disabled by default. Before the
session exits, you need to explicitly commit the transaction. Otherwise, records
will be lost.
● If REPLACE...SELECT is used, the number of columns in select_list must be the
same as that of columns to be inserted.
● In the REPLACE...SET statement, if col_name does not have a default value,
SET col_name = col_name + 1 equals col_name = NULL. If col_name has a
default value, SET col_name = col_name + 1 equals SET col_name = Default
value of col_name + 1.

Syntax
● Directly replace a record.
REPLACE [hint_info] [ INTO ] [ schema_name. ]table_name [ ( column_name [ , ... ] ) ] VALUES
( expression [ , ... ] )
● Replace a record by using SELECT.
REPLACE [ INTO ] [ schema_name. ]table_name [table_alais][ ( column_name [ , ... ] ) ]select_clause
– select_clause
SELECT [ DISTINCT ] select_list FROM table_list [ where_clause ] [ group_by_clause ]
[ order_by_clause ] [ limit_clause ]
● Replace a record by using an expression.
REPLACE [ INTO ] [ schema_name. ]table_name SET {column_name = expression} [ , ... ]

Parameter Description
● table_name
Specifies the name of a table into which data is inserted.
● column_name
Specifies the names of columns into which data is inserted.
If data is to be inserted into all columns of a table, column names can be
omitted in the INSERT statement.
Value range: an existing column name
● expression
Specifies a value to be inserted or an expression evaluating to values to be
inserted.
● select_clause
Specifies the SELECT clause that generates the records to be inserted. For
details, see SELECT parameters in this document.
● select_list
Specifies the columns to be queried.
● table_list
Specifies the tables to be queried, which can be tables, views, or a subquery.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 476


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● DISTINCT
Returns only one copy of each set of duplicate rows selected.
Value range: existing column name or column expression
● where_clause
Specifies the conditions that the query result set must satisfy.
● group_by_clause
Specifies the grouping rules that the query result set must satisfy.
● order_by_clause
Specifies the sorting rules that the query result set must satisfy.
● limit_clause
Specifies the boundary for the query result set.

Examples
-- Delete the training table.
DROP TABLE IF EXISTS training;
-- Create the training table.
CREATE TABLE training(staff_id INT PRIMARY KEY,course_name CHAR(50),course_start_date DATETIME,
course_end_date DATETIME,exam_date DATETIME,score INT);
-- Insert record 1 into the training table.
REPLACE INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'SQL majorization','2017-06-15 12:00:00','2017-06-20 12:00:00','2017-06-25 12:00:00',90);
-- Replace record 1 in the training table.
REPLACE INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
VALUES(10,'information safety','2017-06-20 12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Use REPLACE...SELECT to replace record 1 in the training table.
REPLACE INTO training(staff_id,course_name,course_start_date,course_end_date,exam_date,score)
select 10,'master all kinds of thinking methonds','2017-07-15 12:00:00','2017-07-20 12:00:00','2017-07-25
12:00:00',97 from SYS_DUMMY;
-- Use SET to insert record 2 into the training table.
REPLACE /*+ nologging*/ INTO training SET staff_id = 11,course_name = 'information technology',
course_start_date = '2017-07-20 12:00:00', course_end_date = '2017-07-25 12:00:00',exam_date =
'2017-07-26 12:00:00',score = 95;
-- Commit the transaction.
COMMIT;

3.13.50 REVOKE
Description
REVOKE revokes system permissions or roles from a user.

Precautions
● To revoke a system permission, you must meet one of the following
requirements:
– You have this system permission with WITH ADMIN OPTION specified.
– You have the GRANT ANY PRIVILEGE system permission.
● To revoke a role, you must meet one of the following requirements:
– You are granted with this role, with WITH ADMIN OPTION specified.
– You have the GRANT ANY ROLE system permission.
– You are the creator of this role.
● If you revoke a permission from a user but this user does not have this
permission, an error message is displayed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 477


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The permissions of the DBA role cannot be revoked. The initial rights of the
DBA role are determined when the database is created. Permissions can be
granted to the DBA role but cannot be revoked.

Syntax
● Revoke system permissions.
REVOKE { ALL [ PRIVILEGES ]
|{ system_privilege_name | role_name } [ , ... ] } FROM revokee

revokee:
{ user_name | role_name } [ , ... ]

● Revoke object permissions.


REVOKE { ALL [ PRIVILEGES ]
| { object_privilege_name [, ...] ON [schema_name.]object_name } } FROM revokee

object_privilege_name:
{ SELECT | UPDATE | DELETE | INSERT | ALTER | INDEX | EXECUTE | READ | REFERENCES } [, ... ]

Parameter Description
● system_privilege_name
Specifies the name of a system permission to be revoked.
System permissions supported by the database are listed in Table 3-53.
● role_name
Specifies the name of a role to be revoked. After a role is revoked from users
or other roles, permissions of this role are revoked from these users or roles.
● ALL [ PRIVILEGES ]
All system permissions. PRIVILEGES can be omitted.
● object_privilege_name
Object permission name.
● ALL [ PRIVILEGES ]
Permission of all objects. PRIVILEGES can be omitted.
● [ schema_name. ]
Username. If this parameter is not specified, the current login user is used by
default.
● revokee
A user or role whose permissions are revoked. A user can specify a maximum
of 63 users or roles at a time.
● user_name
Name of the user whose permissions are revoked.

Examples
● Revoke a system permission from user joe.
-- Delete user joe.
DROP USER joe CASCADE;
-- Create user joe.
CREATE USER joe IDENTIFIED BY database_123;
-- Grant system permissions CREATE SESSION, CREATE TABLE, CREATE ANY INDEX, and CREATE
USER to user joe.
GRANT CREATE SESSION, CREATE TABLE, CREATE ANY INDEX, CREATE USER TO joe;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 478


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Revoke the system permission CREATE USER from user joe.


REVOKE CREATE USER FROM joe;
● Revoke a role from user jim.
-- Delete the testers role.
DROP ROLE testers;
-- Create the testers role.
CREATE ROLE testers;
-- Delete user jim.
DROP USER jim CASCADE;
-- Create user jim with the password database_123 specified.
CREATE USER jim IDENTIFIED BY database_123;
-- Delete user glow.
DROP USER glow CASCADE;
-- Create user glow.
CREATE USER glow IDENTIFIED BY database_123;
-- Grant system permissions CREATE SESSION, CREATE USER, CREATE ROLE, CREATE TABLE,
CREATE ANY TABLE, CREATE ANY INDEX, DROP USER, DROP ANY ROLE, DROP ANY TABLE, and
DROP ANY INDEX to the testers role.
GRANT CREATE SESSION, CREATE USER, CREATE ROLE, CREATE TABLE, CREATE ANY TABLE, CREATE
ANY INDEX, DROP USER, DROP ANY ROLE, DROP ANY TABLE, DROP ANY INDEX TO testers;
-- Grant the testers role to users jim and glow.
GRANT testers TO jim, glow;
-- Revoke the testers role from user jim.
REVOKE testers FROM jim;

3.13.51 ROLLBACK
Description
ROLLBACK rolls back (undoes) work done in the current transaction and
terminates the transaction.

Precautions
● You are advised to explicitly end transactions in application programs using
either a COMMIT or ROLLBACK statement. If you do not explicitly commit
the transaction and the program terminates abnormally, the database rolls
back the last uncommitted transaction.
● The CREATE TABLESPACE and ALTER DATABASE DDL statements cannot be
rolled back.

Syntax
ROLLBACK [ TO SAVEPOINT savepoint_name ]

Parameter Description
● TO SAVEPOINT
Rolls back the current transaction to a specified savepoint.
● savepoint_name
Specifies the name of a savepoint to be created.

Examples
Create the posts table and insert data into the table. Roll back all the operations
and terminate the transaction.
-- Delete the posts table.
DROP TABLE IF EXISTS posts;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 479


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create the posts table.


CREATE TABLE posts(post_id CHAR(2) NOT NULL, post_name CHAR(16) NOT NULL, basic_wage INT,
basic_bonus INT);
-- Insert record 1 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('A','general manager',50000,5000);
-- Insert record 2 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('B','project manager',10000,5000);
-- Insert record 3 into the posts table.
INSERT INTO posts(post_id,post_name,basic_wage,basic_bonus) VALUES('C','staff',3000,1000);
--Rolls back the transaction.
ROLLBACK;

3.13.52 SAVEPOINT
Function
SAVEPOINT names and marks the current point in the processing of a transaction.
Then, you can roll back a transaction being executed to a specified savepoint.
Operations before the savepoint are valid, and those after that become invalid.
You can create multiple savepoints in a transaction.

Precautions
After the rollback to a savepoint, the transaction status is the same as that when
the savepoint is created. All the work after the savepoint is undone.

Syntax
SAVEPOINT savepoint_name

Parameter Description
savepoint_name
Specifies the name of a savepoint to be created.

Examples
Roll back a transaction to a savepoint.
-- Delete the bonus_2017 table.
DROP TABLE IF EXISTS bonus_2017;
-- Create the bonus_2017 table.
CREATE TABLE bonus_2017(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus
NUMBER);
-- Insert record 1 into the bonus_2017 table.
INSERT INTO bonus_2017(staff_id, staff_name, job, bonus) VALUES(23,'limingwang','developer',5000);
-- Commit the transaction.
COMMIT;
-- Create a savepoint s1.
SAVEPOINT s1;
-- Insert record 2 into the bonus_2017 table.
INSERT INTO bonus_2017(staff_id, staff_name, job, bonus) VALUES(24,'liyuyu','tester',7000);
-- Create a savepoint s2.
SAVEPOINT s2;
-- Query data in the bonus_2017 table.
SELECT * FROM bonus_2017;

STAFF_ID STAFF_NAME JOB BONUS


------------ -------------------------------------------------- ------------------------------
----------------------------------------

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 480


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

23 limingwang developer 5000


24 liyuyu tester 7000

2 rows fetched.
-- Roll back to the savepoint s1.
ROLLBACK TO SAVEPOINT s1;
-- Query data in the bonus_2017 table.
SELECT * FROM bonus_2017;

STAFF_ID STAFF_NAME JOB BONUS


------------ -------------------------------------------------- ------------------------------
----------------------------------------
23 limingwang developer 5000

1 rows fetched.

3.13.53 SELECT
Description
SELECT retrieves data from tables or views.

Precautions
● To access a table of another user, the user who runs the statement must have
the READ ANY TABLE or SELECT ANY TABLE system permission, or the READ
or SELECT object permission for the table.
● In a SELECT statement, an outer query does not support GROUP BY if a
subquery references a column of the outer query, for example, SELECT a,b,
(SELECT t2.c FROM t2 WHERE t2.a=t1.a) FROM t1 GROUP BY a,b;.
● The number of levels in a hierarchical query cannot exceed 256. Otherwise, an
error is returned.
● To use ORDER BY or LIMITF in a SELECT clause in a statement containing set
operators, such as UNION and MINUS, pack the SELECT clause together with
its ORDER BY or LIMIT clause in a pair of parenthesis.

Syntax
SELECT [hint_info] [SQL_CALC_FOUND_ROWS] [ DISTINCT ] { expression
[ [ AS ] name ] } [ , ... ]
[ FROM { table_reference [ AS OF {SCN(scn_number) | TIMESTAMP(date)} ] [ [AS] alias ] } [ , ... ] ]
[ WHERE { condition | [ NOT ] EXISTS ( correlated subquery ) } ]
[ [START WITH condition ] CONNECT BY [ NOCYCLE ] [ PRIOR ] condition ]
[ GROUP BY { column_name | expression } [ , ... ] ]
[ HAVING condition [ , ... ] ]
[ { UNION [ ALL ] | MINUS } select ]
[ ORDER [SIBLINGS] BY { column_name | number | expression } [ ASC | DESC ][ NULLS FIRST | NULLS
LAST ] [ , ... ] ]
[ LIMIT [ start, ] count | LIMIT count OFFSET start | OFFSET start[ LIMIT count ] ]
[ FOR UPDATE ]
● hint_info:
{/*+ {access_method_hint | join_order_hint | join_method_hint | parallel_hint }[...] */}
– access_method_hint:
{ FULL(table_name [...])
| INDEX(table_name index_name[...])
| NO_INDEX(table_name index_name[...])
| INDEX_ASC(table_name index_name[...])
| INDEX_DESC(table_name index_name[...])
| INDEX_FFS(table_name index_name[...])
| NO_INDEX_FFS(table_name index_name[...])
}

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 481


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– join_order_hint:
{ ORDERED
| LEADING(table_name[...])
}

– join_method_hint:
{ USE_NL(table_name[...])
| USE_MERGE(table_name[...])
| USE_HASH(table_name[...])
}

– parallel_hint
{ parallel(degree)
}

● table_reference:
{ [ schema_name. ]table_name [partition(partition_name)][ [AS] alias ]
| [ schema_name. ]view_name [ [AS] alias]
| ( select query ) [ [AS] alias ]
| join_table
}

– join_table:
INNER join by default
When INNER is selected, the ON condition can be omitted.
table_reference [LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER] | INNER] JOIN table_reference
ON conditional_expr

● Outer join operator (+)


An outer join can be described either by the LEFT/RIGHT keyword or the
operator (+). A condition that contains (+) in the WHERE clause is used for
an outer join. Specifically, the table containing (+) is the right node of a left
join, and the table without (+) is the left node of the left join.
– The outer join operator can be used as follows:

▪ If there is a join keyword, (+) cannot be used.

▪ Only table columns can precede (+).

▪ (+) can only be used in the WHERE clause, and the condition that
contains (+) does not belong to the OR clause.

▪ In a comparison condition, (+) allows for only six operators: =, <>, >,
<, >=, <=.

▪ In a comparison condition, (+) can be placed on either sides.

▪ If (+) is on one side of a comparison condition, columns of at most


one table are allowed on each side of the condition.

▪ The operator (+) takes effect if only it appears on one side of a


comparison condition. Multiple operators (+) produce the same
effect as one operator.

▪ If multiple conditions contain (+), for example, t1.f1=t2.f1(+) and


t1.f1(+)=t2.f1, an error may be reported because the association
relationship fails to be generated.
● condition:
{ predicate } [ { AND | OR } condition ] [ , ... n ]

– predicate:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 482


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

{ expression { = | <> | != | > | >= | < | <= } { ALL | ANY } expression | ( select )
| string_expression [ NOT ] LIKE string_expression
| expression [ NOT ] BETWEEN expression AND expression
| expression IS [ NOT ] NULL
| ( select | expression [,...n] ) [ NOT ] IN ( select | expression [ , ... n ] )
| [ NOT ] EXISTS ( select )
}

Parameter Description
● hint_info
– Specifies special comments in a SQL statement that pass instructions to
the database optimizer. The optimizer uses these hints to choose an
execution plan for the statement, unless there are some conditions that
prevent the optimizer from doing so.
– Exercise caution when using hint_info. You are advised to use hints for a
table query only when you have collected statistics about the table and
evaluated the execution plan without hints by using EXPLAIN PLAN.
– In later database versions, database conditions may change and query
performance will be enhanced, which will affect the use of hints. Note
that short-term benefits generated by hints do not necessarily lead to
long-term improvement.
– Currently, parallel hints support only full table scanning of a single table.
Aggregate functions, ORDER BY, GROUP BY, and building of hash tables
are supported.
● SQL_CALC_FOUND_ROWS
It is a reserved word. SQL_CALC_FOUND_ROWS records the number of rows
the SELECT statement would have returned without LIMIT specified. Then,
you can use the FOUND_ROWS() function to obtain the number.
SQL_CALC_FOUND_ROWS can be specified only after the first SELECT
keyword in the SELECT statement. If SELECT is a clause of a UNION, UNION
ALL, or MINUS statement, SQL_CALC_FOUND_ROWS can be specified only in
the first SELECT clause. This reserved word is valid only when the
FOUND_ROWS() function is used.
For details, see FOUND_ROWS() in Other Functions.
● DISTINCT
Returns only one copy of each set of duplicate rows selected.
Value range: existing column name or column expression
● AS OF {SCN(scn_number) | TIMESTAMP(date)}
Queries the table data of a specified SCN or at a specified time point.
Currently, temporary tables and system views cannot be queried.
– AS OF
Performs a flashback query.
– SCN(scn_number)
Queries the result set of the table with the SCN specified by scn_numer.
– TIMESTAMP(date)
Queries the result set at the time point specified by date. date must be a
valid past timestamp (convert a string to a time type using the
TO_TIMESTAMP function).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 483


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Note: The specified time point must be earlier than the table creation
time. Otherwise, an error is reported.
● START WITH condition CONNECT BY [ NOCYCLE ] [ PRIOR ] condition
Specifies a clause for querying tree-structured data. If a table contains tree-
structured data, you can use this clause to query data.
– START WITH
Specifies the row that is the root of a tree-structured data query.
– CONNECT BY
Specifies the relationship between parent rows and child rows of a tree-
structured data query. It is used in conjunction with PRIOR.
– NOCYCLE
Instructs the database to return rows from a query even if CONNECT BY
LOOP exists in the data.
– PRIOR
PRIOR is a unary operator and has the same precedence as the unary +
and - arithmetic operators. The PRIOR keyword can be on either side of
the equal sign (=). If PRIOR is placed together with the parent ID, the
query traverses data in the direction of parent nodes. If it is placed
together with the child ID, the query traverses data in the direction of
child nodes.
– CONNECT_BY_ISCYCLE pseudocolumn
The CONNECT_BY_ISCYCLE pseudocolumn indicates whether the current
tuple will form the tree-structured data into a loop. It is valid only when
the NOCYCLE keyword is used in a hierarchical query clause. The
CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a
child which is also its ancestor. Otherwise, it returns 0.
– CONNECT_BY_ISLEAF pseudocolumn
The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a
leaf of the tree defined by the CONNECT BY condition. Otherwise, it
returns 0. This information indicates whether a given row can be further
expanded to show more of the hierarchy.
– LEVEL pseudocolumn
For each row returned by a hierarchical query, the LEVEL pseudocolumn
returns 1 for a root row, 2 for a child of a root, and so on. A root row is
the highest row within an inverted tree. A child row is any nonroot row. A
parent row is any row that has children. A leaf row is any row without
children.
● expression
Specifies a field or field expression to be queried.
● table_reference
Specifies a table or view to be queried, or a subquery.
[partition(partition_name)]
Specifies the partition of a table for query. partition_name indicates the
partition name.
● condition
Restricts the rows selected to those that satisfy one or more conditions.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 484


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Query conditions are defined by expressions and operators. Multiple


conditions can be associated by AND or OR. In GaussDB 100, conditions can
be defined by using:
– Comparison operators, such as >, <, >=, <=, !=, <>, and =.
– Test operators, such as LIKE, NOT LIKE, BETWEEN, NOT BETWEEN,
NULL, NOT NULL, IN, and NOT IN.
– EXISTS (select), which requires that the columns to be queried exist.
– NOT EXISTS (select), which requires that the columns to be queried do
not exist.
● GROUP BY
Specifies a column based on which a result set is grouped.
● HAVING
Specifies the filter conditions for restricting the results of a GROUP BY.
● ORDER BY
Specifies a column based on which a result set is sorted.
ORDER SIBLINGS BY
Specifies the columns used for sorting sibling nodes. This parameter can be
used only when CONNECT BY is specified.
● ASC | DESC
Specifies whether the ordering sequence is ascending or descending. The
default value is ASC.
● NULLS FIRST | NULLS LAST
Specifies the position of NULL values in the ORDER BY sorting. FIRST
indicates that NULL values are placed before non-NULL values and LAST
indicates that NULL values are placed after non-NULL values. If this
parameter is not specified, NULLS LAST is used in ASC mode and NULLS
FIRST is used in DESC mode by default.
● FOR UPDATE
Locks the selected rows for UPDATE.
● offset_expr, count_expr
offset_expr limits the offset of a result set and count_expr limits the number
of rows in a result set.
● start,count
count specifies the maximum number of rows to return, while start specifies
the number of rows to skip before the first row is returned. When both are
specified, rows specified by start will be skipped before rows specified by
count are returned.
● UNION [ALL]
Returns all rows in the result sets of multiple SELECT statements.
● FULL(table_name [...])
Specifies a full-table scan.
● INDEX(table_name index_name[...])
Specifies an index scan.
● NO_INDEX(table_name index_name[...])

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 485


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies a non-index scan.


● INDEX_ASC(table_name index_name[...])
Specifies an ascending index scan.
● INDEX_DESC(table_name index_name[...])
Specifies a descending index scan.
● INDEX_FFS(table_name index_name[...])
Specifies a fast full index scan.
● NO_INDEX_FFS(table_name index_name[...])
Excludes a fast full index scan of the specified indexes on the specified table.
● ORDERED
Joins tables in the order in which they appear in the FROM clause.
● LEADING(table_name[...])
Joins tables in the specified order.
● USE_NL(table_name[...])
Joins each specified table to another row source using a nested-loop join.
● USE_MERGE(table_name[...])
Joins each specified table with another row source using a sort-merge join.
● USE_HASH(table_name[...])
Joins each specified table with another row source using a hash join.
● join_table
Specifies a set of tables for join query.
– [INNER] JOIN returns records that have matching values in both tables.
In this case, the subsequent ON condition can be omitted.
– LEFT [OUTER] JOIN returns all records from the left table and the
matched records from the right table. The result is NULL from the right
side, if there is no match.
– RIGHT [OUTER] JOIN returns all records from the right table and the
matched records from the left table. The result is NULL from the left side,
when there is no match.
– FULL [OUTER] JOIN returns all records when there is a match in either
left or right table It is an equivalent of OUTER JOIN.
● {predicate } [ { AND | OR } condition]
Specifies the conditions that the query result set must satisfy.
– AND
Both of the two conditions must be satisfied.
– OR
Either of the two conditions must be satisfied.
● predicate:
Specifies the conditions that the query result set must satisfy.

Examples
● Perform a join query between the education and training_beijing_branch
tables.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 486


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the education table.


DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'doctor','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'scholar','Peking University','2017-07-06 12:00:00','211&985');
-- Commit the transaction.
COMMIT;
-- Delete the training_beijing_branch table.
DROP TABLE IF EXISTS training_beijing_branch;
-- Create the training_beijing_branch table.
CREATE TABLE training_beijing_branch(staff_id INT NOT NULL, staff_name VARCHAR(16),
course_name VARCHAR(60), course_start_date DATETIME, course_end_date DATETIME, exam_date
DATETIME, score INT);
-- Insert record 1 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_dat
e,score) VALUES(10,'liming','the tenth phase of SQL majorization','2017-06-15 12:00:00','2017-06-20
12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_dat
e,score) VALUES(11,'caoxueying','the tenth phase of information safety','2017-06-20
12:00:00','2017-06-25 12:00:00','2017-06-26 12:00:00',95);
-- Insert record 3 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_dat
e,score) VALUES(13,'zhangjianmin','the tenth phase of mastering all kinds of thinking
methonds','2017-07-15 12:00:00','2017-07-20 12:00:00','2017-07-25 12:00:00',97);
-- Insert record 4 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_dat
e,score) VALUES(14,'wangkangmei','quality standard','2017-06-20 12:00:00','2017-06-25
12:00:00','2017-06-26 12:00:00',98);
-- Commit the transaction.
COMMIT;
-- Perform a join query between the education and training_beijing_branch tables.
SELECT education.staff_id, staff_name, highest_degree, course_name, score FROM education JOIN
training_beijing_branch ON education.staff_id=training_beijing_branch.staff_id;
-- Hint example:
create unique index idx_edu_gra_school on education(graduate_school);
-- Access the education table by the idx_edu_gra_school index.
select /*+ index(t idx_edu_gra_school) this is a hint */ * from education t;
-- Specify merge_sort for joining t1 and t2 and specify t2 as the row source.
select /*+ leading(t2 t1) use_merge (t1) */ t1.staff_id , t2.staff_id from education t1,
training_beijing_branch t2 where t1.staff_id= t2.staff_id ;
-- In the SQL parsing phase, the parallelism degree in the parallel hint is 4 or 8. In SQL execution
phase, four or eight threads meeting requirements are enabled for concurrent execution.
select /*+ parallel(8) */ count(*) from par_test_t1;
select /*+ parallel(4) */ a, b, max(c) from tbl_group group by a,b order by a,b;

● Use ORDER SIBLINGS BY to sort a result set.


-- Delete the t_sibling_order table.
DROP TABLE if exists t_sibling_order;
-- Create the t_sibling_order table.
create table t_sibling_order(EMPNO NUMBER(10) NOT NULL,ENAME VARCHAR2(10),MGR
NUMBER(4));
-- Insert records into the t_sibling_order table.
insert into t_sibling_order values (1,'M',NULL);
insert into t_sibling_order values (2,'N',NULL);
insert into t_sibling_order values (3,'A',NULL);
insert into t_sibling_order values (4,'C',3);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 487


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

insert into t_sibling_order values (5,'B',3);


insert into t_sibling_order values (6,'F',4);
insert into t_sibling_order values (7,'E',4);
insert into t_sibling_order values (8,'D',5);
insert into t_sibling_order values (9,'G',5);
-- Use ORDER SIBLINGS BY to sort the result set.
SELECT LEVEL, t.empno, t.ename FROM t_sibling_order t START WITH t.mgr IS NULL CONNECT BY
PRIOR t.empno = t.mgr ORDER SIBLINGS BY t.ename;

3.13.54 SET TRANSACTION


Description
SET TRANSACTION determines the isolation level of a transaction.
The isolation level of a transaction determines how the transaction behavior is
visible to other transactions. If an isolation level is set for a transaction, this
transaction is more visible to other uncommitted transactions, improving the
concurrency level.

Precautions
The isolation level can only be set before the transaction is executed, and the
isolation level cannot be changed during the transaction execution.

Syntax
SET TRANSACTION ISOLATION LEVEL { SERIALIZABLE | READ COMMITTED | CURRENT COMMITTED }

Parameter Description
● SERIALIZABLE
Completely isolates a transaction from others. It is the most strict level.
● READ COMMITTED
Reads only data committed before the query begin, preventing dirty data. It is
the default level. At this level, data read by an SQL statement is the data of
the same snapshot.
● CURRENT COMMITTED
Data read by an SQL statement is the latest committed data at the read time.
All read data is no longer snapshot data.

Examples
Set the isolation level.
--Set the isolation level to READ COMMITED before the transaction is executed.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- Run statement 1 in the transaction.
DROP TABLE IF EXISTS bouns_2017;
-- Run statement 2 in the transaction.
CREATE TABLE bouns_2017(staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bouns
NUMBER);
-- Run statement 3 in the transaction.
INSERT INTO bouns_2017(staff_id, staff_name, job, bouns) VALUES(23,'limingwang','developer',5000);
-- Run statement 4 in the transaction.
INSERT INTO bouns_2017(staff_id, staff_name, job, bouns) VALUES(24,'liyuyu','tester',7000);
-- Run statement 5 in the transaction.
INSERT INTO bouns_2017(staff_id, staff_name, job, bouns) VALUES(25,'wangqizhi','developer',8000);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 488


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Commit the transaction.


COMMIT;

3.13.55 TRUNCATE TABLE


Function
TRUNCATE TABLE removes all data from a table and releases the storage space.

Precautions
● You can run the TRUNCATE TABLE statement to delete all records from a
table. You can truncate your own table without additional permissions. To
truncate tables of other users, you must have the DROP ANY TABLE
permission.
● The TRUNCATE statement cannot be rolled back.
● You can also use the DELETE statement to delete data.
● A table cannot be truncated during database restart or rollback.

Syntax
TRUNCATE TABLE [ schema_name. ]table_name [ PURGE ] [ { DROP | REUSE } STORAGE ]

Parameter Description
● [schema_name.] table_name
Specifies the name of a table to be truncated.
● Not specifying PURGE, DROP STORAGE, or REUSE STORAGE
After you run the TRUNCATE statement for a table, the table is moved to the
recycle bin. You can run the FLASHBACK statement to restore the table.
● PURGE
Removes a table from the recycle bin and releases the tablespace of this
table. It is an equivalent of DROP STORAGE.
● DROP STORAGE
Releases tablespaces from truncated tables. Then, the released tablespaces
are returned to the system and can be used by other segments. DROP
STORAGE is the default.
● REUSE STORAGE
Does not release tablespaces from truncated tables.

Examples
Delete all data from the education table and release the tablespace.
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school VARCHAR(64),
graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'doctor','Xidian University','2017-07-06 12:00:00','211');
-- Insert record 2 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 489


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

VALUES(11,'master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');


-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'scholar','Xi'an University of Architecture and Technology','2017-07-06 12:00:00','not 211 or 985');
-- Commit the transaction.
COMMIT;
-- Delete all data from the education table and release the tablespace.
TRUNCATE TABLE education DROP STORAGE;

3.13.56 UPDATE
Description
UPDATE updates row values in a table.

Precautions
● The commit of the UPDATE transaction is disabled by default. Before the
session exits, you need to explicitly commit the transaction. Otherwise, records
will be lost.
● To run this statement, you must have the UPDATE permission for the table or
have the UPDATE ANY TABLE system permission. Common users are not
allowed to update objects of user SYS.
● Multiple temporary tables cannot be batch updated.

Syntax
(col_name[,...]) = (expression[,...]) can be used only when the join_table clause is
used.
UPDATE table_reference SET { [col_name = expression] [ , ... ] | (col_name[,...]) = (SELECT expression[,...]) }
[ WHERE condition ]

● table_reference:
{ [ schema_name. ] table_name
| join_table
}

● join_table:
table_reference [LEFT [OUTER] | RIGHT [OUTER] | INNER ] JOIN table_reference ON conditional_expr

Parameter Description
● table_reference
Specifies tables to be updated.
Value range: existing tables
● table_name
Specifies names of tables to be updated.
Value range: existing table names
● col_name
Specifies names of columns to be updated.
Value range: existing column names
● expression
Specifies a value assigned to a column or an expression that assigns the value.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 490


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● condition
Specifies an expression that returns a Boolean value. Only rows for which this
expression returns true are updated.
● join_table
Specifies a set of tables for join query.
– INNER JOIN returns records that have matching values in both tables.
– LEFT [OUTER] JOIN returns all records from the left table and the
matched records from the right table. The result is NULL from the right
side, if there is no match.
– RIGHT [OUTER] JOIN returns all records from the right table and the
matched records from the left table. The result is NULL from the left side,
when there is no match.

Examples
In the training table, update the first_name column for the records whose
staff_id is the same as staff_id in the education table.
-- Delete the education and training tables.
DROP TABLE IF EXISTS education;
DROP TABLE IF EXISTS training;
-- Create the education and training tables.
CREATE TABLE education(staff_id INT, first_name VARCHAR(20));
CREATE TABLE training(staff_id INT, first_name VARCHAR(20));
-- Insert data.
INSERT INTO education VALUES(1, 'ALICE');
INSERT INTO education VALUES(2, 'BROWN');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(1, 'ALICE');
INSERT INTO training VALUES(3, 'BOB');
-- In the training table, update the first_name column for the records whose staff_id is the same as
staff_id in the education table.
UPDATE training INNER JOIN education ON training.staff_id = education.staff_id SET training.first_name =
'ALAN';

In the training_beijing_branch table, update the records whose staff_id is 10.


-- Delete the training_beijing_branch table.
DROP TABLE IF EXISTS training_beijing_branch;
-- Create the training_beijing_branch table.
CREATE TABLE training_beijing_branch(staff_id INT NOT NULL, staff_name VARCHAR(16), course_name
VARCHAR(50), course_start_date DATETIME, course_end_date DATETIME, exam_date DATETIME, score INT);
-- Insert record 1 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,scor
e)
VALUES(10,'liming','the tenth phase of SQL majorization','2017-06-15 12:00:00','2017-06-20
12:00:00','2017-06-25 12:00:00',90);
-- Insert record 2 into the training_beijing_branch table.
INSERT INTO
training_beijing_branch(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,scor
e)
VALUES(11,'caoxueying','the tenth phase of information safety','2017-06-20 12:00:00','2017-06-25
12:00:00','2017-06-26 12:00:00',95);
-- Commit the transaction.
COMMIT;
Update data in the training_beijing_branch table.
UPDATE training_beijing_branch SET staff_name='caoxueying', course_name='the twenty-third phase of
information safety' WHERE staff_id=10;
-- Commit the transaction.
COMMIT;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 491


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Update the partition key score of the partitioned table student_score to update a
record from one partition to another.
-- Delete the student_score table.
DROP TABLE IF EXISTS student_score;
-- Create a partitioned table student_score.
CREATE TABLE student_score(id INT NOT NULL, score INT) PARTITION BY RANGE(score)
(
PARTITION P1 VALUES LESS THAN(60),
PARTITION P2 VALUES LESS THAN(100)
);
-- Insert record 1 into the student_score table.
INSERT INTO student_score(id, score) VALUES(20180102, 50);
-- Insert record 2 into the student_score table.
INSERT INTO student_score(id, score) VALUES(20180121, 80);
-- Update record 1 in the student_score table.
UPDATE student_score SET score=70 WHERE id =20180102;
-- Commit the transaction.
COMMIT;

3.13.57 WITH AS
Description
The WITH AS clause defines a SQL fragment, which will be used by the entire SQL
statement.
This makes SQL statements more readable. A table storing SQL fragments is
different from a base table. It is a virtual table, also called a view. The definition
and data corresponding to the view is not stored in the database but still in the
base table. If data in the base table changes, the data in the view changes
accordingly.

Syntax
WITH { table_name AS select_statement1 }[ , ...] select_statement2

Parameter Description
● table_name
Specifies the name of a user-defined table that stores SQL fragments.
● select_statement1
Specifies the SELECT statement that queries data from a base table.
● select_statement2
Specifies the SELECT statement that queries data from a user-defined table
that stores SQL fragments.

Examples
Use WITH AS to query data.
-- Delete the education table.
DROP TABLE IF EXISTS education;
-- Create the education table.
CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school
VARCHAR(64),graduate_date DATETIME, education_note VARCHAR(70));
-- Insert record 1 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(10,'Doctor','Xidian University','2017-07-06 12:00:00','211');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 492


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Insert record 2 into the education table.


INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(11,'Master','Northwestern Polytechnical University','2017-07-06 12:00:00','211&985');
-- Insert record 3 into the education table.
INSERT INTO education(staff_id,highest_degree,graduate_school,graduate_date,education_note)
VALUES(12,'Scholar','Xi'an University of Architecture and Technology','2017-07-06 12:00:00','not 211 or 985');
-- Commit the transaction.
COMMIT;
-- Use WITH AS to query data.
WITH tmp AS (SELECT staff_id, highest_degree FROM education) SELECT * FROM tmp;

3.14 Stored Procedure


A stored procedure is a set of SQL statements used for specific functions.
Generally, it is used for report statistics and data migration.
● If the name of a stored procedure is the same as that of a system function,
the database preferentially invokes the system function. To make the stored
procedure preferential, configure it in the $GSDB_DATA/cfg/udf.ini file in the
format of user_name.procedure_name. Only one stored procedure can be
written in a line, and no comments are allowed. The stored procedure name is
case-sensitive during the configuration in udf.ini.
● The permission for the udf.ini file must be limited to users in the database
user group dbgrp. The permission is 600.

3.14.1 Examples
This example demonstrates the entire process of using a stored procedure,
including creating, calling, and deleting stored a procedure.

Statements
● Use a stored procedure without parameters.
-- Prepare a basic table for a stored procedure.
-- Delete the duplicate temporary table if any.
DROP TABLE IF EXISTS table_temp;
-- Create a temporary table as a basic table.
CREATE TABLE table_temp(f1 INT, f2 VARCHAR2(20));

NOTICE

Stored procedures and functions are stored in the same system catalog. If a
stored procedure to be created has the same name as an existing user-
defined function, creating the stored procedure will fail. Therefore, before
creating a stored procedure, you need to delete the user-defined function with
the same name.

-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS p_no_param;
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS p_no_param;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 493


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

NOTICE

In the declaration statement of a stored procedure, the slash (/) indicates the
end of the statement and cannot be omitted. In addition, the slash (/) must
be in a separate line.

-- Create a stored procedure without parameters.


CREATE OR REPLACE PROCEDURE p_no_param IS
BEGIN
INSERT INTO table_temp VALUES(1,'xxx');
COMMIT;
END;
/
-- Run CALL to execute the stored procedure.
CALL p_no_param;
-- Run EXEC to execute the stored procedure.
EXEC p_no_param;
-- Query data in the temporary table.
SELECT * FROM table_temp;

F1 F2
------------ --------------------
1 xxx
1 xxx

2 rows fetched.
-- Delete the stored procedure.
DROP PROCEDURE p_no_param;
● Use a stored procedure with IN parameters.
-- Prepare a basic table for a stored procedure.
-- Delete the duplicate temporary table if any.
DROP TABLE IF EXISTS table_temp;
-- Create a temporary table as a basic table.
CREATE TABLE table_temp(f1 INT, f2 INT, f3 VARCHAR2(20));

NOTICE

Stored procedures and functions are stored in the same system catalog. If a
stored procedure to be created has the same name as an existing user-
defined function, creating the stored procedure will fail. Therefore, before
creating a stored procedure, you need to delete the user-defined function with
the same name.

-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS p_with_param;
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS p_with_param;

NOTICE

In the declaration statement of a stored procedure, the slash (/) indicates the
end of the statement and cannot be omitted. In addition, the slash (/) must
be in a separate line.

-- Create a stored procedure. The first and second parameters have the default value 0. The third
parameter does not have a default value.
CREATE OR REPLACE PROCEDURE p_with_param(param1 INT := 0, param2 INT DEFAULT 0,param3
VARCHAR2) IS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 494


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

BEGIN
INSERT INTO table_temp VALUES(param1,param2,param3);
COMMIT;
END;
/
-- Specify the values of all input parameters when executing the stored procedure.
-- Run CALL to execute the stored procedure.
CALL p_with_param(1,1,'xxx');
-- Run EXEC to execute the stored procedure.
EXEC p_with_param(1,1,'xxxx');

NOTICE

You must specify values for parameters that do not have a default value. If a
parameter has neither a default value nor a specified value, an error is
returned.

-- When executing a stored procedure, specify a value only for parameters that do not have a default
value.
-- Run CALL to execute the stored procedure.
CALL p_with_param(param3=>'yyy');
-- Run EXEC to execute the stored procedure.
EXEC p_with_param(param3=>'yyyy');
-- Query data in the temporary table.
SELECT * FROM table_temp;

F1 F2 F3
------------ ------------ --------------------
1 1 xxx
1 1 xxxx
0 0 yyy
0 0 yyyy

4 rows fetched.
-- Delete the stored procedure.
DROP PROCEDURE p_with_param;

● Use a stored procedure with OUT and IN OUT parameters.


-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS p_with_outParam;
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS p_with_outParam;
-- Create the p_with_outParam stored procedure.
CREATE OR REPLACE PROCEDURE p_with_outParam(param1 IN INT , param2 OUT INT ,param3 IN
OUT VARCHAR )
IS
BEGIN
param2 :=3;
param3 :='xxx';
DBMS_OUTPUT.PUT_LINE('input variable: '||param1);
DBMS_OUTPUT.PUT_LINE('out variable: '||param2);
DBMS_OUTPUT.PUT_LINE('in out variable: '||param3);
COMMIT;
END;
/

NOTICE

When using the DBMS_OUTPUT.PUT_LINE function to export logs, set


serveroutput to on. The default value is off.
SET serveroutput ON

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 495


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Invoke the p_with_outParam stored procedure.


Declare
param1 int :=1;
param2 int :=1;
param3 varchar(100) :='YYY';
begin
p_with_outParam(param1, param2, param3);
DBMS_OUTPUT.PUT_LINE(param1);
DBMS_OUTPUT.PUT_LINE(param2);
DBMS_OUTPUT.PUT_LINE(param3);
end;
/
-- Delete the p_with_outParam stored procedure.
DROP PROCEDURE IF EXISTS p_with_outParam;

3.14.2 Executing a Stored Procedure


Description
CALL | EXEC executes a stored procedure.

Precautions
● If the name of a user-defined stored procedure is the same as that of a
system function, the database preferentially invokes the system function. To
make the stored procedure preferential, configure it in the $GSDB_DATA/cfg/
udf.ini file in the format of user_name.procedure_name. The configuration
takes effect only after the database is restarted.
● The permission for the udf.ini file must be limited to users in the database
user group dbgrp. The permission is 600.
● You can specify values for all parameters in the parameter list or use => to
specify values for some parameters. If a parameter has neither a default value
nor a specified value, an error is returned.
● You are not allowed to assign constants to an IN OUT or OUT parameter.
● You are advised to query the SYS_PROCS view for the ID of the record that
causes an error.
● To execute a stored procedure (including a customized function) without
parameters, you can directly specify the stored procedure name or customized
function name without parentheses.
● You can use a semicolon (;) or a slash (/) as a terminator. However, the two
terminators cannot be used together. If they are used together, an error is
reported.

Syntax
{ CALL | EXEC } [schema_name.]procedure_name[(param[,...])];

Parameter Description
● CALL
Revokes a stored procedure.
● EXEC
Executes a stored procedure.
● schema_name

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 496


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies the schema to which a stored procedure belongs.


● procedure_name
Specifies the name of a stored procedure to be executed.
● param
Specifies stored procedure parameters. If a stored procedure does not contain
parameters, you can omit parentheses when you specify the stored procedure
to be executed.

Examples
● Use a stored procedure without parameters.
-- Prepare a basic table for a stored procedure.
-- Delete the duplicate temporary table if any.
DROP TABLE IF EXISTS table_temp;
-- Create a temporary table as a basic table.
CREATE TABLE table_temp(f1 INT, f2 VARCHAR2(20));

NOTICE

Stored procedures and functions are stored in the same system catalog. If a
stored procedure to be created has the same name as an existing user-
defined function, creating the stored procedure will fail. Therefore, before
creating a stored procedure, you need to delete the user-defined function with
the same name.

-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS p_no_param;
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS p_no_param;

NOTICE

In the declaration statement of a stored procedure, the slash (/) indicates the
end of the statement and cannot be omitted. In addition, the slash (/) must
be in a separate line.

-- Create a stored procedure without parameters.


CREATE OR REPLACE PROCEDURE p_no_param IS
BEGIN
INSERT INTO table_temp VALUES(1,'xxx');
COMMIT;
END;
/
-- Run CALL to execute the stored procedure.
CALL p_no_param;
-- Run EXEC to execute the stored procedure.
EXEC p_no_param;
-- Query data in the temporary table.
SELECT * FROM table_temp;

F1 F2
------------ --------------------
1 xxx
1 xxx

2 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 497


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete the stored procedure.


DROP PROCEDURE p_no_param;
● Use a stored procedure with IN parameters.
-- Prepare a basic table for a stored procedure.
-- Delete the duplicate temporary table if any.
DROP TABLE IF EXISTS table_temp;
-- Create a temporary table as a basic table.
CREATE TABLE table_temp(f1 INT, f2 INT, f3 VARCHAR2(20));

NOTICE

Stored procedures and functions are stored in the same system catalog. If a
stored procedure to be created has the same name as an existing user-
defined function, creating the stored procedure will fail. Therefore, before
creating a stored procedure, you need to delete the user-defined function with
the same name.

-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS p_with_param;
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS p_with_param;

NOTICE

In the declaration statement of a stored procedure, the slash (/) indicates the
end of the statement and cannot be omitted. In addition, the slash (/) must
be in a separate line.

-- Create a stored procedure. The first and second parameters have the default value 0. The third
parameter does not have a default value.
CREATE OR REPLACE PROCEDURE p_with_param(param1 INT := 0, param2 INT DEFAULT 0,param3
VARCHAR2) IS
BEGIN
INSERT INTO table_temp VALUES(param1,param2,param3);
COMMIT;
END;
/
-- Specify the values of all input parameters when executing the stored procedure.
-- Run CALL to execute the stored procedure.
CALL p_with_param(1,1,'xxx');
-- Run EXEC to execute the stored procedure.
EXEC p_with_param(1,1,'xxxx');

NOTICE

You must specify values for parameters that do not have a default value. If a
parameter has neither a default value nor a specified value, an error is
returned.

-- When executing a stored procedure, specify a value only for parameters that do not have a default
value.
-- Run CALL to execute the stored procedure.
CALL p_with_param(param3=>'yyy');
-- Run EXEC to execute the stored procedure.
EXEC p_with_param(param3=>'yyyy');
-- Query data in the temporary table.
SELECT * FROM table_temp;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 498


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

F1 F2 F3
------------ ------------ --------------------
1 1 xxx
1 1 xxxx
0 0 yyy
0 0 yyyy

4 rows fetched.
-- Delete the stored procedure.
DROP PROCEDURE p_with_param;

3.14.3 Deleting a Stored Procedure


Description
DROP PROCEDURE deletes a stored procedure.

Precautions
● If you are sure that the stored procedure to be deleted exists, IF EXISTS is not
required. Otherwise, you are advised to use DROP PROCEDURE IF EXISTS
procedure_name; to avoid a nonexistence error. Common users cannot delete
the objects of system users.
● You can use a semicolon (;) or a slash (/) as a terminator. However, the two
terminators cannot be used together. If they are used together, an error is
reported.

Syntax
DROP PROCEDURE [ IF EXISTS ] [schema_name.]procedure_name;

Parameter Description
● IF EXISTS
Does not throw an error if a stored procedure to be deleted does not exist.
● schema_name
Specifies the schema to which a stored procedure belongs.
● procedure_name
Specifies the name of a stored procedure to be deleted.

Examples
DROP PROCEDURE IF EXISTS p_no_param;

3.14.4 Creating a Stored Procedure


Description
CREATE PROCEDURE creates a stored procedure. If the stored procedure to be
created already exists, CREATE OR REPLACE updates the existing stored
procedure and does not create a new one.
After a procedure body (stored procedure, user-defined function, or trigger) is
successfully created, OBJECT_ID$ is invoked to allocate an ID to the new

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 499


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

procedure body through a global sequence. The ID uniquely identifies a procedure


body in the system catalog. The global ID allocated by invoking OBJECT_ID$ starts
from 1000 and increases by 1.

The global sequence SEQ_PROC_001 is created during system initialization. This


sequence allocates a unique sequence number to a stored procedure for invoking.
The sequence number starts from 30000 and increases by 1.

Precautions
Stored procedures and user-defined functions share the same system catalog.
Therefore, do not use the same name for a stored procedure and a user-defined
function. Common users cannot create objects of system users.

The statement for creating a stored procedure, anonymous block, user-defined


function, or trigger must end with a slash (/).

Syntax
CREATE [ OR REPLACE ] PROCEDURE [ IF NOT EXISTS ] [schema_name.]procedure_name(args_list)
{ IS | AS }
[ param_list ]
BEGIN
statement;
END;
/

Parameter Description
● OR REPLACE
Replaces an existing stored procedure.
● IF NOT EXIST
Does not throw an error if a stored procedure to be created exists.
● procedure_name
Specifies the name of a stored procedure to be created.
● schema_name
Specifies the schema to which a stored procedure belongs.
● args_list
Specifies a list of parameters in a stored procedure. The list includes input
parameters (IN), output parameters (OUT), and input and output parameter
(IN OUT). A parameter can be one of them. A default value can be specified
for an input parameter.
– IN is the default mode of a parameter. In this mode, a parameter already
has a value when the procedure is running and the value does not
change in the procedure body.
– A parameter in OUT mode is assigned with a value only within a
procedure body. The parameter passes a value back to the procedure that
invokes it.
– A parameter in IN OUT mode passes values to the procedure it locates
and also passes values back to the procedure that invokes it.
● param_list

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 500


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies new parameters and their default values. The value can be empty.
For details about the variable declaration syntax, see DECLARE Syntax.
● statement
Specifies the statement of a stored procedure. You are not allowed to leave
this parameter empty because an error will be reported if it is empty. You can
use basic, dynamic, control, exception, or other statements. For details about
basic statements, see Basic Statements; dynamic statements, see Dynamic
Statements; control statements, see Control Statements; other statements,
see Other Statements; user-defined functions, see User-defined Functions;
and stored procedures, see Creating a Stored Procedure.

Examples
-- Delete the existing stored procedure with the same name.
DROP PROCEDURE IF EXISTS Zenith_Test_003;
-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS Zenith_Test_003;
-- Create the stored procedure.
CREATE OR REPLACE PROCEDURE Zenith_Test_003(param1 IN VARCHAR2,param2 IN VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello Zenith:'||param1||','||param2);
END Zenith_Test_003;
/

3.14.5 Data Type


The following table describes the data types supported by stored procedures.

Data Type Type Keyword Description

GS_TYPE_INTEGER int 4-byte signed integer. For details,


see "INTEGER" in Numeric Data
Types.

GS_TYPE_BOOL bool/boolean For details, see "BOOLEAN" in


Numeric Data Types.

GS_TYPE_BIGINT bigint 8-byte signed integer. For details,


see "INTEGER" in Numeric Data
Types.

GS_TYPE_NUMBER number/decimal High-precision data. You can


GS_TYPE_DECIMAL specify the precision and scale. For
details, see "High-Precision Data
Types" in Numeric Data Types.

GS_TYPE_REAL float/double/real 8-byte floating point number. For


details, see "FLOATING POINT" in
Numeric Data Types.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 501


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Data Type Type Keyword Description

GS_TYPE_CHAR char Fixed-length string. If the length of


an input string is less than the
specified length, the string is
padded with spaces. If the string
length is not specified , the default
length 1 is used.

GS_TYPE_VARCHAR varchar/varchar2 Non-fixed-length char with a


maximum of 32767 characters and
the string constant cannot exceed
16 KB.

GS_TYPE_DATE date Date value. For details, see "DATE"


in Numeric Data Types.

GS_TYPE_TIMESTAMP timestamp Date value. For details, see "DATE"


in Numeric Data Types.

● GS_TYPE_BINARY ● binary ● Binary and varbinary data is


● GS_TYPE_VARBINA ● varbinary supported.
RY ● clob ● If CLOB data is used as the input
● GS_TYPE_CLOB or output argument of a stored
● blob procedure or a user-defined
● GS_TYPE_BLOB function, the data size must be
no greater than 32 KB. The
string constant cannot exceed
16 KB.
● External CLOB data of a stored
procedure cannot be used as
arguments for the stored
procedure.
● External CLOB data of a user-
defined function cannot be used
as arguments for the function.
● If a CLOB data interacts with
other SQL statements, the data
size must be no greater than 8
KB.
● The maximum size of a BLOB
data in a stored procedure is 8
KB.

GS_TYPE_CURSOR sys_refcursor System cursor variable. For details,


see Cursors.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 502


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Data Type Type Keyword Description

N/A record Record variable to obtain and


return a specified record.
● %rowtype cannot be used in
argument declaration of stored
procedures or user-defined
functions.

3.14.6 DECLARE Syntax


Description
DECLARE declares the variables used by a stored procedure.

Precautions
● Variables of stored procedures must be declared before being used. However,
there is a special case. That is, if the FOR loop is used to traverse the cursor,
the index_name variable in the FOR loop can be used without being declared.
● Currently, DECLARE in GaussDB 100 is used to define variables. In the
implementation blocks of functions, stored procedures, anonymous blocks,
and triggers, variables declared in stored procedures have the highest priority.
● Names of variables declared in a stored procedure must be valid identifiers
and cannot be keywords or numbers.
● For details about the data types supported by common variables, see Data
Type. You can specify a default value for a common variable.
● To declare a system cursor variable, use the SYS_REFCURSOR keyword. To
declare a common cursor variable, run TYPE type_name1 IS REF CURSOR to
declare a cursor type, and then declare a cursor variable of this type.
● Currently, cursor variables are implemented based on weak data types. That
is, the RETURN return_type clause cannot be used to specify the data type of
the returned result in the definition statement of a cursor type. Instead, the
data type of the row opened by the cursor is used.
● When a record type is declared, the data type of each column can be a basic
data type or a RECORD type. The SYS_REFCURSOR type is not supported.
● The TYPE statement only declares a cursor or record type and does not
generate variables. A variable is generated only after a variable of the
declared type is declared.

Syntax
● Declare a common variable and its default value.
DECLARE variant_name data_type [ { { := } | DEFAULT } default_expr];
● Declare a system cursor variable.
DECLARE cursor_name SYS_REFCURSOR;
● Declare a cursor type and a variable of this type.
DECLARE TYPE type_name1 IS REF CURSOR;
ref_cursor_name type_name1;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 503


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Declare a record type and declare a variable of this type.


DECLARE TYPE type_name2 IS RECORD ( field_name data_type [,...] );
rec_name type_name2;

Parameter Description
● variant_name
Specifies the name of a variable to be declared.
● data_type
Specifies the data type of a variable. For details about the available types, see
Data Type.
● DEFAULT default_expr
Specifies the default value of a variable. The default value can be a constant
or an expression.
● cursor_name
Specifies the name of a system cursor variable to be declared.
● SYS_REFCURSOR
Specifies that a cursor variable to be declared is a system cursor variable.
● TYPE type_name1 IS REF CURSOR
Declares a cursor type. type_name1 indicates the name of the type to be
declared.
● ref_cursor_name type_name1
Declares a cursor variable of the declared type. This parameter is used
together with TYPE type_name1 IS REF CURSOR.
● TYPE type_name2 IS RECORD (field_name data_type [,...])
Declares a record type. type_name2 indicates the name of the type to be
declared.
● rec_name type_name2
Declares a record variable of the declared type. This parameter is used
together with TYPE type_name2 IS RECORD (field_name data_type [,...]).

Examples
● Prepare data (create the test table and insert a record into it).
-- Delete the existing t1 table.
DROP TABLE IF EXISTS test;
-- Create the test table.
CREATE TABLE test(f_int1 INTEGER,f_int2 INTEGER, f_int3 INTEGER, f_bigint1 BIGINT, f_bigint2
BIGINT, f_bigint3 BIGINT, f_bool1 INTEGER, f_bool2 INTEGER, f_num1 NUMBER(38, 0),f_num2
NUMBER(38, 0), f_dec1 DECIMAL(38, 0), f_dec2 DECIMAL(38, 0), f_num10 NUMBER(38, 10), f_dec10
DECIMAL(38, 10), f_float FLOAT,f_double DOUBLE, f_real REAL, f_char1 CHAR(128),f_char2
CHAR(128), f_varchar1 VARCHAR(512),f_varchar2 VARCHAR2(512), f_date1 DATE, f_date2 DATE,
f_time DATE, f_timestamp TIMESTAMP);
-- Insert a record into the test table.
INSERT INTO test
VALUES(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,'a','b','c','d','2017-01-01','2017-01-01','2017-01-01','201
7-01-01');
-- Commit the transaction.
COMMIT;

● Declare a common variable (in bold).


DECLARE
f_int1 INTEGER;
f_int2 INTEGER;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 504


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

f_int3 INTEGER;
f_bigint1 BIGINT;
f_bigint2 BIGINT;
f_bigint3 BIGINT;
f_bool1 INTEGER;
f_bool2 INTEGER;
f_num1 NUMBER(38, 0);
f_num2 NUMBER(38, 0);
f_dec1 DECIMAL(38, 0);
f_dec2 DECIMAL(38, 0);
f_num10 NUMBER(38, 10);
f_dec10 DECIMAL(38, 10);
f_float FLOAT;
f_double DOUBLE;
f_real REAL;
f_char1 CHAR(128);
f_char2 CHAR(128);
f_varchar1 VARCHAR(512);
f_varchar2 VARCHAR2(512);
f_date1 DATE;
f_date2 DATE;
f_time DATE;
f_timestamp TIMESTAMP;
BEGIN
SELECT * INTO
f_int1,f_int2,f_int3,f_bigint1,f_bigint2,f_bigint3,f_bool1,f_bool2,f_num1,f_num2,f_dec1,f_dec2,f_num10,f
_dec10,f_float,f_double,f_real,f_char1,f_char2,f_varchar1,f_varchar2,f_date1,f_date2,f_time,f_timestamp
from test;
DBMS_OUTPUT.PUT_LINE('f_int1 is ' || f_int1 );
DBMS_OUTPUT.PUT_LINE('f_int2 is ' || f_int2 );
DBMS_OUTPUT.PUT_LINE('f_int3 is ' || f_int3 );
DBMS_OUTPUT.PUT_LINE('f_bigint1 is ' || f_bigint1 );
DBMS_OUTPUT.PUT_LINE('f_bigint2 is ' || f_bigint2 );
DBMS_OUTPUT.PUT_LINE('f_bigint3 is ' || f_bigint3 );
DBMS_OUTPUT.PUT_LINE('f_bool1 is ' || f_bool1 );
DBMS_OUTPUT.PUT_LINE('f_bool2 is ' || f_bool2 );
DBMS_OUTPUT.PUT_LINE('f_num1 is ' || f_num1 );
DBMS_OUTPUT.PUT_LINE('f_num2 is ' || f_num2 );
DBMS_OUTPUT.PUT_LINE('f_dec1 is ' || f_dec1 );
DBMS_OUTPUT.PUT_LINE('f_dec2 is ' || f_dec2 );
DBMS_OUTPUT.PUT_LINE('f_num10 is ' || f_num10 );
DBMS_OUTPUT.PUT_LINE('f_dec10 is ' || f_dec10 );
DBMS_OUTPUT.PUT_LINE('f_float is ' || f_float );
DBMS_OUTPUT.PUT_LINE('f_double is ' || f_double );
DBMS_OUTPUT.PUT_LINE('f_real is ' || f_real );
DBMS_OUTPUT.PUT_LINE('f_char1 is ' || f_char1 );
DBMS_OUTPUT.PUT_LINE('f_char2 is ' || f_char2 );
DBMS_OUTPUT.PUT_LINE('f_varchar1 is ' || f_varchar1 );
DBMS_OUTPUT.PUT_LINE('f_varchar2 is ' || f_varchar2 );
DBMS_OUTPUT.PUT_LINE('f_date1 is ' || f_date1 );
DBMS_OUTPUT.PUT_LINE('f_date2 is ' || f_date2 );
DBMS_OUTPUT.PUT_LINE('f_time is ' || f_time );
DBMS_OUTPUT.PUT_LINE('f_timestamp is ' || f_timestamp);
END;
/

● Declare a system cursor variable (in bold).


DECLARE
b INT;
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT f_int1 FROM test;
FETCH c1 INTO b;
DBMS_OUTPUT.PUT_LINE('result is:' || b);
FETCH c1 INTO b;
DBMS_OUTPUT.PUT_LINE('result is:' || b);
CLOSE c1;
END;
/

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 505


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Declare a cursor type tcur and a cursor variable cursor_k (in bold) of this
type.
DECLARE
TYPE tcur IS REF CURSOR;
cursor_k tcur;
rec test%rowtype;
BEGIN
OPEN cursor_k FOR SELECT * FROM test;
FETCH cursor_k INTO rec;
CLOSE cursor_k;
END;
/

● Declare a record type item_def and a record variable item (in bold) of this
type.
DECLARE
TYPE item_def IS RECORD (
f_int1 integer,
f_int2 integer,
f_int3 integer,
f_bigint1 bigint,
f_bigint2 bigint,
f_bigint3 bigint,
f_bool1 integer,
f_bool2 integer,
f_num1 number(38, 0),
f_num2 number(38, 0),
f_dec1 DECIMAL(38, 0),
f_dec2 DECIMAL(38, 0),
f_num10 number(38, 10),
f_dec10 decimal(38, 10),
f_float float,
f_double double,
f_real real,
f_char1 char(128),
f_char2 char(128),
f_varchar1 varchar(512),
f_varchar2 varchar2(512),
f_date1 date,
f_date2 date,
f_time date,
f_timestamp timestamp
);
item item_def;
BEGIN
SELECT * INTO item FROM test;
DBMS_OUTPUT.PUT_LINE('item.f_int1 is ' || item.f_int1 );
DBMS_OUTPUT.PUT_LINE('item.f_int2 is ' || item.f_int2 );
DBMS_OUTPUT.PUT_LINE('item.f_int3 is ' || item.f_int3 );
DBMS_OUTPUT.PUT_LINE('item.f_bigint1 is ' || item.f_bigint1 );
DBMS_OUTPUT.PUT_LINE('item.f_bigint2 is ' || item.f_bigint2 );
DBMS_OUTPUT.PUT_LINE('item.f_bigint3 is ' || item.f_bigint3 );
DBMS_OUTPUT.PUT_LINE('item.f_bool1 is ' || item.f_bool1 );
DBMS_OUTPUT.PUT_LINE('item.f_bool2 is ' || item.f_bool2 );
DBMS_OUTPUT.PUT_LINE('item.f_num1 is ' || item.f_num1 );
DBMS_OUTPUT.PUT_LINE('item.f_num2 is ' || item.f_num2 );
DBMS_OUTPUT.PUT_LINE('item.f_dec1 is ' || item.f_dec1 );
DBMS_OUTPUT.PUT_LINE('item.f_dec2 is ' || item.f_dec2 );
DBMS_OUTPUT.PUT_LINE('item.f_num10 is ' || item.f_num10 );
DBMS_OUTPUT.PUT_LINE('item.f_dec10 is ' || item.f_dec10 );
DBMS_OUTPUT.PUT_LINE('item.f_float is ' || item.f_float );
DBMS_OUTPUT.PUT_LINE('item.f_double is ' || item.f_double );
DBMS_OUTPUT.PUT_LINE('item.f_real is ' || item.f_real );
DBMS_OUTPUT.PUT_LINE('item.f_char1 is ' || item.f_char1 );
DBMS_OUTPUT.PUT_LINE('item.f_char2 is ' || item.f_char2 );
DBMS_OUTPUT.PUT_LINE('item.f_varchar1 is ' || item.f_varchar1 );
DBMS_OUTPUT.PUT_LINE('item.f_varchar2 is ' || item.f_varchar2 );
DBMS_OUTPUT.PUT_LINE('item.f_date1 is ' || item.f_date1 );
DBMS_OUTPUT.PUT_LINE('item.f_date2 is ' || item.f_date2 );

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 506


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DBMS_OUTPUT.PUT_LINE('item.f_time is ' || item.f_time );


DBMS_OUTPUT.PUT_LINE('item.f_timestamp is ' || item.f_timestamp);
END;
/

3.14.7 Basic Statements


Description
Stored procedures support two types of basic statements: assignment statements
and SQL statements.

Assignment Statements
● Syntax
-- Assign a value to a declared variable.
variant_name := variant_expr;
● Parameter Description
– variant_name
Specifies the name of a declared variable. The value must be a variable or
input parameter declared in a stored procedure.
– variant_expr
Specifies an expression used to assign a value to a declared variable. The
expression can be a common expression, an expression involving
functions and variables, or a CASE or WHEN expression.
Variables in an expression match the variables declared in stored
procedures first, and then match table or column names. Therefore,
ensure that names of variables declared in the stored procedure are
different from the table and column names. Functions in an expression
match built-in functions first, then the functions in the advanced
package, and finally the user-defined functions. Therefore, ensure that
names of user-defined functions are different from those of built-in
functions and functions in the advanced package.
● Examples
– Assign a value to a variable by using a common expression. (in bold)
CREATE OR REPLACE PROCEDURE Zenith_Test_004(param1 in out varchar2)
IS
tmp varchar2(20) := '12345678';
BEGIN
param1 := param1 || tmp;
END Zenith_Test_004;
/

– Assign a value to a variable by using an expression involving functions


and variables. (in bold)
CREATE OR REPLACE FUNCTION DATEADD( datepart VARCHAR2, num NUMBER, indate DATE)
RETURN DATE IS
Result DATE;
v_sql VARCHAR2(1000);
v_datepart VARCHAR2(30);
v_ms VARCHAR2(13);
BEGIN
v_datepart := lower(datepart);
CASE
WHEN v_datepart IN ('year','yy','y') THEN
v_sql := 'SELECT :1 + interval '''||num||''' year FROM SYS_DUMMY';
ELSE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 507


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

RAISE_APPLICATION_ERROR(-20001, ''''||datepart||''' is not a recognized dateadd option.' );


END CASE;
EXECUTE IMMEDIATE v_sql into Result using indate;
return(Result);
END DATEADD;
/

– Assign a value to a variable by using a CASE or WHEN expression. (in


bold)
DECLARE
class CHAR(1) := 'S';
age VARCHAR2(15);
BEGIN
age := CASE class
WHEN 'S' THEN '3-4 years'
WHEN 'M' THEN '4-5 years'
WHEN 'P' THEN '5-6 years'
ELSE 'No such class'
END ;
DBMS_OUTPUT.PUT_LINE(age);
END;
/

SQL Statements
Currently, only the UPDATE, INSERT, DELETE, MERGE, SELECT ... INTO, COMMIT,
and ROLLBACK statements in stored procedures can be immediately executed.
Other four SQL statements can be executed only after the EXECUTE IMMEDIATE
statement is executed. Otherwise, an error occurs during stored procedure
compiling. For details about dynamic SQL statements, see Dynamic Statements.

● Precautions
– Variables in DML statements match the variables declared in stored
procedures first and then match column names. Therefore, ensure that
variable names are different from the column names.
– When you run the SELECT ... INTO statement, if variant_list is used to
store data after the INTO keyword, the number of columns in column_list
after the SELECT keyword must be the same as the number of variables
in variant_list. If a record variable instead of variant_list is used to store
data after the INTO keyword, the preceding restriction becomes invalid.
In addition, if more than one record is returned, the
"ERR_TOO_MANY_ROWS" error message is displayed when you assign
values using INTO {variant_list | record_variant}; if no record is returned,
the "NO_DATA_FOUND" error message is displayed when you assign
values using INTO {variant_list | record_variant}.
– If the variable name in a DML statement is the same as a table or
column name, variables except the following ones in the DML statement
are replaced with the variables declared in stored procedures:

▪ table_name following the keywords UPDATE, INSERT INTO, DELETE


FROM, SELECT FROM, MERGE INTO, and USING

▪ alias following the AS keyword

▪ column_name following the UPDATE SET keyword

▪ column_list following the INSERT keyword in the SELECT...INTO


statement

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 508


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– Variables in SQL statements match the variables declared in stored


procedures first, and then match table or column names. Therefore,
ensure that names of variables declared in the stored procedure are
different from the table and column names.
– Functions in SQL statements match built-in functions first, then the
functions in the advanced package, and finally the user-defined functions.
Therefore, ensure that names of user-defined functions are different from
those of built-in functions and functions in the advanced package.
● Syntax
– UPDATE statement. For details, see UPDATE.
UPDATE table_name SET column = expression [ WHERE { CURRENT OF cursor_name |
condition } ];

– INSERT statement. For details, see INSERT.


INSERT INTO table_name { [ ( column_list ) ] VALUES ( values_list ) | select_statement };

– DELETE statement. For details, see DELETE.


DELETE FROM table_name [ WHERE { CURRENT OF cursor_name | condition } ];

– MERGE statement. For details, see MERGE.


MERGE INTO table_name USING table_name
ON condition
WHEN MATCHED THEN update_clause
WHEN NOT MATCHED THEN insert_clause
[ LIMIT limit_num OFFSET offset_num ];

– SELECT ... INTO statement.


SELECT { * | column_list } INTO { variant_list | record_variant } FROM table_name
[ rest_of_select_statment ];

▪ rest_of_select_statment clause. For details about the SELECT


statement, see SELECT.
[WHERE { condition | [ NOT ] EXISTS ( correlated subquery ) } ]
[[START WITH condition ] CONNECT BY [ NOCYCLE ] [ PRIOR ] condition ]
[GROUP BY { column_name | number } [ , ... ] ]
[HAVING condition [ , ... ] ]
[{ UNION [ ALL ] } select ]
[ORDER BY { column_name | number } [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
[, ... ] ]
[LIMIT [ offset_expr, ] count_expr | LIMIT count_expr OFFSET offset_expr | OFFSET
offset_expr [ LIMIT count_expr ] ]

– COMMIT statement. For details, see COMMIT.


COMMIT;

– ROLLBACK statement. For details, see ROLLBACK.


ROLLBACK;

● Examples
– Prepare data (create the T_PROC_1 table and insert data into it).
-- Delete the existing T_PROC_1 table.
DROP TABLE IF EXISTS T_PROC_1;
-- Create the T_PROC_1 table.
CREATE TABLE T_PROC_1 (f_int1 INTEGER,f_int2 INTEGER, f_int3 INTEGER, f_bigint1 BIGINT,
f_bigint2 BIGINT, f_bigint3 BIGINT, f_bool1 INTEGER, f_bool2 INTEGER, f_num1 NUMBER(38,
0),f_num2 NUMBER(38, 0), f_dec1 DECIMAL(38, 0), f_dec2 DECIMAL(38, 0), f_num10
NUMBER(38, 10), f_dec10 DECIMAL(38, 10), f_float FLOAT,f_double DOUBLE, f_real REAL,
f_char1 CHAR(128),f_char2 CHAR(128), f_varchar1 VARCHAR(512),f_varchar2 VARCHAR2(512),
f_date1 DATE, f_date2 DATE, f_time DATE, f_timestamp TIMESTAMP);
-- Insert data into the T_PROC_1 table.
INSERT INTO T_PROC_1
VALUES(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,'a','b','c','d','2017-01-01','2017-01-01','2017-01-01
','2017-01-01');
-- Commit the transaction.
COMMIT;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 509


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– UPDATE statement (in bold)


DECLARE
A INT;
B INT;
BEGIN
UPDATE T_PROC_1 SET F_INT1 = 2 WHERE F_INT1 = 1;
A := SQL%ROWCOUNT;
EXECUTE IMMEDIATE 'UPDATE T_PROC_1 SET F_INT1 = 3 WHERE F_INT1 = 2';
B := SQL%ROWCOUNT;
INSERT INTO T_PROC_1(F_INT1,F_INT2) VALUES(A,B);
COMMIT;
END;
/

– INSERT statement (in bold)


DECLARE
A INT;
B INT;
BEGIN
INSERT INTO T_PROC_1(F_INT1) VALUES(12);
INSERT INTO T_PROC_1(F_INT1) VALUES(12);
A := SQL%ROWCOUNT;
EXECUTE IMMEDIATE 'DELETE FROM T_PROC_1';
B := SQL%ROWCOUNT;
INSERT INTO T_PROC_1(F_INT1,F_INT2) VALUES(A,B);
ROLLBACK;
END;
/

– DELETE statement (in bold)


DECLARE
a INT;
BEGIN
a := 1;
UPDATE T_PROC_1 SET f_int1 = f_int1 + 11 WHERE f_int1 = 1;
DELETE FROM T_PROC_1 WHERE f_int1 = 1;
SELECT f_int1 INTO a FROM T_PROC_1 LIMIT 1;
COMMIT;
DBMS_OUTPUT.PUT_LINE('result is:' || a);
END;
/

– MERGE statement (in bold)


DECLARE
A INT;
B INT;
BEGIN
MERGE INTO T_PROC_1 USING SYS_DUMMY ON (1=1) WHEN MATCHED THEN UPDATE
SET F_INT1 = 2;
A := SQL%ROWCOUNT;
EXECUTE IMMEDIATE 'MERGE INTO T_PROC_1 USING SYS_DUMMY ON (1=0) WHEN NOT
MATCHED THEN INSERT (F_INT1) VALUES(1)';
B := SQL%ROWCOUNT;
INSERT INTO T_PROC_1(F_INT1,F_INT2) VALUES(A,B);
END;
/

– SELECT statement (in bold)


DECLARE
a INT;
BEGIN
a := 1;
UPDATE T_PROC_1 SET f_int1 = f_int1 + 11 WHERE f_int1 = 1;
DELETE FROM T_PROC_1 WHERE f_int1 = 1;
SELECT f_int1 INTO a FROM T_PROC_1 LIMIT 1;
COMMIT;
DBMS_OUTPUT.PUT_LINE('result is:' || a);
END;
/

– COMMIT and ROLLBACK statements (in bold)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 510


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DECLARE
a INT;
BEGIN
MERGE INTO T_PROC_1 USING SYS_DUMMY ON (f_int1 = 2) WHEN NOT MATCHED THEN
INSERT (f_int1) VALUES(2);
SELECT f_int1 INTO a FROM T_PROC_1 LIMIT 1;
IF (a = 2) THEN
COMMIT;
ELSE
ROLLBACK;
END IF;
END;
/

3.14.8 Dynamic Statements


Function
Dynamic statements are SQL statements that can be dynamically built up. They
can be compiled and executed only in the execution phase.

Syntax
EXECUTE IMMEDIATE sql_statement [ INTO variant_name[, ...] ] [ USING { [IN] [OUT] variant_name }
[, ...] ]

Parameter Description
● EXECUTE IMMEDIATE
Dynamically issues SQL statements.
● sql_statement
Specifies the SQL statements to be dynamically issued. Currently, only the
UPDATE, INSERT, DELETE, MERGE, SELECT ... INTO, COMMIT, and
ROLLBACK statements in stored procedures can be immediately executed.
Other four SQL statements can be executed only after the EXECUTE
IMMEDIATE statement is executed. Otherwise, an error occurs during stored
procedure compiling.
● INTO
Saves the query result to a variable. If INTO is used, sql_statement must be a
SELECT statement and the result set can contain only one record. The number
of columns in the SELECT clause must be the same as that of variables in the
INTO clause.
● USING
The number and data types of variables in the USING clause must be the
same as those of parameters in sql_statement.

Examples
SQL> SET serveroutput ON;

ON
SQL> DECLARE
SQL> a INT;
SQL> b CHAR(16);
SQL> c VARCHAR(16);
SQL> BEGIN
SQL> a := 10;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 511


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

SQL> b := 'abc';
SQL> c := 'efc';
SQL> EXECUTE IMMEDIATE 'BEGIN
dbms_output.put_line(''a=''||:x);dbms_output.put_line(''b=''||:y);dbms_output.put_line(''c=''||:z); :x :=
11; :y := ''aaa''; :z := ''bbb'';END;' USING OUT a, OUT b, OUT c;
SQL> DBMS_OUTPUT.PUT_LINE('a='||a);
SQL> DBMS_OUTPUT.PUT_LINE('b='||b);
SQL> DBMS_OUTPUT.PUT_LINE('c='||c);
SQL> END;
SQL> /

a=
b=
c=
a=11
b=aaa
c=bbb

PL/SQL procedure successfully completed.

3.14.9 Control Statements


Description
Control statements are a basic part of a stored procedure. It is used to control
statement logic and implement functionality, such as branch, loop, and jump.
GaussDB 100 supports the GOTO, FOR LOOP, LOOP, WHILE LOOP, CASE WEHN,
and IF control statements.

Precautions
● BEGIN-END blocks are basic statement blocks and cannot be empty.
● FOR LOOP and WHILE LOOP statement blocks cannot be empty.
● LOOP statement blocks must contain EXIT and CONTINUE. Otherwise, an
infinite loop occurs.
● If a statement block has an infinite loop and does not respond, you can create
a new connection on the client, query the DV_SESSIONS system catalog for
the corresponding session ID, and run the ALTER SYSTEM KILL session_id;
statement to restore the statement block.

GOTO Statement
● Syntax
GOTO label_name;

● Parameter Description
label_name
Specifies the name of a label to be declared. The value cannot conflict with a
variable name or user name. A label can be defined before or after the GOTO
statement.
● Example (GOTO statement in bold)
<<main>>
DECLARE
x NUMBER;
BEGIN
x := 0;
GOTO outer_loop;
x := 100;
<<outer_loop>>

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 512


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

LOOP
DBMS_OUTPUT.PUT_LINE(' outer in ');
<<inner_loop>>
LOOP
DBMS_OUTPUT.PUT_LINE('Inside loop: x = ' || x);
x := x + 1;
IF x > 3 THEN
DBMS_OUTPUT.PUT_LINE(' BEGIN EXIT ');
EXIT inner_loop WHEN x > 4;
DBMS_OUTPUT.PUT_LINE(' AFTER EXIT ');
ELSE
CONTINUE inner_loop WHEN x > 1;
END IF;
DBMS_OUTPUT.PUT_LINE(' after continue ');
END LOOP;
DBMS_OUTPUT.PUT_LINE(' outer_loop ');
EXIT outer_loop;
DBMS_OUTPUT.PUT_LINE(' After loop: x = ' || x);
IF x < 6 THEN
GOTO inner_loop;
END IF;
END LOOP;
END;
/

FOR LOOP Statement


● Syntax
FOR index_name IN [REVERSE] lower_bound..upper_bound
LOOP
statements
END LOOP;

● Parameter Description
– index_name
Specifies a loop index. A loop variable is a local variable defined in the
FOR LOOP statement. If the name of a local variable duplicates with that
of an external variable, the FOR LOOP statement uses the local variable.
– REVERSE
Specifies that a reverse loop is used. If REVERSE is specified, the iteration
proceeds downward from upper_bound to lower_bound. If REVERSE is
not specified, the iteration proceeds upward from lower_bound to
upper_bound.
– lower_bound..upper_bound
Specifies the upper and lower boundary values of a loop variable. The
values can be numbers or an expression that evaluate to numbers.
lower_bound indicates the value of the lower boundary value and
upper_bound indicates that of the higher boundary. The value of
lower_bound must be smaller than that of upper_bound. The double dots
(..) function as a range operator.
– statements
Specifies a loop body. The value cannot be empty (it can be a NULL
statement). Otherwise, an error will be reported.
● Example (FOR loop in bold)
Declare
x bool;
BEGIN
x := FALSE;
FOR i IN 1..3 LOOP

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 513


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DBMS_OUTPUT.PUT_LINE('here:' || i);
END LOOP;
DBMS_OUTPUT.PUT_LINE('x:' || x);
END;
/

LOOP Statement
● Syntax
LOOP
statements;
EXIT [ WHEN condition1 ];
CONTINUE [ WHEN condition2 ];
END LOOP;

● Parameter Description
– LOOP/END LOOP
Specifies the start and end of a loop. Generally, LOOP is used together
with IF.
– statements
Specifies a loop body. The value cannot be empty (it can be a NULL
statement). Otherwise, an error will be reported.
– EXIT [ WHEN condition1 ]
Specifies the conditions for a loop to continue.
condition1 indicates the condition expression for exiting the loop. If this
condition is TRUE, the loop exits.
– CONTINUE [ WHEN condition2 ]
Specifies the conditions for a loop to continue.
condition2 indicates the condition expression for the loop to continue. If
this condition is TRUE, the loop continues.
● Example (LOOP statement in bold)
DECLARE
x NUMBER;
BEGIN
x := 0;
LOOP
DBMS_OUTPUT.PUT_LINE('Inside loop: x = ' || x);
x := x + 1;
IF x > 10 THEN
DBMS_OUTPUT.PUT_LINE(' BEGIN EXIT ');
EXIT WHEN x > 20;
DBMS_OUTPUT.PUT_LINE(' AFTER EXIT ');
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(' After loop: x = ' || x);
END;
/

WHILE LOOP Statement


● Syntax
WHILE condition LOOP
statements;
END LOOP;

● Parameter Description
– condition

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 514


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Specifies a condition for a WHILE loop to start. If the condition is TRUE,


the statements after LOOP run. Otherwise, control transfers to the
statement after the WHILE LOOP statement.
– statements
Specifies a loop body. The value cannot be empty. If it is empty, an error
will be reported.
● Example (WHILE loop in bold)
DECLARE
x NUMBER;
BEGIN
x := 0;
WHILE x <= 1 LOOP
DBMS_OUTPUT.PUT_LINE('here:' || x);
x := x + 1;
END LOOP;
END;
/

CASE WHEN Statement


● Description
CASE WHEN executes one or more operations based on the specified
conditions. If a condition is TRUE, the operation corresponding to the
condition is executed.
● Syntax
– Basic CASE functions
CASE variant_name
WHEN expr1 THEN statement1
WHEN expr2 THEN statement2
ELSE statement3
END CASE;

– Searched CASE functions


CASE
WHEN variant_name = expr1 THEN statement1
WHEN variant_name = expr2 THEN statement2
ELSE statement3
END CASE;

● Parameter Description
– Basic CASE functions

▪ variant_name
Specifies the name of a variable used to check a condition.

▪ WHEN expr1 THEN statement1


If the variable value is expr1, statement1 is executed.

▪ WHEN expr2 THEN statement2


If the variable value is expr2, statement2 is executed.

▪ ELSE statement3
If the variable value is neither expr1 nor expr2, statement3 is
executed.
– Searched CASE functions

▪ WHEN variant_name = expr1 THEN statement1

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 515


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

If variant_name = expr1 is TRUE, statement1 is executed.

▪ WHEN variant_name = expr2 THEN statement2


If variant_name = expr2 is TRUE, statement2 is executed.

▪ ELSE statement3
If neither variant_name = expr1 nor variant_name = expr2 is TRUE,
statement3 is executed
● Examples
– Basic CASE function (in bold)
DECLARE
class CHAR(1) := 'S';
age VARCHAR2(15);
BEGIN
CASE class
WHEN 'S' THEN age := '3-4 years';
WHEN 'M' THEN age := '4-5 years';
WHEN 'P' THEN age := '5-6 years';
ELSE age := 'No such class';
END CASE;
DBMS_OUTPUT.PUT_LINE(age);
END;
/

– Searched CASE function (in bold)


DECLARE
class CHAR(1) := 'S';
age VARCHAR2(15);
BEGIN
CASE
WHEN class = 'S' THEN age := '3-4 years';
WHEN class = 'M' THEN age := '4-5 years';
WHEN class = 'P' THEN age := '5-6 years';
ELSE age := 'No such class';
END CASE;
DBMS_OUTPUT.PUT_LINE(age);
END;
/

IF Statement
● Syntax
IF condition THEN
statement
ELSIF condition THEN
statement
ELSIF
...
ELSE
statement
END IF;

NOTICE

An IF statement can be nested in another IF statement.

● Parameter Description
– condition
Specifies a condition for a WHILE loop to start.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 516


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– statement
Specifies the statements that will be executed if a specified condition is
TRUE.
● Example (IF statement in bold)
DECLARE
v_sal INT;
BEGIN
v_sal := 1;
v_sal := v_sal + 1;
DBMS_OUTPUT.PUT_LINE('value1:'||v_sal);
IF v_sal < 2 THEN
DBMS_OUTPUT.PUT_LINE('value2:'||v_sal);
ELSIF v_sal = 2 THEN
IF v_sal != 2 THEN
DBMS_OUTPUT.PUT_LINE('value3:'||v_sal);
ELSE
DBMS_OUTPUT.PUT_LINE('value3x:'||v_sal);
END IF;
ELSIF v_sal = 4 THEN
DBMS_OUTPUT.PUT_LINE('value4:'||v_sal);
ELSE
DBMS_OUTPUT.PUT_LINE('value5:'||v_sal);
END IF;
DBMS_OUTPUT.PUT_LINE('value6:'||v_sal+2);
END;
/

3.14.10 Exception Statements


EXCEPTION handles exceptions during stored procedure execution. Currently,
GaussDB 100 can handle system predefined exceptions, user-defined exceptions,
and internal exceptions. Error codes and messages of these exceptions are
obtained by using SQLCODE and SQLERRM.

Exception Handling Mechanisms


● Syntax
EXCEPTION
{ [ WHEN expr THEN sql ] [...]
[ WHEN OTHERS THEN sql1 ]
}
END;

● Parameter Description
– WHEN expr THEN sql
expr specifies an exception expression. sql specifies the statement for
handling the exception specified by expr. An exception can be handled
only once.
– WHEN OTHERS THEN sql1
Specifies the statement for handling an exception that matches no
specified exception expressions. WHEN OTHERS THEN sql1 must be
placed at the end of an EXCEPTION statement.
● Example (EXCEPTION statement in bold)
-- Delete the existing test_pl_excpt1 stored procedure.
DROP PROCEDURE IF EXISTS test_pl_excpt1;
-- Create the test_pl_excpt1 stored procedure.
CREATE OR REPLACE PROCEDURE test_pl_excpt1
AS
v_age INTEGER;
v_name VARCHAR(30);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 517


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

BEGIN
v_age:=89;v_age:= v_age/0;
DBMS_OUTPUT.PUT_LINE('correct');
EXCEPTION
WHEN Zero_divide THEN SYS.DBMS_OUTPUT.PUT_LINE('Zero divide');
SYS.DBMS_OUTPUT.PUT_LINE(SQLCODE || 'error ' || sqlerrm);
WHEN value_error THEN SYS.DBMS_OUTPUT.PUT_LINE('value error');
SYS.DBMS_OUTPUT.PUT_LINE(SQLCODE || 'error ' || sqlerrm);
WHEN OTHERS THEN SYS.DBMS_OUTPUT.PUT_LINE('other error');
SYS.DBMS_OUTPUT.PUT_LINE(sqlcode||'error'||sqlerrm);
END;
/

Handling Exceptions Using SQLCODE and SQLERRM


● Description
In stored procedures, you can use SQLCODE to obtain an error code and use
SQLERRM to obtain the corresponding error information.
● Precautions
– SQLCODE and SQLERRM can be defined as variables in stored
procedures. If you have defined the variables and set the corresponding
values, the values that you have set instead of the system error code or
message are returned when you use SQLCODE and SQLERRM to obtain
information.
– If no parameters are used, the parentheses in SQLCODE() and
SQLERRM() are unnecessary.
● Syntax
– SQLCODE Syntax
SQLCODE();

– SQLERRM Syntax
SQLERRM([ errorcode ]);

● Example (SQLCODE and SQLERRM in bold)


CREATE OR REPLACE PROCEDURE test_pl_excpt1
AS
v_age INTEGER;
v_name VARCHAR(30);
BEGIN
v_age:=89;v_age:= v_age/0;
DBMS_OUTPUT.PUT_LINE('correct');
EXCEPTION
WHEN Zero_divide THEN SYS.DBMS_OUTPUT.PUT_LINE('Zero divide');
SYS.DBMS_OUTPUT.PUT_LINE(SQLCODE || 'error ' || SQLERRM);
WHEN value_error THEN SYS.DBMS_OUTPUT.PUT_LINE('value error');
SYS.DBMS_OUTPUT.PUT_LINE(SQLCODE || 'error ' || SQLERRM);
WHEN OTHERS THEN SYS.DBMS_OUTPUT.PUT_LINE('other error');
SYS.DBMS_OUTPUT.PUT_LINE(SQLCODE||'error'||SQLERRM);
END;
/

System Predefined Exceptions


There are 14 predefined exceptions. For details, see Table 3-55. System predefined
exceptions do not need to be declared.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 518


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Table 3-55 System predefined exceptions

No. Exception Name Error No.

1 CASE_NOT_FOUND 902

2 CURSOR_ALREADY_OPEN 904

3 DUP_VAL_ON_INDEX 729

4 INVALID_CURSOR 905

5 INVALID_NUMBER 636

6 NO_DATA_FOUND 906

7 PROGRAM_ERROR 908

8 ROWTYPE_MISMATCH 926

9 STORAGE_ERROR 911

10 SYS_INVALID_ROWID 639

11 TIMEOUT_ON_RESOURCE 723

12 TOO_MANY_ROWS 915

13 VALUE_ERROR 635

14 ZERO_DIVIDE 637

User-defined Exceptions
● Syntax
exception_name EXCEPTION;
A declared exception is thrown by the RAISE statement.
● Parameter Description
exception_name
Specifies the name of an exception to be declared.
● Example (user-defined exception in bold)
CREATE OR REPLACE PROCEDURE employee_income ( salary number )
IS
low_income EXCEPTION; // Declare an exception.
BEGIN
IF salary < 30000 THEN
RAISE low_income; // Throws the exception.
END IF;
EXCEPTION
The WHEN low_income THEN // Handle the exception.
DBMS_OUTPUT.PUT_LINE ('low_income:'||salary);
END;
/

BEGIN
employee_income (10000);
END;
/

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 519


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Output:
low_income:10000

Internal Exceptions
● Description
An internal exception is the one declared in GaussDB 100. The corresponding
error code and message are automatically raised when the defined exception
is matched.
● Syntax
-- Define an exception.
exception_name EXCEPTION;
-- Associate the exception with an internal error code.
PRAGMA EXCEPTION_INIT (exception_name, error_code);
● Parameter Description
– exception_name
Specifies the name of an exception to be declared.
– error_code
Specifies the error code to be associated with an exception. The code
range is (0, 100000) or [-20999, -20000].
● Examples
DECLARE
my_except EXCEPTION;
PRAGMA EXCEPTION_INIT(my_except, 932);
BEGIN
...
EXCEPTION
WHEN my_except THEN
...
WHEN OTHERS THEN
...
END;
/

3.14.11 Other Statements


Function
Other statements include the NULL statement, label declaration statements, and
variable declaration reference statements.

NULL Statement
The NULL statement is a ''no-op" (no operation) statement and is usually used in
an empty function or an loop body. The syntax is as follows:
NULL;

Label Declaration Statements


● Precautions
– In the definition of an anonymous block, function body, or trigger,
restrictions on a label declaration in the GOTO statement are as follows:

▪ A label cannot be used in an unknown loop in the GOTO statement.


For details, see incorrect case 1.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 520


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ A label cannot be used in an unknown condition in the GOTO


statement. For details, see incorrect case 2.

▪ A label cannot be used in a conflicted loop in the GOTO statement.


For details, see incorrect case 3.

▪ A label cannot be used in a conflict CASE in the GOTO statement.


For details, see incorrect case 4.

▪ A label cannot be used in an unknown BEGIN in the GOTO


statement. For details, see incorrect case 5.

▪ A label cannot be used in an unknown EXCEPTION in the GOTO


statement. For details, see incorrect case 6.

▪ lable_name must be unique. For details, incorrect case 7.


– In the definition of an anonymous block, lable_name followed by the
DECLARE keyword of an anonymous block is considered to be the name
of the block.
– lable_name followed by the LOOP, FOR, or WHILE loop body is
considered to be the name of the loop.
● Syntax
<<label_name>>

● Parameter Description
label_name
Specifies the name of a label to be declared.
● 示例(LABEL语句以粗体显示)
<<main>>
DECLARE
aaa NUMBER;
j NUMBER;
bbb NUMBER;
BEGIN
aaa := 2;
j := 1;
bbb := 0;
<<outer_loop>>
bbb := bbb + 1;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('i:' || i);
<<inner_loop>>
WHILE j < 6 LOOP
DBMS_OUTPUT.PUT_LINE('j:' || j);
j := j + 1;
FOR k IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('k:' || k);
FOR l IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('l:' || l);
EXIT inner_loop WHEN bbb = 2;
GOTO outer_loop;
END LOOP;
END LOOP;
END LOOP;
END LOOP;
END;
/

Incorrect case 1:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 521


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DECLARE
bbb NUMBER;
BEGIN
bbb := 1;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
GOTO my_label;
FOR i IN 1..5 LOOP
<<my_label>>
bbb := bbb + 1;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
END LOOP;
END;
/

Incorrect case 2:
DECLARE
bbb NUMBER;
BEGIN
bbb := 1;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
GOTO my_label;
IF bbb = 1 THEN
<<my_label>>
DBMS_OUTPUT.PUT_LINE('bbb = 1');
bbb := bbb + 1;
ELSIF bbb = 2 THEN
DBMS_OUTPUT.PUT_LINE('bbb = 2');
END IF;
END;
/

Incorrect case 3:
DECLARE
bbb NUMBER;
BEGIN
bbb := 1;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
IF bbb = 1 THEN
<<my_label>>
DBMS_OUTPUT.PUT_LINE('bbb = 1');
bbb := bbb + 1;
ELSIF bbb = 2 THEN
GOTO my_label;
DBMS_OUTPUT.PUT_LINE('bbb = 2');
END IF;
END;
/

Incorrect case 4:
DECLARE
bbb NUMBER;
BEGIN
bbb := 3;
DBMS_OUTPUT.PUT_LINE('bbb:' || bbb);
CASE bbb
WHEN 1 THEN
<<my_label>>
DBMS_OUTPUT.PUT_LINE('bbb = 1');
bbb := bbb + 1;
WHEN 2 THEN
DBMS_OUTPUT.PUT_LINE('bbb = 2');
bbb := bbb + 1;
GOTO my_label;
ELSE
DBMS_OUTPUT.PUT_LINE('bbb = 3');
END CASE;
END;
/

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 522


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Incorrect case 5:
DECLARE
aaa NUMBER;
BEGIN
aaa := 2;
GOTO my_label;
BEGIN
<<my_label>>
DBMS_OUTPUT.PUT_LINE('aaa:' || aaa);
END;
aaa := 3;
END;
/

Incorrect case 6:
DECLARE
aaa NUMBER;
BEGIN
aaa := 2;
BEGIN
FOR l IN 1..3 LOOP
GOTO my_label;
DBMS_OUTPUT.PUT_LINE('l:' || l);
END LOOP;
END;
aaa := 3;
EXCEPTION
when no_data_found then
<<my_label>>
dbms_output.put_line(aaa);
END;
/

Incorrect case 7:
DECLARE
aaa NUMBER;
BEGIN
aaa := 2;
<<my_label>>
FOR l IN 1..3 LOOP
GOTO my_label;
DBMS_OUTPUT.PUT_LINE('l:' || l);
END LOOP;
<<my_label>>
aaa := 3;
END;
/

Variable Declaration Reference Statements


● Precautions
– %ROWTYPE references data types of table and cursor variables.
– %ROWTYPE provides a record type that represents a row. A record has
the same number of columns and column data types with the referenced
row.
– %TYPE references data types of column (format: table name.column
name), record, and common variables.
– %TYPE provides a common variable that represents the referenced ones.
● Syntax
%ROWTYPE
%TYPE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 523


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● Example (variable declaration reference statement in bold)


-- Delete the existing emp_test table.
DROP TABLE IF EXISTS emp_test;
-- Create the emp_test table.
CREATE TABLE emp_test(empno int, ename varchar(50), sal int);
-- Insert data into the emp_test table.
INSERT INTO emp_test VALUES(123, 'abc', 456);
-- Commit the transaction.
COMMIT;
-- Declare a variable.
DECLARE
cv SYS_REFCURSOR;
v_empno emp_test.empno%TYPE;
v_ename emp_test.ename%TYPE;
v_sal emp_test.sal%TYPE;
query_2 VARCHAR2(200) :=
'SELECT * FROM emp_test ORDER BY 1,2,3';
v_emp_test emp_test%ROWTYPE;
BEGIN
OPEN cv FOR SELECT empno,ename FROM emp_test ORDER BY empno;
LOOP
FETCH cv INTO v_empno, v_ename;
EXIT WHEN cv%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(rpad(v_empno,25,' ')||v_ename);
END LOOP;

DBMS_OUTPUT.PUT_LINE( '-------------------------------------' );
CLOSE cv;
END;
/

3.14.12 Cursors
Description
GaussDB 100 supports the following types of cursors: explicit cursors, reference
cursors, FOR loop cursors, and implicit cursors.

Precautions
● Cursors do not support the RETURN clause.
● Reference cursors can be returned as output parameters, but explicit and
implicit cursors cannot.
● Implicit cursors do not need to be declared. Explicit cursors are bound to the
SELECT statement when declared, and the statement is verified in the
compilation phase. Reference cursors can be dynamically associated to a
specific SELECT statement, and the statement is verified in the execution
phase.
● Currently, cursor variables are implemented based on weak data types. That
is, the RETURN return_type clause cannot be used to specify the data type of
the returned result in the definition statement of a cursor type. Instead, the
data type of the row opened by the cursor is used.

Declaring a Cursor
● Syntax
– Declare an explicit cursor.
CURSOR cursor_name [(param_list)] IS (select_statement);
– Declare a reference cursor. (Reference cursors declared using the
following two methods are equivalent).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 524


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ Method 1:
cursor_name SYS_REFCURSOR;

▪ Method 2:
-- Define a REF CURSOR type (which is equivalent to the SYS_REFCURSOR type):
TYPE type_name IS REF CURSOR;
-- Declare a cursor of the REF CURSOR type:
cursor_name type_name;
● Parameter Description
– cursor_name
Specifies the name of the cursor that you are declaring.
– param_list
Specifies a list of parameters for an explicit cursor.
When declaring an explicit cursor, you can use the listed parameters in
the WHERE clause of the SELECT statement following the keyword IS.
This parameter is optional for explicit cursors. If an explicit cursor has
parameters defined, the actual parameter values must be transferred
when the cursor is opened.
– select_statement
Specifies the SELECT statement for declaring an explicit cursor.
When declaring an explicit cursor, specify the SELECT statement
following the keyword IS. The SELECT statement can be a table or view
query, or even a join query. It can concatenate WHERE, ORDER BY, and
GROUP BY clauses, but cannot concatenate the INTO clause. For details
about the SELECT statement, see SELECT.
– SYS_REFCURSOR
Specifies a system cursor, which is used to declare a reference cursor.
When cursor_name SYS_REFCURSOR is used to declare a cursor, no
SELECT statement is required. A declared cursor variable can be used as
an output parameter and bound to the SQL statement in the cursor
opening phase.
– type_name
Specifies the name of the REF CURSOR type that you are defining.
● Examples
-- Delete the existing test table.
DROP TABLE IF EXISTS test;
-- Create the test table.
CREATE TABLE test(a int,b int);
-- Declare a cursor.
DECLARE
TYPE type_name IS RECORD (
a INT,
b INT
);
CURSOR c1 IS SELECT * FROM test ORDER BY a; // Declare an explicit cursor.
c2 sys_refcursor; // Declare a reference cursor (method 1).
abc type_name;
TYPE tcur IS REF CURSOR;
cursor_k tcur; // Declare a reference cursor (method 2).
rec test%rowtype;
BEGIN
OPEN c2 FOR SELECT a FROM test ORDER BY a;
CLOSE c2;
OPEN c2 FOR SELECT a,b FROM test ORDER BY a;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 525


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

FETCH c2 INTO abc;


CLOSE c2;
DBMS_OUTPUT.PUT_LINE('result is ' || abc.a);
DBMS_OUTPUT.PUT_LINE('result is ' || abc.b);
OPEN cursor_k FOR (SELECT * FROM test);
FETCH cursor_k INTO rec;
close cursor_k;
END;
/

Using an Explicit Cursor


● Precautions
– The OPEN statement for an explicit cursor cannot concatenate the FOR
clause.
– In the FETCH statement of a cursor, the number of columns in the
variable list of the INTO clause must be the same as that of columns in
the result set returned by the cursor. Otherwise, the error
"NOT_ENOUGH_VALUE" will be reported.
– In the FETCH statement of a cursor, the INTO clause can use only one
record variable to store data, and the number of columns in the record
variable must be the same as that of columns in the result set returned
by the cursor. Otherwise, the error "NOT_ENOUGH_VALUE" will be
reported.
– In the FETCH statement of a cursor, if the data types of assignment
variables defined are different from those of the corresponding columns
in the result set returned by the cursor, there will be a forcible data type
conversion. If the conversion fails, an error will be reported.
– After an explicit cursor is opened, you are advised to explicitly close it. If a
cursor is not explicitly closed, the system will automatically release it
when the anonymous block is exited or the stored procedure is executed.
● Syntax
-- Open a cursor:
OPEN cursor_name;
-- Fetch data from the cursor:
FETCH cursor_name INTO { variant_list | record_variant };
-- Close the cursor:
CLOSE cursor_name;
● Parameter Description
– course_name
Specifies the name of the target cursor.
– variant_list
Specifies a variable list, which is used to store data fetched from a cursor.
– record_variant
Specifies a record variable, which is used to store data fetched from a
cursor.
● Examples (The statements that use a cursor are displayed in bold.)
-- Delete the existing emp table.
DROP TABLE IF EXISTS emp;
-- Create the emp table.
CREATE TABLE emp(empno int, empname varchar(50), job varchar(50), sal int);
-- Insert records into the emp table.
INSERT INTO emp VALUES(123, 'abc', 'doctor', 456);
-- Commit the transaction.
COMMIT;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 526


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Declare and use the cursor.


DECLARE
CURSOR c_job
IS
SELECT * FROM emp WHERE job='doctor';
c_row emp%rowtype;
BEGIN
OPEN c_job;
LOOP
FETCH c_job INTO c_row;
EXIT WHEN c_job%notfound;
DBMS_OUTPUT.PUT_LINE(c_row.empno||'-'||c_row.empname ||'-'||c_row.job||'-'||c_row.sal);
END LOOP;
CLOSE c_job;
END;
/

Using a Reference Cursor


● Precautions
– The OPEN statement for a reference cursor must concatenate the FOR
clause. The FOR clause allows for only the SELECT statement or a
dynamic SQL statement. Note that the dynamic SQL statement must also
be SELECT. Otherwise, an error will be reported in the execution phase.
– In the FETCH statement of a cursor, the number of columns in the
variable list of the INTO clause must be the same as that of columns in
the result set returned by the cursor. Otherwise, the error
"NOT_ENOUGH_VALUE" will be reported.
– In the FETCH statement of a cursor, the INTO clause can use only one
record variable to store data, and the number of columns in the record
variable must be the same as that of columns in the result set returned
by the cursor. Otherwise, the error "NOT_ENOUGH_VALUE" will be
reported.
– A reference cursor can be used as an output parameter of the SELECT
statement and returned, either directly or through the system function
DBMS_SQL.RETURN_RESULT, to a client as the result set.
– The OPEN statement that references the cursor uses the FOR clause to
assign a value to the cursor.
● Syntax
-- Open a cursor:
OPEN cursor_name FOR { dynamic_sql | select statement };
-- Fetch data from the cursor:
FETCH cursor_name INTO { variant_list | record_variant };
-- Close the cursor:
CLOSE cursor_name;

● Parameter Description
– course_name
Specifies the name of the target cursor.
– variant_list
Specifies a variable list, which is used to store data fetched from a cursor.
– record_variant
Specifies a record variable, which is used to store data fetched from a
cursor.
● Examples (The statements that use a cursor are displayed in bold.)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 527


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DECLARE
c2 SYS_REFCURSOR;
abc test%rowtype;
BEGIN
OPEN c2 FOR SELECT a FROM test ORDER BY a;
CLOSE c2;
OPEN c2 FOR SELECT a,b FROM test ORDER BY a;
FETCH c2 INTO abc;
CLOSE c2;
DBMS_OUTPUT.PUT_LINE('result is ' || abc.a);
DBMS_OUTPUT.PUT_LINE('result is ' || abc.b);
END;
/

Using a Cursor FOR LOOP


● Precautions
– When an explicit cursor FOR LOOP statement is used for traversing, the
OPEN, FETCH, CLOSE, and LOOP statements of the cursor are
automatically executed. That is, when a loop begins, the cursor FOR
LOOP statement automatically opens the cursor and fetches a row from
the result set. After fetched data is processed and the next iteration
starts, the cursor FOR LOOP statement automatically fetches the next
row. When there are no more rows to fetch, the cursor FOR LOOP
statement ends the loop and closes the cursor. If the OPEN, FETCH, and
CLOSE statements of a cursor are executed inside the loop body, the error
"INVALID_CURSOR" will be reported.
– When the cursor FOR LOOP statement is used and if the keyword IN is
followed by a cursor name, the name must be an explicit or reference
cursor name.
– When an implicit cursor FOR LOOP statement is used, the keyword IN
must be the SELECT statement.
● Syntax
– Explicit cursor FOR LOOP statement
FOR index_name IN cursor_name LOOP
statement;
END LOOP;

– Implicit cursor FOR LOOP statement


FOR index_name IN select_statement LOOP
statement;
END LOOP;

● Parameter Description
– index_name
Specifies a loop index.
– cursor_name
Specifies the name of a cursor for FOR LOOP.
– select_statement
Specifies an implicit cursor for traversing.
– statement
Specifies the loop body. This parameter cannot be empty.
● Examples
– Use an explicit cursor FOR LOOP (in bold).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 528


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DECLARE
CURSOR c1 IS
SELECT a,b FROM test ORDER BY a;
BEGIN
DELETE FROM test;
INSERT INTO test(a,b) VALUES(1,100);
INSERT INTO test(a,b) VALUES(1,100);
FOR item IN c1
LOOP
DBMS_OUTPUT.PUT_LINE('A = ' || item.a || ',B = ' || item.b);
DBMS_OUTPUT.PUT_LINE('CURSOR%ISOPEN is ' || c1%ISOPEN);
DBMS_OUTPUT.PUT_LINE('CURSOR%FOUND is ' || c1%FOUND);
DBMS_OUTPUT.PUT_LINE('CURSOR%NOTFOUND is ' || c1%NOTFOUND);
DBMS_OUTPUT.PUT_LINE('CURSOR%ROWCOUNT is ' || c1%ROWCOUNT);
END LOOP;
DBMS_OUTPUT.PUT_LINE('after for loop');
DBMS_OUTPUT.PUT_LINE('CURSOR%ISOPEN is ' || c1%ISOPEN);
END;
/

– Use an implicit cursor FOR LOOP (in bold).


BEGIN
FOR a IN(SELECT * FROM emp WHERE ename LIKE '%zhangsan%' AND sal > 9000
ORDER BY empno;)
LOOP
DBMS_OUTPUT.PUT_LINE('a is emp:'||a.empno||'name:'||a.ename||'job:'||a.job||'sal:'||
a.sal);
DBMS_OUTPUT.PUT_LINE(sql%rowcount);
END LOOP;
END;
/

Cursor Attributes
Cursor attributes are classified into %ISOPEN, %FOUND, %NOTFOUND, and
%ROWCOUNT.
● %ISOPEN checks whether a cursor is open.
● %FOUND and %NOTFOUND checks whether the last fetch is successful. The
logics of them are opposite to each other.
● %ROWCOUNT returns the number of records read from a cursor.
For details about the attribute return values of explicit cursors, see Table 3-56. For
details about the attribute return values of implicit cursors, see Table 3-57.

Table 3-56 Attribute return values of explicit cursors


Attribute Description

Cursor name %ISOPEN If a cursor is not defined or is defined


but not opened, FALSE will be
returned.
If a cursor is defined and then opened,
TRUE will be returned.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 529


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Attribute Description

Cursor name %FOUND If a cursor is not opened, the error


"INVALID CURSOR" will be reported.
If a cursor is opened but not executed,
NULL will be returned.
If a cursor is executed without
affecting any rows, FALSE will be
returned.
If a cursor is executed with rows
affected, TRUE will be returned.

Cursor name %NOTFOUND If a cursor is not opened, the error


"INVALID CURSOR" will be reported.
If a cursor is opened but not executed,
NULL will be returned.
If a cursor is executed with rows
affected, FALSE will be returned.
If a cursor is executed without
affecting any rows, TRUE will be
returned.

Cursor name %ROWCOUNT If a cursor is not opened, the error


"INVALID CURSOR" will be reported.
If a cursor is opened but not executed,
NULL will be returned.
After a cursor is executed, the number
of rows affected will be returned.

Table 3-57 Attribute return values of implicit cursors


Attribute Description

SQL%ISOPEN FALSE is always returned.

SQL%FOUND If no SQL statement is not executed,


NULL will be returned.
If executing a SQL statement affected
rows, TRUE will be returned.
If executing a SQL statement did not
affect rows, FALSE will be returned.

SQL%NOTFOUND If no SQL statement is not executed,


NULL will be returned.
If executing a SQL statement affected
rows, FALSE will be returned.
If executing a SQL statement did not
affect rows, TRUE will be returned.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 530


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Attribute Description

SQL%ROWCOUNT If no SQL statement is not executed,


NULL will be returned.
If a SQL statement has been executed,
the number of rows affected will be
returned.

Cursor Value Assignment and Referencing


● Description
A cursor variable defined in a database is actually a pointer. If a source cursor
is not open, assigning the value of the source cursor to a target cursor
generates an empty target cursor. If a source cursor is open, assigning the
value of the source cursor to a target cursor makes the target cursor pointing
to the source cursor. That is, the target and source cursors point to the same
area.
● Syntax
rc1 := rc2;
● Parameter Description
– rc1
Specifies a target cursor.
– rc2
Specifies a source cursor.
● Examples (The value assignment and referencing statements are displayed in
bold)
– Assume that a source cursor is not open, and assign the value of the
source cursor to a target cursor. This generates an empty target cursor.
CREATE OR REPLACE PROCEDURE proc1 AS
rc1 SYS_REFCURSOR;
rc2 SYS_REFCURSOR;
BEGIN
rc1 := rc2;
OPEN rc2 FOR SELECT 1 FROM SYS_DUMMY;
DBMS_SQL.RETURN_RESULT(rc1);
END;
/

EXEC proc1;

GS-00932, PL/SQL(SYS.PROC1) terminated with execute errors


[7:6] PL/SQL(DBMS_SQL.RETURN_RESULT) terminated with execute errors
[7:29] GS-00924, cursor not open
– Assume that a source cursor is open, and assign the value of the source
cursor to a target cursor. This makes the target and source cursors point
to the same area.
CREATE OR REPLACE PROCEDURE proc2 AS
rc1 SYS_REFCURSOR;
rc2 SYS_REFCURSOR;
BEGIN
OPEN rc2 FOR SELECT 1 FROM SYS_DUMMY;
rc1 := rc2;
DBMS_SQL.RETURN_RESULT(rc1);
END;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 531


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

EXEC proc2;
PL/SQL procedure successfully completed.
ResultSet #1
1
----------
1

3.14.13 Anonymous Blocks

Description
An anonymous block is a statement that can be directly executed. Specifically, it
will be immediately compiled and executed once defined. Anonymous blocks are
not stored in databases, and need to be defined each time they are used.

Precautions
Parameter values must be different from column names in tables because
anonymous blocks give parameters precedence. If they repeat, the column values
cannot be obtained.

Syntax
DECLARE
[param-list]
BEGIN
statement;
END;

Parameters
● param-list
Specifies a list of parameters. Default parameter values can be used. The
format is as follows: variant_name data_type [ { := | DEFAULT }
default_expr ];
● statement
Specifies an anonymous block statement. This parameter cannot be empty
because leaving it empty will raise an error report.
Such a statement can contain basic statements, dynamic statements, control
statements, exception statements, other statements, functions, or stored
procedures. For details about basic statements, see Basic Statements. For
details about dynamic statements, see Dynamic Statements. For details
about control statements, see Control Statements. For details about other
statements, see Other Statements. For details about user-defined functions,
see User-defined Functions. For details about user-defined stored
procedures, see Creating a Stored Procedure.

Examples
Create an anonymous block.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 532


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

NOTICE

Stored procedures and functions are stored in the same system catalog. If a stored
procedure to be created has the same name as an existing user-defined function,
creating the stored procedure will fail. Therefore, before creating a stored
procedure, you need to delete the user-defined function with the same name.

-- Delete a stored procedure Zenith_Test_004, if any:


DROP PROCEDURE IF EXISTS Zenith_Test_004;
-- Delete a user-defined function Zenith_Test_004, if any:
DROP FUNCTION IF EXISTS Zenith_Test_004;

NOTICE

In a statement for creating a stored procedure or anonymous block, the last slash
(/) is used to indicate the end of the definition statement. It cannot be omitted
and must be placed in a different line.

-- Create the Zenith_Test_004 stored procedure:


CREATE OR REPLACE PROCEDURE Zenith_Test_004(param1 OUT VARCHAR2)
IS
tmp VARCHAR(20):='12345678';
BEGIN
param1:=param1||tmp;
END Zenith_Test_004;
/
-- Create an anonymous block:
DECLARE
v_char1 CHAR(9) :='A';
BEGIN
Zenith_Test_004(v_char1);
DBMS_OUTPUT.PUT_LINE('OUT PUT RESULT:'||v_char1);
END;
/

3.15 Built-in Advanced Packages


The built-in advanced packages provide common system functionality, including
stored procedures, functions, and constants.

Table 3-58 lists the advanced packages provided by GaussDB 100. Common users
can use the DBMS_JOB package only after being granted with the EXECUTE
permission. All users have permission to use other advanced packages.

Table 3-58 Advanced package list

Package Description

DBMS_LOB The DBMS_LOB package is used to process data of the


LOB type.

DBMS_JOB The DBMS_JOB package is used to execute scheduled


jobs.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 533


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Package Description

DBMS_OUTPUT The DBMS_OUTPUT package is used to debug stored


procedures and functions or displays information in
zsql.

DBMS_RAFT Used to maintain primary-standby nodes by using GS-


Paxos.

DBMS_RANDOM A built-in random number generator, used to generate


random numbers and characters

DBMS_SQL Used to execute SQL statements

DBMS_STANDARD A standard package, used for transaction management


and exception handling

DBMS_STATS Used to optimize statistics

DBMS_UTILITY Used for data type processing and calculation

DBMS_DIAGNOSE Used to control access to functions.

3.15.1 DBMS_LOB

Description
The DBMS_LOB package is used to process data of the LOB type.

Interfaces
● GETLENGTH
Description: Obtains the length information of the LOB type.
Interface:
DBMS_LOB.GETLENGTH (
lob_loc IN LOB)
RETURN INTEGER;

Parameters:
lob_loc: Specifies a LOB whose length is to be calculated.
Return value: length of the LOB

● SUBSTR
Description: Obtains the substring of the LOB type.
Interface:
DBMS_LOB.SUBSTR (
lob_loc IN LOB,
amount IN INTEGER,
offset IN INTEGER)
RETURN VARCHAR2;

Parameters:
– lob_loc: Specifies a LOB whose length is to be calculated.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 534


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– amount: Specifies the length of characters for calculation.


– offset: Specifies the start offset of calculation.
Return value: a substring that meets the requirements

3.15.2 DBMS_JOB

Description
The DBMS_JOB package is used to execute scheduled jobs.

● The COMMIT statement must be executed after a DBMS_JOB interface is implemented.


Otherwise, the interface will not take effect.
● Common users can create, suspend, run, and delete only their own jobs.
● User SYS can create jobs and can suspend, run, and delete the jobs of all users.
● JOB_THREADS specifies the number of concurrent jobs. The default value is 100, and
the value range is (0, 200].
● If there is an error during job running, the system will write an alarm log. If there are
more errors later, the system will not write the alarm log.
● If a job fails, the background thread will attempt to process the job at an interval of 1
minute until the job execution succeeds.
● If the PL/SQL statement block executed by the job is not internally committed, the
system will perform the commit operation after the job execution succeeds or perform
the rollback operation after the job execution fails.
● Currently, the parameters of a created job cannot be modified. If you need to modify the
parameters, delete the original job and create it again.
● The unique ID of a JOB is implemented through the global sequence JOBSEQ. When a
JOB task is submitted, a unique ID is obtained. In other interfaces, this identifier can be
used to perform corresponding operations on corresponding JOB tasks. The minimum
value is 1000, and the value is incremented by 1 each time.
● A job is executed by the user who submits the job. Job execution consumes sessions. The
maximum number of sessions per user is limited by SESSIONS_PER_USER.

Interfaces
● BROKEN
Description: Changes job status to blocked.
Interface:
DBMS_JOB.BROKEN (
job IN BINARY_BIGINT,
broken IN BOOLEAN,
next_date IN DATE DEFAULT SYSDATE);

Parameters:
job: ID of the job to be modified
broken: block flag, allowing for values true and false
next_date: next update time
● REMOVE
Description: Deletes a specified job.
Interface:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 535


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DBMS_JOB.REMOVE (
job IN BINARY_BIGINT );

Parameters:
job: ID of the job to be deleted
Note that you can use the REMOVE interface to remove an existing job. If the
job is ongoing, its current execution will not be affected, but it will not be
executed next time.
● RUN
Description: Runs a specified job.
Interface:
DBMS_JOB.RUN (
job IN BINARY_BIGINT,
force IN BOOLEAN DEFAULT FALSE);

Parameters:
job: ID of the job to be executed
force: This parameter is only for syntax compatibility, and does not take effect
currently.
● SUBMIT
Description: Creates a job.
Interface:
DBMS_JOB.SUBMIT (
job OUT BINARY_BIGINT,
what IN VARCHAR2,
next_date IN DATE DEFAULT sysdate,
interval IN VARCHAR2 DEFAULT 'null',
no_parse IN BOOLEAN DEFAULT FALSE,
instance IN BINARY_INTEGER DEFAULT 0,
force IN BOOLEAN DEFAULT FALSE);

Parameters:
– job: ID of the job to be created
– what: PL/SQL block involved in job execution
– next_date: next execution time
– interval: execution interval expression
– no_parse: If it is set to false, what and interval will be parsed during
creation. If it is set to true, the two will not be parsed during creation.
– instance: This parameter is only for syntax compatibility, and does not
take effect currently.
– force: This parameter is only for syntax compatibility, and does not take
effect currently.

Example 1
create table test_job(
id varchar2(30),
dt varchar2(30)
);

create or replace procedure job_proce_t is


begin
insert into test_job(id, dt) values('1', to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss'));
commit;
end job_proce_t;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 536


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

declare
jobno number;
begin
dbms_job.submit(jobno,'job_proce_t();', sysdate, 'sysdate+1/24/60');
commit;
end;
/

declare
jobno int;
begin
select job into jobno from user_jobs where what='job_proce_t();';
dbms_job.broken(jobno, true, sysdate);
commit;
end;
/

declare
jobno int;
begin
select job into jobno from user_jobs where what='job_proce_t();';
dbms_job.run(jobno);
commit;
end;
/

declare
jobno int;
begin
select job into jobno from user_jobs where what='job_proce_t();';
dbms_job.remove(jobno);
commit;
end;
/

Example 2
By default, the system creates a full statistics collection job and a data change
collection job when being started.
CREATE OR REPLACE PROCEDURE GATHER_DB_STATS(
estimate_percent NUMBER DEFAULT 30,
force BOOLEAN DEFAULT TRUE
)
--force false: don't gather when cbo is disable
IS
cbo_enable VARCHAR(3);
BEGIN
--check cbo flag
IF force = FALSE THEN
SELECT VALUE INTO cbo_enable FROM SYS.DV_PARAMETERS WHERE NAME='CBO';
IF UPPER(cbo_enable) = 'OFF' THEN
RETURN;
END IF;
END IF;

--flush modification to table


DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO();

--only gather heap table


FOR ITEM IN (SELECT A.OWNER, A.TABLE_NAME FROM DBA_TABLES A, DBA_TAB_MODIFICATIONS B
WHERE A.PARTITIONED = 0 AND A.TABLE_TYPE ='HEAP' AND
A.OWNER = B.TABLE_OWNER AND A.TABLE_NAME=B.TABLE_NAME AND
(NVL(B.INSERTS, 0) + NVL(B.UPDATES, 0) + NVL(B.DELETES, 0))>0) LOOP
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(ITEM.OWNER, ITEM.TABLE_NAME, null, estimate_percent);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 537


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END LOOP;
END;
/

CREATE OR REPLACE PROCEDURE GATHER_CHANGE_STATS(


estimate_percent NUMBER DEFAULT 30,
change_percent NUMBER DEFAULT 10,
force BOOLEAN DEFAULT TRUE
)
--force false: don't gather when cbo is disable
IS
cbo_enable VARCHAR(3);
BEGIN
--check cbo flag
IF force = FALSE THEN
SELECT VALUE INTO cbo_enable FROM SYS.DV_PARAMETERS WHERE NAME='CBO';
IF UPPER(cbo_enable) = 'OFF' THEN
RETURN;
END IF;
END IF;

--flush modification to table


DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO();

--gather the table changed


FOR ITEM IN (SELECT A.OWNER, A.TABLE_NAME
FROM DBA_TABLES A, DBA_TAB_MODIFICATIONS B
WHERE A.PARTITIONED = 0 AND A.OWNER = B.TABLE_OWNER AND A.TABLE_NAME=B.TABLE_NAME
AND( A.NUM_ROWS is null or
((NVL(B.INSERTS, 0) + NVL(B.UPDATES, 0) + NVL(B.DELETES, 0))>= (CHANGE_PERCENT *
A.NUM_ROWS/100))))
LOOP
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(ITEM.OWNER, ITEM.TABLE_NAME, NULL, estimate_percent);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END LOOP;

--temp table without statistic will gather at the first time


FOR ITEM IN (SELECT OWNER, TABLE_NAME FROM DBA_TABLES WHERE PARTITIONED = 0 AND
TABLE_TYPE <> 'HEAP' AND LAST_ANALYZED IS NULL) LOOP
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(ITEM.OWNER, ITEM.TABLE_NAME, null, estimate_percent);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END LOOP;

END;
/

DECLARE
JOBNO NUMBER;
BEGIN
DBMS_JOB.SUBMIT(JOBNO,'GATHER_DB_STATS(estimate_percent=>30, force=>FALSE);', TRUNC(SYSDATE
+1) + 1/24, 'TRUNC(sysdate+1) +1/24');
COMMIT;
END;
/

DECLARE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 538


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

JOBNO NUMBER;
BEGIN
DBMS_JOB.SUBMIT(JOBNO,'GATHER_CHANGE_STATS(estimate_percent=>30, change_percent=>10,
force=>FALSE);', SYSDATE, 'SYSDATE+15/24/60');
COMMIT;
END;
/

3.15.3 DBMS_OUTPUT

Description
The DBMS_OUTPUT package is used to debug stored procedures and functions or
displays information in zsql.

To view the output of DBMS_OUTPUT in zsql, set serveroutput to ON. The default
parameter value is OFF.
SET serveroutput ON

Interfaces
● PUT_LINE
Description: Outputs characters.
Interface:
DBMS_OUTPUT.PUT_LINE(varchar2);

Parameters: varchar2, indicating characters to be output


Remarks: When this interface is being implemented, the server immediately
sends user content to the zsql client for buffering. The client supports a
maximum of 2^20 records to be printed. The server limits the maximum
length of each output record to 64 KB, whereas this limit is not imposed on
the client side.
● PUT
Description: Outputs characters.
Interface:
DBMS_OUTPUT.PUT(varchar2);

Parameters: varchar2, indicating characters to be output


Remarks: Currently, GaussDB 100 implements this interface in the same way
as it implements PUT_LINE. The client buffers data by using discontinuous
memory. When centrally outputting data, the client adds a linefeed between
every two records to be printed.

Examples
BEGIN
DBMS_OUTPUT.PUT ('hello, ');
DBMS_OUTPUT.PUT_LINE('database!');-- Output"hello, database!".
END;
/

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 539


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.15.4 DBMS_RAFT

Description
This package is used only in GS-Paxos clusters. If it is used in standalone scenarios,
GS-00133 "RAFT: raft is not enabled, or raft module is not inited error" will be
reported.

Interfaces
● RAFT_ADD_MEMBER
Description: Adds a standby node.
● RAFT_DEL_MEMBER
Description: Deletes a standby node.
● RAFT_MONITOR_INFO
Description: Monitors node status. If node status is abnormal, an error will be
returned.
● RAFT_QUERY_INFO
Description: Queries for node status.
● RAFT_SET_PARAM
Description: Sets parameters.
● RAFT_VERSION
Description: Returns version information.

3.15.5 DBMS_RANDOM

Description
The DBMS_RANDOM package is a built-in random number generator provided by
GaussDB 100. It is used to generate random numbers and characters.

Interfaces
● STRING
Description: Generates a random string with the number of characters and
pattern specified.
Interface:
DBMS_RANDOM.STRING (
opt IN CHAR,
len IN INTEGER )
RETURN VARCHAR2;

Parameters:
– opt: Specifies the format of a returning string. By default, the string is
returned in uppercase letters.

▪ 'u', 'U': returning a string in uppercase letters

▪ 'l', 'L': returning a string in lowercase letters

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 540


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

▪ 'a', 'A': returning a string in uppercase and lowercase (mixed) letters

▪ 'x', 'X': returning a string in uppercase letters and digits

▪ 'p', 'P': returning a string in any printable characters


– len: Specifies the length of a returning string.
If the length exceeds 8000 characters, it will be considered 8000
characters. If the length is less than 1, NULL will be returned.
Examples:
SELECT DBMS_RANDOM.STRING('p',5) FROM SYS_DUMMY;
DBMS_RANDOM.STRING('P',5)
-------------------------
na1iz

1 rows fetched.

● VALUE
Description: Generates a random number. If no range is specified, the random
number will be greater than or equal to 0 and less than 1. If a range is
specified, the random number will be greater than or equal to low and less
than high.
Interface:
– No range is specified.
DBMS_RANDOM.VALUE
RETURN NUMBER;

– A range is specified.
DBMS_RANDOM.VALUE(
low IN NUMBER,
high IN NUMBER)
RETURN NUMBER;

Parameters:
– low: Specifies the smallest number in a range from which to generate a
random number.
The number generated may be equal to low.
– high: Specifies the largest number below which to generate a random
number.
The number generated will be less than high.
Return value: A number will be returned.
Examples:
-- No range is specified.
SELECT DBMS_RANDOM.VALUE FROM SYS_DUMMY;
VALUE
----------------------------------------
.2515

1 rows fetched.
-- A range is specified.
SELECT DBMS_RANDOM.VALUE(100,200) FROM SYS_DUMMY;
DBMS_RANDOM.VALUE(100,200)
----------------------------------------
156.2419

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 541


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

3.15.6 DBMS_SQL
Description
The DBMS_SQL package provided by GaussDB 100 is used to execute SQL
statements and return execution results.

Interfaces
DBMS_SQL.RETURN_RESULT
Description: Returns execution result sets.
Precautions:
● Currently, only SQL query results can be returned, and they are not allowed to
be returned through a remote procedure call (PRC).
● Once a statement is returned, it is accessible only to the client or the direct
caller that returns it.
● If a statement executed by clients or any recursion statement is a SQL query
and throws an error, the statement results cannot be returned.
● If an error is raised in executing a stored procedure after the procedure
returns results, the statement results cannot be returned.
● This interface can be used only for stored procedures and anonymous blocks.
Currently, RETURN_RESULT returns cursors only to clients, rather than upper-
layer callers.
● A maximum of 2000 cursors can be returned by a SQL statement at a time.
Interface:
DBMS_SQL.RETURN_RESULT(rc IN OUT SYS_REFCURSOR);

Parameters: rc, a system cursor


Examples:
CREATE OR REPLACE PROCEDURE proc_return(f1 in int) IS
v_refcur2 SYS_REFCURSOR;
BEGIN
OPEN v_refcur2 FOR SELECT 1 FROM SYS_DUMMY;
DBMS_SQL.RETURN_RESULT(v_refcur2);
OPEN v_refcur2 FOR SELECT 2 FROM SYS_DUMMY;
DBMS_SQL.RETURN_RESULT(v_refcur2);
OPEN v_refcur2 FOR SELECT 3 FROM SYS_DUMMY;
DBMS_SQL.RETURN_RESULT(v_refcur2);
END;
/

EXEC proc_return(2);
PL/SQL procedure successfully completed.
ResultSet #1
1
------------
1
1 rows fetched.
ResultSet #2
2
------------
2
1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 542


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

ResultSet #3
3
------------
3
1 rows fetched.

3.15.7 DBMS_STANDARD
Description
The DBMS_STANDARD package is a standard package provided by GaussDB 100.
It is used for transaction management and exception handling.

Interfaces
● SQLCODE
Description: Obtains the current error code.
Interface:
SQLCODE

Parameters:
error_code: error code. The value is an integer.
Remarks: SQLCODE can be used only in a stored procedure body.
● SQLERRM
Description: Obtains the current error information.
Interface:
SQLERRM

Parameters:
message: error information. The value is a string consisting of up to 2048
bytes.
Remarks:
– SQLERRM can be used only in a stored procedure body.
– If there is no error, the return value is null.
● SLEEP
Description: Specifies sleep time for waiting (in seconds).
Interface:
SLEEP(SECONDS IN INTEGER);

Parameters:
SECONDS: sleep time
The value is an integer in the range [1, 2147483647].
● RAISE_APPLICATION_ERROR
Description: Throws a specified exception (including error code and error
information).
Interface:
RAISE_APPLICATION_ERROR (error_code, message[, { TRUE | FALSE } ]);

Parameters:
– error_code: error code.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 543


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

The value is an integer in the range [–20999, –20000].


– message: error information.
The value is a string of up to 896 bytes. It cannot be NULL or empty.
– {TRUE | FALSE}
It is used offer compatibility with other database syntax and is not
processed.

3.15.8 DBMS_STATS

Description
The DBMS_STATS package provided by GaussDB 100 is used for optimizing
statistics.

Interfaces
● DBMS_STATS.AUTO_SAMPLE_SIZE
Description: Returns the default sample size.
Interface:
DBMS_STATS.AUTO_SAMPLE_SIZE

● DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO
Description: Flushes system monitoring information.
Interface:
DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO();

Permission control
The SYS user and DBA can invoke this interface. The ANALYZE ANY system
permission can be invoked to invoke this interface.
● DBMS_STATS.GATHER_TABLE_STATS
Description: Collects statistics about a specified table.
Interface:
DBMS_STATS.GATHER_TABLE_STATS (
ownname VARCHAR2,
tabname VARCHAR2,
partname VARCHAR2 DEFAULT NULL,
estimate_percent NUMBER DEFAULT 10,
block_sample BOOLEAN DEFAULT TRUE,
method_opt VARCHAR2 DEFAULT NULL,
degree NUMBER DEFAULT NULL,
granularity VARCHAR2 DEFAULT NULL,
cascade BOOLEAN DEFAULT NULL,
stattab VARCHAR2 DEFAULT NULL,
statid VARCHAR2 DEFAULT NULL,
statown VARCHAR2 DEFAULT NULL,
no_invalidate BOOLEAN DEFAULT NULL,
stattype VARCHAR2 DEFAULT NULL,
force BOOLEAN DEFAULT NULL);

Parameters:
– ownname: name of the user who will collect statistics
– tabname: name of the table whose statistics will be collected

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 544


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– estimate_percent: sampling rate, with the value range [0.000001,100] If


the value is 0, the sampling rate is determined by the system. Currently,
the sample size is 128MB.
– block_sample: The value true is for block sampling and false for row
sampling. Currently, the value is fixed to true.
– method_opt: statistics collection range. FOR ALL COLUMNS collects
statistics about all columns, and FOR ALL INDEXED COLUMNS collects
statistics only about indexed columns. The former is the default.
Other parameters are optional. They are only for syntax compatibility and
do not take effect currently.
Permission control
– The SYS user and DBA can collect and delete the statistics of all objects.
Common users can only collect and delete their own tables.
– Users with the ANALYZE ANY permission can perform statistics on all
users except the SYS user.
● DBMS_STATS.GATHER_SCHEMA_STATS
Description: Collects statistics on specified users, excluding statistics about
system catalogs, temporary tables, and other tables in recycle bins.
Interface:
DBMS_STATS.GATHER_SCHEMA_STATS (
ownname VARCHAR2,
estimate_percent NUMBER DEFAULT 10,
block_sample BOOLEAN DEFAULT TRUE,
method_opt VARCHAR2 DEFAULT NULL,
degree NUMBER DEFAULT NULL,
granularity VARCHAR2 DEFAULT NULL,
cascade BOOLEAN DEFAULT NULL,
stattab VARCHAR2 DEFAULT NULL,
statid VARCHAR2 DEFAULT NULL,
options VARCHAR2 DEFAULT NULL,
statown VARCHAR2 DEFAULT NULL,
no_invalidate BOOLEAN DEFAULT NULL,
force BOOLEAN DEFAULT NULL,
obj_filter_list ObjectTab DEFAULT NULL);
Parameters:
– ownname: name of the user who will collect statistics
– estimate_percent: sampling rate, with the value range [0.000001,100]. If
the value is 0, the sampling rate is determined by the system. Currently,
the sample size is 128MB.
– block_sample: The value true is for block sampling and false for row
sampling. Currently, the value is fixed to true.
– method_opt: statistics collection range. FOR ALL COLUMNS collects
statistics about all columns, and FOR ALL INDEXED COLUMNS collects
statistics only about indexed columns. The former is the default.
Other parameters are optional. They are compatible with each other and
do not take effect currently.
Permission control
– The SYS user and DBA can collect and delete the statistics of all objects.
Common users can only collect and delete their own tables.
– The ANALYZE ANY permission can be used to collect statistics on all users
except the SYS user.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 545


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● DBMS_STATS.PURGE_STATS
Description: Purges old versions of statistics saved in the dictionary at a
specified time.
Interface:
DBMS_STATS.PURGE_STATS(before_timestamp TIMESTAMP );

Parameters: before_timestamp, purging versions of statistics saved before


this timestamp
Permission control
Only the SYS user and DBA can invoke this interface.
● DBMS_STATS.DELETE_TABLE_STATS
Description: Deletes statistics about a specified table.
Interface:
DBMS_STATS.DELETE_TABLE_STATS (
ownname VARCHAR2,
tabname VARCHAR2,
partname VARCHAR2 DEFAULT NULL,
stattab VARCHAR2 DEFAULT NULL,
statid VARCHAR2 DEFAULT NULL,
cascade_parts BOOLEAN DEFAULT TRUE,
cascade_columns BOOLEAN DEFAULT TRUE,
cascade_indexes BOOLEAN DEFAULT TRUE,
statown VARCHAR2 DEFAULT NULL,
no_invalidate BOOLEAN ,
force BOOLEAN DEFAULT FALSE);

Parameters:
ownname: username
tabname: table name
Other parameters are optional. They are only for syntax compatibility and do
not take effect currently.
Permission control
– The SYS user and DBA can collect and delete the statistics of all objects.
Common users can only collect and delete their own tables.
– The ANALYZE ANY permission can be used to collect statistics on all users
except the SYS user.
● DBMS_STATS.DELETE_SCHEMA_STATS
Description: Deletes statistics about a specified schema.
Interface:
DBMS_STATS.DELETE_SCHEMA_STATS (
ownname VARCHAR2,
stattab VARCHAR2 DEFAULT NULL,
statid VARCHAR2 DEFAULT NULL,
statown VARCHAR2 DEFAULT NULL,
no_invalidate BOOLEAN DEFAULT FALSE,
force BOOLEAN DEFAULT FALSE
);

Parameters:
ownname: username
Other parameters are optional. They are only for syntax compatibility and do
not take effect currently.
Permission control

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 546


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– The SYS user and DBA can collect and delete the statistics of all objects.
Common users can only collect and delete their own tables.
– The ANALYZE ANY permission can be used to collect statistics on all users
except the SYS user.

3.15.9 DBMS_UTILITY

Description
The DBMS_UTILITY package provided by GaussDB 100 is used for data type
processing and calculation.

Interfaces
DBMS_UTILITY.GET_TIME

Description: Returns time (in the unit of 10 ms), which is used to calculate the
time consumed by a program block. The type of return values is unit64.

The time values are used to calculate time differences. Obtaining the time for
once is meaningless.

Interface:
DBMS_UTILITY.GET_TIME();

Parameters: none

Examples:
SELECT DBMS_UTILITY.GET_TIME() FROM SYS_DUMMY;
DBMS_UTILITY.GET_TIME()
-----------------------
156419546633

1 rows fetched.

DBMS_UTILITY.COMPILE_SCHEMA

Description: Recompiles objects in a specified schema.

Interface:
DBMS_UTILITY.COMPILE_SCHEMA(
schema IN VARCHAR2,
compile_all IN BOOLEAN DEFAULT TRUE,
reuse_settings IN BOOLEAN DEFAULT FALSE
);

Parameters:

● schema: name of the schema for recompilation


● compile_all:
– true: All objects are recompiled.
– false: Only invalid and unknown objects are recompiled.
● reuse_settings: compatibility syntax, which does not take effect currently.

Note:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 547


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Common users can compile only their own objects, and users SYS and DBA can
recompile the objects in all schemas.

3.15.10 DBMS_DIAGNOSE
Description
The DBMS_DIAGNOSE package is used to control the permissions to access
functions. Non-SYS users can access functions only after the EXECUTE ON
DBMS_DIAGNOSE permission is granted.

Interfaces
● DBMS_DIAGNOSE.DBA_IND_POS
Syntax:
DBMS_DIAGNOSE.DBA_IND_POS('column_list','column_id')

Purpose: It is a diagnosis function and is used to return the position of the


column ID in the column ID set.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– If column_list does not contain column_id, 0 is returned.
– The position starts from 1.
– column_list is a string. It is a set of column IDs separated by commas (,).
A single column ID is of the NUMERIC type. The value range is [–
9223372036854775808, 9223372036854775807].
– column_id is of the NUMERIC type. The value range is [–
9223372036854775808, 9223372036854775807].
Examples:
Return the position of column_id in column_list.
SELECT DBMS_DIAGNOSE.DBA_IND_POS('2,3,1,0,4','4') from SYS_DUMMY;

DBMS_DIAGNOSE.DBA_IND_POS('2,3,1,0,4','4')
-------------------------------------------
5

1 rows fetched.

● DBMS_DIAGNOSE.DBA_LISTCOLS
Syntax:
DBMS_DIAGNOSE.DBA_LISTCOLS(user_name,table_name|view_name, column_list)

Purpose: It is a diagnosis function. It converts the column set under a


username, table name, or view name to a column name set in the form of
column ID.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– user_name is a string. It must be an existing username in the database.
– table_name|view_name is a string. It must be the names of the table and
view that already exist in the corresponding user in the database.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 548


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– column_list is a string. It is a set of column IDs. The columns must exist in


the table.
Examples:
Return column names. The database administrator GAUSSDBA is used as an
example.
CREATE TABLE GAUSSDBA.TEST(A INT, B INT);
SELECT DBMS_DIAGNOSE.DBA_LISTCOLS('GAUSSDBA','TEST','0,1');

DBMS_DIAGNOSE.DBA_LISTCOLS('GAUSSDBA','TEST','0,1')
----------------------------------------------------------------
A, B

1 rows fetched.

● DBMS_DIAGNOSE.DBA_PARTITIONED_INDSIZE
Syntax:
DBMS_DIAGNOSE.DBA_PARTITIONED_INDSIZE(size_type,user_name,table_name,index_name)
Purpose: It is a diagnosis function and is used to return the size of the index
in the partitioned table.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– size_type: size type
▪ 0: number of bytes

▪ 1: number of pages

▪ 2: number of extents
– user_name is a string. It must be an existing username in the database.
– table_name is a string. It must be an existing table name of the
corresponding user in the database. Note that the table must be a
partitioned table.
– index_name is a string. This parameter is optional. If this parameter is not
specified, the total size of all indexes in the partitioned table is returned.
– Only local indexes in the partitioned table are supported. The size of
global indexes is 0.
Examples:
Return the total size of indexes in the partitioned table.
-- Create a partitioned table.
create table test_part_t1(f1 int, f2 real, f3 number, f4 char(30), f5 varchar(30), f6 date, f7 timestamp)
PARTITION BY RANGE(f1)
(
PARTITION p1 values less than(10),
PARTITION p2 values less than(20),
PARTITION p3 values less than(30),
PARTITION p4 values less than(MAXVALUE)
);
-- Create indexes on the partitioned table.
create index idx_t1_1 on test_part_t1(f2,f3);
create index idx_t1_2 on test_part_t1(f4,f5) local;
-- Insert data into the partitioned table.
insert into test_part_t1 values(5, 15, 28, 'abcd', 'abcd', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'));
insert into test_part_t1 values(6, 16, 29, '16', '29', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'));

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 549


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Query for the total size of indexes on the partitioned table.


SELECT DBMS_DIAGNOSE.DBA_PARTITIONED_INDSIZE(0,'GAUSSDBA','TEST_PART_T1');

DBMS_DIAGNOSE.DBA_PARTITIONED_INDSIZE(0,'GAUSSDBA','TEST_PART_T1')
------------------------------------------------------------------
65536

1 rows fetched.
● DBMS_DIAGNOSE.DBA_PARTITIONED_LOBSIZE
Syntax:
DBMS_DIAGNOSE.DBA_PARTITIONED_LOBSIZE(size_type,user_name,table_name,column_id)
Purpose: It is a diagnosis function and is used to return the segment size of
the LOB column in the partitioned table.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– size_type: size type
▪ 0: number of bytes

▪ 1: number of pages

▪ 2: number of extents
– user_name is a string. It must be an existing username in the database.
– table_name is a string. It must be an existing table name of the
corresponding user in the database. The table must be a partitioned
table.
– column_id is an integer. It is optional. If it is not specified, the total value
of all LOB columns in the partitioned table is returned. Its value must be
the ID of the column where the LOB column is located.
– By default, if the storage space consumed by LOB data does not exceed
4000 bytes (including the extra overhead of 12 to 14 bytes), the LOB data
adopts the inline mode and data is stored in the heap segment instead of
the LOB segment. Therefore, the result of this function does not contain
the LOB data stored in inline mode.
Examples:
Return the total size of the LOB column in the partitioned table.
-- Create a partitioned table.
create table test_part_t1(f1 int, f2 real, f3 number, f4 char(30), f5 varchar(30), f6 date, f7
timestamp,f8 clob)
PARTITION BY RANGE(f1)
(
PARTITION p1 values less than(10),
PARTITION p2 values less than(20),
PARTITION p3 values less than(30),
PARTITION p4 values less than(MAXVALUE)
);
-- Create indexes on the partitioned table.
create index idx_t1_1 on test_part_t1(f2,f3);
create index idx_t1_2 on test_part_t1(f4,f5) local;
-- Insert data into the partitioned table.
insert into test_part_t1 values(5, 15, 28, 'abcd', 'abcd', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'),'xxx');
insert into test_part_t1 values(6, 16, 29, '16', '29', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'),'yyy');
-- Query the total size of the LOB column in the partitioned table.
SELECT DBMS_DIAGNOSE.DBA_PARTITIONED_LOBSIZE(0,'GAUSSDBA','TEST_PART_T1');

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 550


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DBMS_DIAGNOSE.DBA_PARTITIONED_LOBSIZE(0,'SYS','TEST_PART_T1')
------------------------------------------------------------------
0

1 rows fetched.
● DBMS_DIAGNOSE.DBA_PARTITIONED_TABSIZE
Syntax:
DBMS_DIAGNOSE.DBA_PARTITIONED_TABSIZE(size_type,user_name,table_name)
Purpose: It is a diagnosis function and is used to return the size of the
partitioned table.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– size_type: size type
▪ 0: number of bytes

▪ 1: number of pages

▪ 2: number of extents
– user_name is a string. It must be an existing username in the database.
– table_name is a string. It must be an existing table name of the
corresponding user in the database. The table must be a partitioned
table.
Examples:
Return the size of the partitioned table.
-- Create a partitioned table.
create table test_part_t1(f1 int, f2 real, f3 number, f4 char(30), f5 varchar(30), f6 date, f7 timestamp)
PARTITION BY RANGE(f1)
(
PARTITION p1 values less than(10),
PARTITION p2 values less than(20),
PARTITION p3 values less than(30),
PARTITION p4 values less than(MAXVALUE)
);
-- Create indexes on the partitioned table.
create index idx_t1_1 on test_part_t1(f2,f3);
create index idx_t1_2 on test_part_t1(f4,f5) local;
-- Insert data into the partitioned table.
insert into test_part_t1 values(5, 15, 28, 'abcd', 'abcd', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'));
insert into test_part_t1 values(6, 16, 29, '16', '29', to_date('2018/01/24', 'YYYY/MM/DD'),
to_timestamp('2018-01-24 16:00:00.00', 'YYYY-MM-DD HH24:MI:SS.FF3'));
-- Return the size of the partitioned table.
select DBMS_DIAGNOSE.DBA_PARTITIONED_TABSIZE(0,'GAUSSDBA','TEST_PART_T1');

DBMS_DIAGNOSE.DBA_PARTITIONED_TABSIZE(0,'GAUSSDBA','TEST_PART_T1')
-------------------------------------------------------------------
65536

1 rows fetched.
● DBMS_DIAGNOSE.DBA_SEGSIZE
Syntax:
DBMS_DIAGNOSE.DBA_SEGSIZE(size_type,table_entry)
Purpose: It is a diagnosis function and is used to return the size of an
ordinary table.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 551


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– size_type: size type
▪ 0: number of bytes

▪ 1: number of pages

▪ 2: number of extents
– table_entry: entry of an ordinary table, which can be obtained by
querying the system catalog SYS_TABLES.
Examples:
Return the size of an ordinary table.
-- Create an ordinary table.
CREATE TABLE TEST(A INT, B INT);
-- Insert data.
INSERT INTO TEST VALUES(1,1);
-- Show the table size.
SELECT DBMS_DIAGNOSE.DBA_SEGSIZE(0, T.ENTRY) FROM SYS_TABLES T WHERE T.NAME = 'TEST';

DBMS_DIAGNOSE.DBA_SEGSIZE(0, T.ENTRY)
--------------------------------------
65536

1 rows fetched.
● DBMS_DIAGNOSE.DBA_SPACE_NAME
Syntax:
DBMS_DIAGNOSE.DBA_SPACE_NAME(space_id)
Purpose: It is a diagnosis function and is used to return the name of the table
where the tablespace ID is located.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– This function is used to return the name of the table where the
tablespace ID is located. If the tablespace ID does not exist, an error is
reported.
– space_id: tablespace ID
Examples:
Return the name of the table where the tablespace ID is located.
SELECT DBMS_DIAGNOSE.DBA_SPACE_NAME(0);

DBMS_DIAGNOSE.DBA_SPACE_NAME(0)
----------------------------------------------------------------
SYSTEM

1 rows fetched.
● DBMS_DIAGNOSE.DBA_SPCSIZE
Syntax:
DBMS_DIAGNOSE.DBA_SPCSIZE(space_id,size_type_name)
Purpose: It is a diagnosis function and is used to return the tablespace size.
Note:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 552


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

– This function is a diagnosis function and cannot be directly invoked by


non-SYS users.
– space_id: tablespace ID
– size_type_name: size type
▪ 'PAGE': size of each page, in bytes. The default value is 8K.

▪ 'TOTAL': total size

▪ 'USED': used size


Examples:
Return the tablespace size.
SELECT DBMS_DIAGNOSE.DBA_SPCSIZE(0,'TOTAL');

DBMS_DIAGNOSE.DBA_SPCSIZE(0,'TOTAL')
--------------------------------------
134217728

1 rows fetched.
● DBMS_DIAGNOSE.DBA_TABTYPE
Syntax:
DBMS_DIAGNOSE.DBA_TABTYPE(table_type_id)
Purpose: It is a diagnosis function and is used to return the table type name
corresponding to the table type ID.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– If the table type ID does not exist and is not NULL, UNKNOWN_TYPE is
returned.
– table_type_id: table type ID
▪ 0: HEAP, ordinary table (heap table)

▪ 1: IOT, index-organized table

▪ 2: TRANS_TEMP, transaction-level temporary table

▪ 3: SESSION_TEMP, session-level temporary table

▪ 4: NOLOGGING, nologging table

▪ 5: EXTERNAL, external table


Examples:
Return the table type name corresponding to the table type ID.
SELECT DBMS_DIAGNOSE.DBA_TABTYPE(3);

DBMS_DIAGNOSE.DBA_TABTYPE(3)
----------------------------------------------------------------
SESSION_TEMP

1 rows fetched.
● DBMS_DIAGNOSE.DBA_USER_NAME
Syntax:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 553


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

DBMS_DIAGNOSE.DBA_USER_NAME(user_id)

Purpose: It is a diagnosis function and is used to return the username


corresponding to the user ID.
Note:
– This function is a diagnosis function and cannot be directly invoked by
non-SYS users.
– If the user ID does not exist, an error message is displayed, indicating
that the user does not exist.
– user_id is a non-negative integer.
Examples:
Return the user name corresponding to the user ID.
select DBMS_DIAGNOSE.dba_user_name(1);

DBMS_DIAGNOSE.DBA_USER_NAME(1)
----------------------------------------------------------------
PUBLIC

1 rows fetched.

3.16 User-defined Functions


Description
A function is used to return specific data. One or more values can be returned. A
function must contain one or more RETURN clauses.
User-defined functions (UDFs) can be directly invoked by stored procedures or
used in SQL statements as common functions. Table 3-59 lists check rules when
user-defined functions are used.

Table 3-59 Check rules


Outer SQL Statement SQL Statement in a Return Information of
for a UDF UDF the Outer SQL
Statement

SELECT Any table SELECT Returns execution


results.

SELECT Table in the SQL INSERT/UPDATE/ Returns the error


statement of a UDF DELETE/MERGE message "GS-00927, The
trigger or user-defined
function used by a SQL
statement which is
adjusting a table %s.%s
did not find the table.".

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 554


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Outer SQL Statement SQL Statement in a Return Information of


for a UDF UDF the Outer SQL
Statement

UPDATE/DELETE Table SELECT/INSERT/UPDATE/ Returns the error


in the SQL statement of DELETE/MERGE message "GS-00927, The
a UDF trigger or user-defined
function used by a SQL
statement which is
adjusting a table %s.%s
did not find the table.".

INSERT Any table SELECT/INSERT/UPDATE/ Records a success data


DELETE/MERGE insertion into the
database and returns the
message "n rows
affected."

MERGE Any table SELECT Returns execution


results.

MERGE Table in the SQL INSERT/UPDATE/ Returns the error


statement of a UDF DELETE/MERGE message "GS-00927, The
trigger or user-defined
function used by a SQL
statement which is
adjusting a table %s.%s
did not find the table.".

Precautions
● If the name of a UDF is the same as that of a system function, the database
preferentially invokes the system function. To make the UDF preferential,
configure it in the $GSDB_DATA/cfg/udf.ini file in the format of
user_name.function_name. Only one UDF can be written in a line, and no
comments are allowed. The UDF name is case-sensitive during the
configuration in udf.ini. The configuration takes effect only after the database
is restarted.
● If a compilation error occurs in the UDF specified in udf.ini, GaussDB 100
determines that the UDF cannot be matched and tries to use the system
function. In this case, the compilation error information of the UDF will be
overwritten.
● The permission for the udf.ini file must be limited to users in the database
user group dbgrp. The permission is 600.
● When running a UDF without parameters, you can directly specify the UDF
name without parentheses.
● Be cautious to use statements that affect transaction commit or rollback in a
UDF body. If there are such statements and the UDF is contained in a DML
operation, the error GS-00973 will be reported, indicating that the operation
is not executed. However, the statements can be normally invoked in stored
procedures or anonymous blocks.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 555


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● The following enumerates the statements that affect transaction commit or


rollback:
– All DDL statements
– COMMIT
– ROLLBACK
– SAVEPOINT
– SET TRANSACTION
– ALTER SESSION
– ALTER SYSTEM KILL SESSION
– GRANT
– REVOKE

Syntax
CREATE [OR REPLACE] [IF [NOT] EXIST] FUNCTION [schema_name.]function_name [(args_list)] RETURN
data_type
{ IS | AS }
[param-list]
BEGIN
statement;
RETURN expression;
...
END;

Parameter Description
● schema_name
Specifies the owner of the function.
● function_name
Specifies the name of the function.
● args_list
Specifies a list of input parameters. Default parameter values can be used.
● data_type
Specifies the data type of return values.
● param-list
Specifies a list of variables for declaration. Default variable values can be
used. The format is as follows: variant_name data_type [:= default_expr];
● statement
Specifies the statement where the function appears.
You can use basic, dynamic, control, exception, or other statements. For
details about basic statements, see Basic Statements. For details about
dynamic statements, see Dynamic Statements. For details about control
statements, see Control Statements. For details about other statements, see
Other Statements.
● expression
Specifies an expression for return values. The value can be a common variable
or expression. Subquery results cannot be directly returned.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 556


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Examples
● Create a UDF ztest_f1.

NOTICE

Stored procedures and functions are stored in the same system catalog. If the
UDF to be created has the same name as an existing stored procedure,
creating the UDF will fail. Therefore, before creating a UDF, you need to
delete the stored procedure with the same name.

-- Delete the existing stored procedure with the same name.


DROP PROCEDURE IF EXISTS ztest_f1;
-- Delete the user-defined function with the same name as the stored procedure.
DROP FUNCTION IF EXISTS ztest_f1;

NOTICE

In a statement for creating a UDF, the last slash (/) is used to indicate the end
of the definition statement. It cannot be omitted and must be placed in a
different line.

-- Create the ztest_f1 UDF:


CREATE OR REPLACE FUNCTION ztest_f1(a INT, b VARCHAR2) RETURN INT
AS
c INT;
BEGIN
c := a;
RETURN c;
END ztest_f1;
/

● Create a UDF USER_FUNC_QUERY_TEMP and use it.


-- Delete a table USER_FUNC_TEMP, if any:
DROP TABLE IF EXISTS USER_FUNC_TEMP;
-- Create the USER_FUNC_TEMP table:
CREATE TABLE USER_FUNC_TEMP(ID INT);
-- Insert records into the USER_FUNC_TEMP table:
INSERT INTO USER_FUNC_TEMP VALUES(1);
-- Create a UDF USER_FUNC_QUERY_TEMP, and specify a SQL statement in the UDF to query the
USER_FUNC_TEMP table:
CREATE OR REPLACE FUNCTION USER_FUNC_QUERY_TEMP(a INT) RETURN INT
AS
c INT;
d INT;
BEGIN
c := a;
SELECT ID INTO d FROM USER_FUNC_TEMP WHERE ROWNUM = c;
RETURN d;
END USER_FUNC_QUERY_TEMP;
/
-- The outer SQL statement for the UDF USER_FUNC_QUERY_TEMP UDF is a SELECT statement. The
table used by the outer SQL statement is the same as that used by the SQL statement in the UDF. The
execution results of the SELECT statement are returned.
SELECT * FROM USER_FUNC_TEMP WHERE USER_FUNC_QUERY_TEMP(1) = 1;

ID
------------
1

1 rows fetched.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 557


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- The outer SQL statement for the UDF USER_FUNC_QUERY_TEMP UDF is an INSERT statement. The
table used by the outer SQL statement is the same as that used by the SQL statement in the UDF. The
execution results of the INSERT statement are returned.
INSERT INTO USER_FUNC_TEMP VALUES(USER_FUNC_QUERY_TEMP(1));
1 rows affected.
-- The outer SQL statement of the UDF USER_FUNC_QUERY_TEMP is an UPDATE statement. The
table used by the outer SQL statement is the same as that used by the SQL in the UDF. The error
message "GS-00927: The trigger or user-defined function used by a SQL statement which is adjusting
a table %s.%s did not find the table." is returned.
UPDATE USER_FUNC_TEMP SET ID=100 WHERE ID = USER_FUNC_QUERY_TEMP(1);
GS-00927, [7:1]The trigger or user-defined function used by a SQL statement which is adjusting a
table %s.%s did not find the table..
-- The outer SQL statement for the USER_FUNC_QUERY_TEMP UDF is a DELETE statement. The table
used by the outer SQL statement is the same as that used by the SQL statement in the UDF. The error
message "GS-00927:"The trigger or user-defined function used by a SQL statement which is adjusting
a table %s.%s did not find the table." is returned.
DELETE FROM USER_FUNC_TEMP WHERE ID = USER_FUNC_QUERY_TEMP(1);
GS-00927, [7:1]The trigger or user-defined function used by a SQL statement which is adjusting a
table %s.%s did not find the table..

● Create a UDF USER_FUNC_DELETE_TEMP and use it.


-- Delete a table USER_FUNC_TEMP01, if any:
DROP TABLE IF EXISTS USER_FUNC_TEMP01;
-- Create the USER_FUNC_TEMP01 table:
CREATE TABLE USER_FUNC_TEMP01(ID INT);
-- Insert records into the USER_FUNC_TEMP01 table:
INSERT INTO USER_FUNC_TEMP01 VALUES(1);
-- Create a UDF USER_FUNC_DELETE_TEMP, and specify a SQL statement in the UDF to delete records
from the USER_FUNC_TEMP01 table:
CREATE OR REPLACE FUNCTION USER_FUNC_DELETE_TEMP(a INT) RETURN INT
AS c INT;
BEGIN
c := a;
DELETE FROM USER_FUNC_TEMP01 WHERE ID = c;
return c;
END USER_FUNC_DELETE_TEMP;
/
-- The outer SQL statement for the UDF USER_FUNC_DELETE_TEMP is a SELECT statement. The table
used by the outer SQL statement is the same as that used by the SQL statement in the UDF. SELECT
USER_FUNC_DELETE_TEMP(100) FROM USER_FUNC_TEMP01;
-- An error is returned.
GS-00927, [5:1]The trigger or user-defined function used by a SQL statement which is adjusting a
table %s.%s did not find the table..

3.17 Triggers
A trigger is a special type of stored procedure that is triggered by a specified
event. It is generally used for auditing and backing up data.

3.17.1 Examples
This example demonstrates the entire process of using a trigger, including creating
and deleting the trigger.

Statements
-- Delete a table T_TRIG, if any:
DROP TABLE IF EXISTS T_TRIG;
-- Delete a table T_TRIG_LOG, if any:
DROP TABLE IF EXISTS T_TRIG_LOG;
-- Delete a sequence TRIG_LOG_SEQ, if any:
DROP SEQUENCE IF EXISTS TRIG_LOG_SEQ;
-- Delete a trigger TRIG_AFTER_INSERT, if any:
DROP TRIGGER IF EXISTS TRIG_AFTER_INSERT;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 558


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Delete a trigger TRIG_BEFORE_INSERT, if any:


DROP TRIGGER IF EXISTS TRIG_BEFORE_INSERT;
-- Create the T_TRIG table:
CREATE TABLE T_TRIG (ID INT, CREATE_DATE TIMESTAMP);
-- Create the T_TRIG_LOG table:
CREATE TABLE T_TRIG_LOG (LOG_SEQ INT,LOG_DESC VARCHAR(30), CREATE_DATE TIMESTAMP);
-- Create the TRIG_LOG_SEQ sequence:
CREATE SEQUENCE TRIG_LOG_SEQ START WITH 1 INCREMENT BY 1;

NOTICE

When a row trigger is used, the verification rules are different.


● Table 3-60 lists rules for TRIG_BEFORE_EACH_ROW.
● Table 3-61 lists rules for TRIG_AFTER_EACH_ROW.

Table 3-60 TRIG_BEFORE_EACH_ROW trigger rules

Outer SQL Statement SQL Inside the Trigger Validation Result

UPDATE/DELETE SELECT/INSERT/ ERR_TAB_MUTATING


UPDATE/DELETE/
MERGE same table as
that in the outer SQL
statement
INSERT SELECT/INSERT/ OK
UPDATE/DELETE/
MERGE any table

MERGE SELECT any table OK

MERGE INSERT/UPDATE/ ERR_TAB_MUTATING


DELETE/MERGE same
table as that in the outer
SQL statement

Table 3-61 TRIG_AFTER_EACH_ROW trigger rules

Outer SQL Statement SQL Inside the Trigger Validation Result

UPDATE/DELETE SELECT/INSERT/ ERR_TAB_MUTATING


UPDATE/DELETE/
MERGE same table as
that in the outer SQL
statement
INSERT SELECT/INSERT/ ERR_TAB_MUTATING
UPDATE/DELETE/
MERGE same table as
that in the outer SQL
statement

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 559


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Outer SQL Statement SQL Inside the Trigger Validation Result

MERGE SELECT any table OK

MERGE INSERT/UPDATE/ ERR_TAB_MUTATING


DELETE/MERGE same
table as that in the outer
SQL statement

-- Create table 1:
CREATE TABLE T_TRIG_1 (F_INT1 INT, F_INT2 INT, F_CHAR1 CHAR(16), F_DATE DATE);

Succeed.
-- Insert a piece of data to table 1:
INSERT INTO T_TRIG_1 VALUES(1,2,'A','2017-12-11 14:08:00');

1 rows affected.
-- Create a row trigger of Table 1, which is triggered each time a statement is inserted into Table 1, and a
statement for updating Table 1 exists in the trigger.
CREATE OR REPLACE TRIGGER TEST_TRIG AFTER INSERT ON T_TRIG_1
FOR EACH ROW
BEGIN
UPDATE T_TRIG_1 SET F_INT1 = 1;
END;
/

Succeed.
-- Insert a piece of data to table 1, which fires the trigger to update the same table and causes an error:
INSERT INTO T_TRIG_1 VALUES(1,2,'A','2017-12-11 14:08:00');

GS-00932, PL/SQL(SYS.TEST_TRIG) terminated with execute errors


[4:3] GS-00927, The trigger or user-defined function used by a SQL statement which is adjusting a table %s.
%s did not find the table..

NOTICE

In a statement for creating a trigger, the last slash (/) is used to indicate the end
of the definition statement. It cannot be omitted and must be placed in a different
line.

-- Create the TRIG_AFTER_INSERT trigger. After a record is inserted into the T_TRIG table, a record with
description "after insert" will be written into the T_TRIG_LOG table.
CREATE OR REPLACE TRIGGER TRIG_AFTER_INSERT AFTER INSERT ON T_TRIG
BEGIN
INSERT INTO T_TRIG_LOG VALUES(TRIG_LOG_SEQ.NEXTVAL,'after insert',systimestamp);
END;
/
-- Create the TRIG_BEFORE_INSERT trigger. Before a record is inserted into the T_TRIG table, a record with
description "before insert" will be written into the T_TRIG_LOG table.
CREATE OR REPLACE TRIGGER TRIG_BEFORE_INSERT BEFORE INSERT ON T_TRIG
BEGIN
INSERT INTO T_TRIG_LOG VALUES(TRIG_LOG_SEQ.NEXTVAL,'before insert',systimestamp);
END;
/
-- Insert a record into the T_TRIG table:
INSERT INTO T_TRIG VALUES (1,systimestamp);
-- Query the T_TRIG table:
SELECT * FROM T_TRIG;

ID CREATE_DATE
------------ --------------------------------

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 560


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

1 2018-09-11 15:59:36.970759

1 rows fetched.
-- Query the T_TRIG_LOG table:
SELECT * FROM T_TRIG_LOG;

LOG_SEQ LOG_DESC CREATE_DATE


------------ ------------------------------ --------------------------------
1 before insert 2018-09-11 15:59:36.967120
2 after insert 2018-09-11 15:59:36.974199

2 rows fetched.
-- Delete a trigger:
DROP TRIGGER IF EXISTS T_TRIG;

3.17.2 Creating a Trigger

Description
Create a trigger.

Precautions
● OF column_name is supported only in row triggers, and the column data
type cannot be LOB.
● DDL and DCL operations are not allowed inside triggers. Common users
cannot create objects for system users.
● If a row trigger uses the insert operation (BEFORE | AFTER INSERT) as the
trigger event, such an operation on the table on which the trigger is created is
not allowed inside the trigger. If a row trigger uses the update operation
(BEFORE | AFTER UPDATE) as the trigger event, such an operation on the
table on which the trigger is created is not allowed inside the trigger. If a row
trigger uses the delete operation (BEFORE | AFTER DELETE) as the trigger
event, such an operation on the table on which the trigger is created is not
allowed inside the trigger.
● A maximum of eight triggers can be created on a table.
● Triggers cannot be created on local temporary tables.
● Triggers of a common user cannot be created on the table of user SYS.

Syntax
CREATE [ OR REPLACE ] TRIGGER [ schema_name. ]trigger_name
{ BEFORE | AFTER } { DELETE | INSERT | UPDATE [ OF column_name[,...] ] } [ OR ... ] ON table_name
[FOR EACH ROW]
[ param_list ]
BEGIN
statements;
END;

Parameter Description
● OR REPLACE
Replaces a trigger if it already exists.
● schema_name
Specifies the owner of the trigger to be created.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 561


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

● trigger_name
Specifies the name of the trigger to be created.
● { BEFORE | AFTER }
Specifies the timing of a trigger. BEFORE indicates that the trigger runs before
the specified database operation, and AFTER indicates that the trigger runs
after the specified database operation.
● { DELETE | INSERT | UPDATE [ OF column_name[,...] ] } [ OR ... ]
Specifies a trigger event, that is, an operation upon which a trigger fires.
– DELETE: The trigger fires when there is a delete operation in the
database.
– INSERT: The trigger fires when there is an insert operation in the
database.
– UPDATE: The trigger fires when there is an update operation in the
database.
– MERGE: The trigger fires when there is an update or insert operation
from other data sources.
– [ OR ... ] indicates that multiple trigger events specified are connected by
OR. For example, INSERT OR DELETE indicates that the trigger event is
an insert or delete operation.
● table_name
Specifies the table on which a trigger will be created.
● [FOR EACH ROW]
Specifies a row trigger. If no FOR EACH ROW is used, a statement trigger will
be created.
● param_list
Declares a list of parameters. For details about declaration syntax, see
DECLARE Syntax.
● statements
Specifies statements inside a trigger. You are not allowed to leave this
parameter empty because an error will be reported if it is empty. You can use
basic, dynamic, control, exception, or other statements. For details about basic
statements, see Basic Statements; dynamic statements, see Dynamic
Statements; control statements, see Control Statements; other statements,
see Other Statements; user-defined functions, see User-defined Functions;
and stored procedures, see Creating a Stored Procedure.

Examples
-- Delete a table T_TRIG, if any:
DROP TABLE IF EXISTS T_TRIG;
-- Delete a table T_TRIG_LOG, if any:
DROP TABLE IF EXISTS T_TRIG_LOG;
-- Delete a sequence TRIG_LOG_SEQ, if any:
DROP SEQUENCE IF EXISTS TRIG_LOG_SEQ;
-- Delete a trigger TRIG_AFTER_INSERT, if any:
DROP TRIGGER IF EXISTS TRIG_AFTER_INSERT;
-- Delete a trigger TRIG_BEFORE_INSERT, if any:
DROP TRIGGER IF EXISTS TRIG_BEFORE_INSERT;
-- Create the T_TRIG table:
CREATE TABLE T_TRIG (ID INT, CREATE_DATE TIMESTAMP);

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 562


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

-- Create the T_TRIG_LOG table:


CREATE TABLE T_TRIG_LOG (LOG_SEQ INT,LOG_DESC VARCHAR(30), CREATE_DATE TIMESTAMP);
-- Create the TRIG_LOG_SEQ sequence:
CREATE SEQUENCE TRIG_LOG_SEQ START WITH 1 INCREMENT BY 1;

NOTICE

In a statement for creating a trigger, the last slash (/) is used to indicate the end
of the definition statement. It cannot be omitted and must be placed in a different
line.

-- Create the TRIG_AFTER_INSERT trigger. After a record is inserted into the T_TRIG table, a record with
description "after insert" will be written into the T_TRIG_LOG table.
CREATE OR REPLACE TRIGGER TRIG_AFTER_INSERT AFTER INSERT ON T_TRIG
BEGIN
INSERT INTO T_TRIG_LOG VALUES(TRIG_LOG_SEQ.NEXTVAL,'after insert',systimestamp);
END;
/
-- Create the TRIG_BEFORE_INSERT trigger. Before a record is inserted into the T_TRIG table, a record with
description "before insert" will be written into the T_TRIG_LOG table.
CREATE OR REPLACE TRIGGER TRIG_BEFORE_INSERT BEFORE INSERT ON T_TRIG
BEGIN
INSERT INTO T_TRIG_LOG VALUES(TRIG_LOG_SEQ.NEXTVAL,'before insert',systimestamp);
END;
/
-- Insert a record into the T_TRIG table:
INSERT INTO T_TRIG VALUES (1,systimestamp);
-- Query the T_TRIG table:
SELECT * FROM T_TRIG;

ID CREATE_DATE
------------ --------------------------------
1 2018-09-11 15:59:36.970759

1 rows fetched.
-- Query the T_TRIG_LOG table:
SELECT * FROM T_TRIG_LOG;

LOG_SEQ LOG_DESC CREATE_DATE


------------ ------------------------------ --------------------------------
1 before insert 2018-09-11 15:59:36.967120
2 after insert 2018-09-11 15:59:36.974199

2 rows fetched.

3.17.3 Deleting a Trigger

Description
Delete a trigger.

Precautions
If the trigger to be deleted exists, the keyword IF EXISTS will be optional. If there
is uncertainty about whether the trigger to be deleted exists, DROP TRIGGER IF
EXISTS trigger_name; is recommended. This prevents errors from being returned
because of a trigger not existed. Common users cannot delete the objects of
system users.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 563


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Syntax
DROP TRIGGER [ IF EXISTS ] [ schema_name. ]trigger_name;

Parameters
● IF EXISTS
Indicates that no error will be reported and the delete operation will be
displayed as successful if the trigger to be deleted does not exist.
● schema_name
Specifies the owner of the trigger to be deleted.
● trigger_name
Specifies the name of the trigger to be deleted.

Examples
-- Delete a trigger:
DROP TRIGGER IF EXISTS TRIG_BEFORE_INSERT1;

3.17.4 Modifying a Trigger

Description
Modify a trigger.

Syntax
ALTER TRIGGER [ schema_name. ]trigger_name { ENABLE | DISABLE };

Parameters
● schema_name
Specifies the owner of the trigger to be modified.
● trigger_name
Specifies the name of the trigger to be modified.
● ENABLE
The trigger takes effect.
● DISABLE
The trigger does not take effect.

Examples
-- Enable the trigger:
ALTER TRIGGER trigger_name ENABLE;

3.18 Object Dependencies


GaussDB 100 allows you to view the information about dependencies between
objects in the system. When an object is modified, the status information of other
objects that depend on the object is synchronously updated.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 564


GaussDB 100
R&D Documentation (Standalone) 3 SQL Syntax Reference

Currently, the following database objects can be interdependent: tables, views,


sequences, synonyms, triggers, user-defined functions, and stored procedures.
Currently, only objects can depend on each other. A finer-level dependency is not
supported, for example, table columns and stored procedure parameters cannot
depend on each other.
When the structure of an object is changed, the status of other objects that
directly or indirectly depend on the object is changed to UNKNOWN, but the
compilation of the other objects is not triggered.
Objects involved in dynamic SQL statements are excluded from the dependency
relationships. If a SQL statement uses a local temporary table, it will be regarded
as a dynamic SQL statement, and its objects are excluded from the dependency
relationships.
You can query the ALL_DEPENDENCIES, DBA_DEPENDENCIES, and
USER_DEPENDENCIES views to observe the dependencies between current
objects.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 565


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

4 Interface Mapping (GaussDB 100 Native


Interface Names vs. Mainstream Database
Interface Names)

4.1 Data Dictionary Tables


Table 4-1 Name mapping of data dictionary tables (GaussDB 100 native interface
names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 566


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 567


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

4.2 DBA Views


Table 4-2 Name mapping of DBA views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 568


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 569


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 570


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

4.3 User Views


Table 4-3 Name mapping of user views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_ARGUMENTS ALL_ARGUMENTS

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 571


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 572


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

4.4 Dynamic Performance Views


Table 4-4 Name mapping of dynamic performance views (GaussDB 100 native
interface names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 573


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 574


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 575


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
R&D Documentation (Standalone) Names vs. Mainstream Database Interface Names)

4.5 Configuration Parameters


Table 4-5 Name mapping of configuration parameters (GaussDB 100 native
interface names vs. mainstream database interface names)
GaussDB 100 Native Interface Name Mainstream Database Interface
Name

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 576


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

5 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are


a set of features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a


thread database. The thread is used to archive database logs to a
specified path.

atomicity One of the ACID features of database transactions. Atomicity


means that a transaction is composed of an indivisible unit of
work. All operations performed in a transaction must either be
committed or uncommitted. If an error occurs during transaction
execution, the transaction will be rolled back to the state when it
was not committed.

backup A backup, or the process of backing up, refers to the copying and
archiving of computer data. Backup data can be used for
restoration in case of data loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false
logical condition. A bit is physically represented by an element
such as high or low voltage at one point in a circuit, or a small
spot on a disk that is magnetized in one way or the other. A single
bit conveys little information a human would consider meaningful.
A group of eight bits, however, makes up a byte, which can be
used to represent many types of information, such as a letter of
the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at


a certain time. GaussDB 100 periodically stores the data of
committed transactions and data of uncommitted transactions to
disks. The data and redo logs can be used for database restoration
if a database restarts or breaks down.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 577


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands
are entered through keyboards or similar devices and are compiled
and executed by applications. The results are displayed in text or
graphic forms on the terminal interface.

coding Coding is representing data and information using code so that it


can be processed and analyzed by a computer. Characters, digits,
and other objects can be converted into digital code, or
information and data can be converted into the required electrical
pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or


more columns.

compressio Data compression, source coding, or bit-rate reduction involves


n encoding information that uses fewer bits than the original
representation. Compression can be either lossy or lossless.
Lossless compression reduces bits by identifying and eliminating
statistical redundancy. No information is lost in lossless
compression. Lossy compression reduces bits by identifying and
removing unnecessary or less important information. The process
of reducing the size of a data file is commonly referred as data
compression, although its formal name is source coding (coding
done at the source of data, before it is stored or transmitted).

concurrenc A DBMS service that ensures data integrity when multiple


y control transactions are concurrently executed in a multi-user
environment. In a multi-threaded GaussDB 100 environment,
concurrency control ensures that database operations are safe and
all database transactions remain consistent at any given time.

consistency One of the ACID features of database transactions. Consistency is


a database state. In such a state, integrity constraints on tables
are not damaged.

convergenc Downlink to uplink bandwidth ratio of a switch. A high


e ratio convergence ratio indicates a highly converged traffic environment
and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or
system dump records the state of working memory of the
program at that point in time. The states of key programs are
often dumped at the same time. For example, information about
processor registers, including program metrics, stack pointers,
memory management, other processors, and OS flags are often
dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 578


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

core file A file that is created when memory overwriting, assertion failures,
or access to invalid memory occurs in a process, causing it to fail.
This file is then used for further analysis.
A core file stores memory dump data, and supports binary mode
and specified ports. The name of a core file consists of the word
"core" and the OS process ID.
The core file is available regardless of the type of platform.

crash A crash (or system crash) is when a computer or program, such as


a software application or an operating system, stops functioning
properly. Often the program will exit after encountering this type
of error. The program experiencing the crash can hang or freeze
until a crash reporting service reports the crash and any details
relating to it. If the program is a critical part of the operating
system and crashes, the entire system may be paralyzed, often
resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes
constants, variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored
procedure information, user rights, user statistics, database
process information, database increase statistics, and database
performance statistics.

data flow An operator that exchanges data among query fragments. By their
operator input/output relationships, data flows can be categorized into
Gather flows, Broadcast flows, and Redistribution flows. Gather
combines multiple query fragments of data into one. Broadcast
forwards the data of one query fragment to multiple query
fragments. Redistribution reorganizes the data of multiple query
fragments and then redistributes the reorganized data to multiple
query fragments.

data A division of a logical database or its constituent elements into


partitionin multiple parts (partitions) whose data does not overlap based on
g ranges or lists. The target storage location is mapped based on the
range of the values in the column that is specified in the tuple.

database A collection of data that is stored together and can be accessed,


managed, and updated. Data in a view in a database can be
classified into the following types: numeral, full text, digit, and
image.

database A binary file that stores user data and the internal data of a
file database system.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 579


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

database GaussDB 100 provides a highly reliable HA solution. Every logical


HA node in GaussDB 100 is identified as a primary or standby node.
At the same time, only one GaussDB 100 node is identified as the
primary server. In GaussDB 100, standby nodes first perform full
synchronization from the primary node and later incremental
synchronization. When the HA system is running, the primary
node can receive data read and write requests in GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database
instances to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database


maintenance operations.

DBLINK An object of the path from one database to another. A remote


database object can be queried with DBLINK.

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a
database. It is a collection of programs that allows users to access,
manage, and query data in a database. A DBMS can be classified
as memory DBMS or disk DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent
device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data
during an event response, whereas a trace file contains
continuously generated diagnostic data.

durability One of the ACID features of database transactions. Transactions


that have been committed will permanently survive and not be
rolled back.

encryption A function hiding information content during data transmission to


prevent unauthorized use of the information.

environme An environment variable defines a part of the environment in


nt variable which a process runs. For example, it can define a main directory,
command search path, terminal that is in use, or the current time
zone.

error A technique that automatically detects and corrects errors in


correction software and data streams to improve system stability and
reliability.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 580


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

F–J

failover Automatic switchover from a faulty node to its standby node.


Reversely, automatic switchback from the standby node to the
primary node is called failback.

failover Automatic substitution of a functionally equivalent system


component for a failed one. The system component can be a
processor, server, network, or database.

free space A mechanism for managing free space in a table. This mechanism
manageme enables a database system to record free space in each table and
nt establish an easy-to-find data structure, accelerating operations
(such as INSERT) performed on the free space.

freeze An operation automatically performed by the AutoVacuum


Worker process when transaction IDs are exhausted. GaussDB 100
records transaction IDs in the row heading. When a transaction
reads a row, the transaction ID in the row heading and the actual
transaction ID are compared to determine whether this row is
explicit. Transaction IDs are integers containing no symbols. If
exhausted, transaction IDs are re-calculated outside of the integer
range, causing the explicit rows to become implicit. To prevent
such a problem, the freeze operation marks a transaction ID as a
special ID. Rows marked with these special transaction IDs are
explicit to all transactions.

full A data synchronization mechanism specified in the GaussDB 100


synchroniz HA solution. Used to synchronize all data from the primary server
ation to a standby server.

GNU The GNU Project was publicly announced on September 27, 1983
by Richard Stallman, aiming at building an OS composed wholly
of free software. GNU is a recursive acronym for "GNU's Not
Unix!". Stallman announced that GNU should be pronounced as
Guh-NOO. Technically, GNU is similar to Unix in design, a widely
used commercial OS. However, GNU is free software and contains
no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for
each node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration


of service interruptions caused by routine maintenance (planned)
or sudden system breakdowns (unplanned), improving system and
application usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on


behalf of all or some of the system users.

incrementa Incremental backup stores all file changes since the last valid
l backup backup.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 581


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

index An ordered data structure in a DBMS. An index accelerates data


query and update in database tables.

isolation One of the ACID features of database transactions. Isolation


means that the operations inside a transaction and data used are
isolated from other concurrent transactions. Concurrent
transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java


APIs of SQL statements. It provides unified access to multiple
relational databases, consisting of a set of classes and interfaces
written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements.
When deleting a tuple, GaussDB 100 only marks the tuples that
are to be cleared. The VACUUM thread will then periodically clear
these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

metadata Data that provides information about other data. Metadata


describes the source, size, format, or other characteristics of data.
In database columns, metadata explains the content of a data
warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that


allows a tuple to have multiple versions, on which different query
operations can be performed. One basic advantage is that read
and write operations do not conflict.

network Network backup provides a comprehensive, flexible data


backup protection solution for Microsoft Windows, UNIX, and Linux
platforms. Network backup can back up, archive, and restore files,
folders, directories, volumes, and partitions on a computer.

OS An operating system (OS) manages applications or application


programs on a computer.

P–T

page Smallest memory unit for row storage in the relational object
structure in GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature


of GaussDB 100. Data can be restored to a specified point in time
if backup data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB
server 100 HA system and works with all standby servers. At any time,
only one node in the HA system is identified as the primary server.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 582


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

process An instance of a computer program that is being executed. A


process may be made up of one or more threads. A process
cannot use a thread occupied by another process.

QPS Query Per Second (QPS) means the number of queries that a
server can respond to per second.

query Each query job can be split into one or more query fragments.
fragment Each query fragment consists of one or more query operators and
can independently run on a node. Query fragments exchange data
through data flow operators.

query An iterator or a query tree node, which is a basic unit for the
operator execution of a query. Execution of a query can be split into one or
more query operators. Common query operators include scan, join,
and aggregation.

record In a relational database, a record corresponds to data in each row


of a table.

redo log A log that contains information required for performing an


operation again in a database. If a database is faulty, redo logs
can be used to restore the database to its original state.

relational A database created using the relational model. It processes data


database using methods of set algebra.

resource A collection of resources that can be accessed to obtain


library information.

RPO Recovery point objective (RPO) refers to the latest status that a
database system and the data can be restored to after a disaster,
and it is usually represented by time.

RTO Recovery time objective (RTO) refers to the duration between the
database system failure caused by a disaster and its restoration to
proper running.

schema A database object set that includes the logical structure, such as
tables, views, sequences, stored procedures, synonyms, clusters,
and database links.

segment A segment in a database indicates a part containing one or more


extents. An extent is the smallest range of a database and consists
of data blocks. One or more segments comprise a tablespace.

session A job created by a database system for connection purposes when


an application attempts to connect to the database. Sessions are
managed by the session manager. They execute initial jobs to
perform all user operations.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 583


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

SGA System global area (SGA). It is the cache management framework


of GaussDB 100. It contains most cache management components
of the storage engine and SQL engine, including PlanCache,
DataBuffer, DcCache, RedoBuffer, CkptBuffer, LockBuffer,
TransactionBuffer, and ReplicationBuffer.

shared A shared pool is created for repeatedly executed SQL statements


pool to save memory. It contains the explain trees and execution plans
of given SQL statements.

SQL Structured Query Language (SQL) is a standard database query


language. It consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used
by Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides
three basic security services, all of which use the public key
technology. SSL ensures the security of service communication
through a network by establishing a secure connection between a
client and a server and then sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup


server of the primary server. If the primary server is behaving abnormally,
the standby server is promoted to primary, ensuring uninterrupted
data services.

statistics Information that is automatically collected by databases, including


table-level information (number of tuples and number of pages)
and column-level information (column value range distribution
histograms). Statistics in databases are used to estimate the costs
of query plans to find the plan with the lowest cost.

stop word In computing, stop words are words which are filtered out before
or after processing of natural language data (text), saving storage
space and improving search efficiency.

stored A group of SQL statements compiled into a single execution plan


procedure and stored in a large database system. Users can specify a name
and parameters (if any) for a stored procedure to execute the
procedure.

system A table storing meta information about a database. The meta


catalog information includes user tables, indexes, columns, functions, and
data types in a database.

table A set of columns and rows. Each column is referred to as a field.


Values in each field represent a data type. For example, if a table
contains three fields of person names, cities, and states, it has
three columns: Name, City, and State. In every row in the table,
the Name column contains a name, the City column contains a
city, and the State column contains a state.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 584


GaussDB 100
R&D Documentation (Standalone) 5 Glossary

Term Description

tablespace A tablespace is a logical storage structure that contains tables,


indexes, and objects. A tablespace provides an abstract layer
between physical data and logical data, and provides storage
space for all database objects. When you create an object, you can
specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and


are used for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a


database. A transaction consists of a limited database operation
sequence, and must have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information


library. A WSR is generated by comparing statistics collected by
two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively


enter queries, issue them to GaussDB 100, and view the query
results. Queries can also be entered from files. zsql supports many
meta commands and shell-like commands, allowing you to
conveniently compile scripts and automate jobs.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 585


GaussDB 100
V300R001C00

Security Hardening Guide


(Standalone)

Issue 04
Date 2019-12-28

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties, guarantees
or representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Security Hardening Guide (Standalone) Contents

Contents

1 About This Document.............................................................................................................1


2 OS Configuration..................................................................................................................... 6
2.1 Configuring System Resources............................................................................................................................................6
2.1.1 Configuring the SSH Protocol.......................................................................................................................................... 6
2.1.2 Configuring the Server to Prevent IP Spoofing Attacks..........................................................................................7
2.1.3 Removing the Remote Login Permission from the Database OS Account...................................................... 8
2.1.4 Configuring the Maximum Number of Files That Can Be Opened in Processes........................................... 8
2.2 Restricting Directory and File Permissions..................................................................................................................... 8
2.2.1 Restricting the Permission for the Home Directory................................................................................................. 9
2.2.2 Restricting the Permissions for the {GSDB_HOME}/lib and {GSDB_HOME}/add-ons Directories.......... 9
2.2.3 Restricting the Permission for the {GSDB_HOME}/bin Directory........................................................................9
2.2.4 Restricting the Permission for the data Directory.................................................................................................. 10
2.2.5 Restricting the Permission for the zengine.ini File............................................................................................... 10
2.2.6 Restricting the Permission for the SSL Certificate..................................................................................................10

3 Database Configuration.......................................................................................................12
3.1 Configuring the Database Connection.......................................................................................................................... 12
3.1.1 Disabling the Use of 0.0.0.0 and :: for Listening..................................................................................................... 12
3.1.2 Changing the Default Listening Port.......................................................................................................................... 13
3.1.3 Setting the Maximum Number of Connections...................................................................................................... 13
3.1.4 Configuring Remote Connection Control.................................................................................................................. 13
3.1.4.1 Configuring the User Whitelist.................................................................................................................................. 14
3.1.4.2 Configuring the IP Address Whitelist and Blacklist............................................................................................ 15
3.1.4.2.1 Enabling IP Address Whitelist/Blacklist Checking............................................................................................15
3.1.4.2.2 Configuring the IP Address Whitelist................................................................................................................... 16
3.1.4.2.3 Configuring the IP Address Blacklist.................................................................................................................... 16
3.1.5 Configuring the SSL Private Key................................................................................................................................... 17
3.1.6 Configuring the Aging Time of Non-Authentication Sessions...........................................................................18
3.1.7 Disabling Local Trust Authentication..........................................................................................................................18
3.1.8 Establishing TCP/IP Connections in SSL Mode........................................................................................................ 19
3.2 Managing Users, Roles, and Permissions..................................................................................................................... 33
3.2.1 Checking for Unknown Users........................................................................................................................................ 33
3.2.2 Checking the DBA Role....................................................................................................................................................33

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Security Hardening Guide (Standalone) Contents

3.2.3 Checking the CREATE USER Permission.................................................................................................................... 34


3.2.4 Checking the ALTER USER Permission........................................................................................................................35
3.2.5 Checking the DROP USER Permission........................................................................................................................ 35
3.2.6 Checking the CREATE DATABASE Permission.......................................................................................................... 36
3.2.7 Removing the WITH GRANT OPTION Permission Attribute.............................................................................. 37
3.2.8 Removing the GRANT ANY PRIVILEGE Permission................................................................................................ 37
3.2.9 Removing the GRANT ANY ROLE Permission..........................................................................................................38
3.2.10 Removing the GRANT ANY OBJECT PRIVILEGE Permission............................................................................. 39
3.2.11 Removing All Object Permissions from User PUBLIC......................................................................................... 40
3.3 Configuring User Security Policies.................................................................................................................................. 45
3.3.1 Configuring the Number Of Days Before Which a Password Cannot Be Reused....................................... 45
3.3.2 Configuring the Number Of Password Changes Required Before the Current Password Can Be
Reused.............................................................................................................................................................................................. 46
3.3.3 Configuring the Number of Failed Login Attempts...............................................................................................47
3.3.4 Configuring the Account Lock Time........................................................................................................................... 47
3.3.5 Changing the Password of the Initial User............................................................................................................... 48
3.3.6 Configuring the Password Lifetime............................................................................................................................. 48
3.3.7 Configuring the Password Grace Period.................................................................................................................... 49
3.3.8 Configuring the Maximum Number of Connections of a Single User............................................................ 49
3.4 Configuring Database Audit..............................................................................................................................................50
3.4.1 Enabling Database Audit................................................................................................................................................ 50
3.4.2 Enabling DDL Audit.......................................................................................................................................................... 50
3.4.3 Enabling DCL Audit........................................................................................................................................................... 51
3.4.4 Enabling DML Audit......................................................................................................................................................... 51
3.4.5 Enabling PL Audit.............................................................................................................................................................. 51
3.4.6 Enabling DDL and DCL Audit........................................................................................................................................ 52
3.4.7 Enabling DDL and DML Audit....................................................................................................................................... 52
3.4.8 Enabling DCL and DML Audit....................................................................................................................................... 53
3.4.9 Enabling Audit for All Operations................................................................................................................................53
3.4.10 Configuring the Audit File Path................................................................................................................................. 53
3.4.11 Configuring the Maximum Capacity of an Audit Log File................................................................................ 54
3.4.12 Configuring the Maximum Number of Backup Audit Files.............................................................................. 55
3.5 Configuring Error Reports and Logs............................................................................................................................... 55
3.5.1 Configuring the Log Path............................................................................................................................................... 55
3.5.2 Configuring the Log File Permission........................................................................................................................... 56
3.5.3 Configuring the Log Directory Permission................................................................................................................ 56
3.5.4 Configuring Server Logging Levels.............................................................................................................................. 57

4 Interface Mapping (GaussDB 100 Native Interface Names vs. Mainstream


Database Interface Names)................................................................................................... 59
4.1 Data Dictionary Tables........................................................................................................................................................ 59
4.2 DBA Views............................................................................................................................................................................... 61
4.3 User Views............................................................................................................................................................................... 64

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Security Hardening Guide (Standalone) Contents

4.4 Dynamic Performance Views............................................................................................................................................ 66


4.5 Configuration Parameters.................................................................................................................................................. 69

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
Security Hardening Guide (Standalone) 1 About This Document

1 About This Document

Overview
GaussDB 100 is a high-performance and high-reliability distributed relational
database developed by Huawei Technologies Co., Ltd. It supports automatic
horizontal sharding and breaks the storage and performance bottlenecks of a
single server, applying to massive data storage and processing.
The framework of GaussDB 100 is component-based and can be used for a
standalone database or a cluster. To enhance the security of GaussDB 100, a series
of security rules are formulated based on Huawei security requirements. This
document describes how to perform security hardening on GaussDB 100 and Linux
where the database is running. Security hardening is performed after GaussDB 100
is installed.
GaussDB 100 is compatible with the user habits of mainstream databases. You can
use native GaussDB 100 interface names or their corresponding names in the
mainstream databases. For details, see Interface Mapping (GaussDB 100 Native
Interface Names vs. Mainstream Database Interface Names). The interfaces
mentioned in this document use their native GaussDB 100 names.

Applicable Scope
This document is applicable to all Huawei products that use GaussDB 100.

Intended Audience
This document is intended for all GaussDB 100 users.

Item Description
For details about items in security configuration rules, see Table 1-1.

Table 1-1 Items in security configuration rules

Item Name Description

Configuration Description of configuration items, their purposes, and basis


description

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Security Hardening Guide (Standalone) 1 About This Document

Item Name Description

Configuration Configuration procedure


method

Recommended Expected value that meets the security requirements


value

Check method Method for checking the current configuration

Expected result Value returned by the system

Risk level Level of a risk brought by a check item: high, medium, and
low

Reference Reference of the configuration items

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not


avoided, will result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in equipment damage, data loss,
performance deterioration, or unanticipated results.
NOTICE is used to address practices not related to personal
injury.

Calls attention to important information, best practices, and


tips.
NOTE is used to address information not related to personal
injury, equipment damage, and environment deterioration.

Example Conventions
The following table describes some example information in this document. You
can replace the example information as needed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Security Hardening Guide (Standalone) 1 About This Document

Information Description

$GSDB_HOME Environment variable of the GaussDB 100 installation


directory that is automatically written when install.py is
used for installation. Assume that /opt/gaussdb/app is set
as the installation directory.

$GSDB_DATA Environment variable of the GaussDB 100 data directory


that is automatically written when install.py is used for
installation. Assume that /opt/gaussdb/data is set as the
data directory.

gaussdba GaussDB 100 administrator manually created after the


installation

database_123 Password of the database administrator gaussdba

192.168.0.1 IP address of the GaussDB 100 server

1888 Port number used by GaussDB 100 to listen to client


connection requests

Parameters of GaussDB 100 tools are parsed in sequence. If a parameter is


specified for multiple times, the last value takes effect.

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are


in italics.

[] Items (keywords and parameters) in brackets [ ] are


optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more


options or no item is selected.

{ x | y | ... } Indicates that one item is selected from two or more


options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with commas (,).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Security Hardening Guide (Standalone) 1 About This Document

Format Description

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
commas (,).

Change History
Version Change Description Date

04 This issue is the fourth official release. 2019-07-18

03 Rectified known defects. 2019-06-26

02 Added the following section: 2019-04-05


● Configuring the Maximum Number
of Files That Can Be Opened in
Processes
● Configuring the Number Of
Password Changes Required Before
the Current Password Can Be
Reused
● Configuring the Password Grace
Period
● Disabling Local Trust Authentication
● Added Table 3-5 to Removing All
Object Permissions from User
PUBLIC.
● Configuring the Maximum Number
of Connections of a Single User
● Restricting the Permission for the
SSL Certificate
● Configuring the SSH Protocol
● Enabling PL Audit
Modified the following sections:
● Establishing TCP/IP Connections in
SSL Mode
● Configuring the Audit File Path
● Configuring the Log Path
● Configuring Remote Connection
Control
● Enabling Audit for All Operations

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Security Hardening Guide (Standalone) 1 About This Document

Version Change Description Date

01 This issue is the first official release. 2018-10-30

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

2 OS Configuration

You can perform security hardening on the OS where GaussDB 100 is running.

Parameter Description
Parameters used for GaussDB 100 OS configuration are described in Table 2-1. Set
these parameters as needed.

Table 2-1 Parameter description


Parameter Description

GSDB_HOME Installation directory of GaussDB 100

GSDB_DATA Data directory of GaussDB 100

GSDB_USER User who installs GaussDB 100

GSDB_GROUP Group of the user who installs GaussDB 100

2.1 Configuring System Resources


Operations in this section can be performed only by user root.

2.1.1 Configuring the SSH Protocol


Configuration description
Secure Shell (SSH) is a security protocol on the application layer and transport
layer. It is used for secure remote login and other secure network services over an
insecure network. To ensure that SSH can prevent information disclosure during
remote management, set Protocol in the /etc/ssh/sshd_config file to a value
meeting the security requirements of the local environment.
Configuration method
vim /etc/ssh/sshd_config

Recommended value: 2

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

Check method
grep -P '^[^#]*Protocol\s*' /etc/ssh/sshd_config

Expected result: Protocol 2

Risk level: medium

2.1.2 Configuring the Server to Prevent IP Spoofing Attacks


Configuration description

Setting rp_filter to 1 enables the server's reverse path filtering mechanism. In this
way, the server checks whether the reverse path of each incoming data packet is
the optimal one. If it is not, the packet is discarded to prevent the server from IP
spoofing attacks.

Configuration method

Step 1 Run the sysctl -a command as user root to check the rp_filter values of all
interfaces on the server.
sysctl -a | grep rp_filter | grep -v arp_filter
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.lo.rp_filter = 1
net.ipv4.conf.eth0.rp_filter = 1
net.ipv4.conf.eth1.rp_filter = 1

Step 2 Open the /etc/sysctl.conf file, change the value of rp_filter from 0 to 1 for all
interfaces, and save the file.
vi /etc/sysctl.conf
net.ipv4.conf.all.rp_filter = 1

Step 3 Run the sysctl -p command to load the configuration file.


sysctl -p

----End

NOTICE

After the reverse path filtering mechanism is enabled, packet loss may occur on
NICs. In this case, check the system route settings.

Recommended value: 1

Check method

Run the sysctl -a command as user root to check the rp_filter values of all
interfaces on the server.
sysctl -a | grep rp_filter | grep -v arp_filter

Expected result: 1

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

2.1.3 Removing the Remote Login Permission from the


Database OS Account
Configuration description

The database OS account has the permission to access all database files. Once the
password of this account is disclosed, the database is seriously threatened.
Therefore, removing the remote login permission from this account improves
database security.

Configuration method

Change the shell of the database OS account (for example, gaussdba) to /sbin/
nologin.
usermod gaussdba -s /sbin/nologin

Recommended value: /sbin/nologin

Check method
grep -P '^gaussdba:.*?:/sbin/nologin$' /etc/passwd

Expected result: not empty

Risk level: medium

2.1.4 Configuring the Maximum Number of Files That Can Be


Opened in Processes
Configuration description

If the maximum number of files that can be opened in processes is too small, SQL
operations will fail once the maximum number is exceeded.

Configuration method

Run the following command as user root to change the maximum number of files
that can be opened in processes. The configuration takes effect upon the next
login to the OS.
echo "* soft nofile 1000000" >> /etc/security/limits.conf
echo "* hard nofile 1000000" >> /etc/security/limits.conf

Recommended value: 1000000

Check method
ulimit -a|grep "open files"

Expected result:
open files (-n) 1000000

Risk level: medium

2.2 Restricting Directory and File Permissions


Operations in this section can be performed only by a database installation user.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

2.2.1 Restricting the Permission for the Home Directory


Configuration description
The home directory is a database installation directory specified by the
environment variable {GSDB_HOME}.
Configuration method
chmod 0700 ${GSDB_HOME}

Recommended value: 0700


Check method
find ${GSDB_HOME} -prune -perm /g=rwx,o=rwx

Expected result: empty


Risk level: medium

2.2.2 Restricting the Permissions for the {GSDB_HOME}/lib


and {GSDB_HOME}/add-ons Directories
Configuration description
The {GSDB_HOME}/lib and {GSDB_HOME}/add-ons directories store GaussDB
100 shared components.
Configuration method
chmod 0700 ${GSDB_HOME}/lib
chmod 0700 ${GSDB_HOME}/add-ons

Recommended value: 0700


Check method
find ${GSDB_HOME}/lib -prune -perm /g=rwx,o=rwx
find ${GSDB_HOME}/add-ons -prune -perm /g=rwx,o=rwx

Expected result: empty


Risk level: medium

2.2.3 Restricting the Permission for the {GSDB_HOME}/bin


Directory
Configuration description
The {GSDB_HOME}/bin directory stores binary files of the database.
Configuration method
chmod 0700 ${GSDB_HOME}/bin

Recommended value: 0700


Check method
find ${GSDB_HOME}/bin -prune -perm /g=rwx,o=rwx

Expected result: empty

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

Risk level: medium

2.2.4 Restricting the Permission for the data Directory


Configuration description
The data directory stores user data files.
Configuration method
chmod 0700 ${GSDB_DATA}/data

Recommended value: 0700


Check method
export GSDB_USER=install_user
export GSDB_GROUP=install_group
find ${GSDB_DATA}/data -prune \( ! -user ${GSDB_USER} -o ! -group ${GSDB_GROUP} -o -perm /
g=rwx,o=rwx \)

Expected result: empty


Risk level: medium

2.2.5 Restricting the Permission for the zengine.ini File


Configuration description
The zengine.ini file stores database connection configuration.
Configuration method
chmod 0600 ${GSDB_DATA}/cfg/zengine.ini

Recommended value: 0600


Check method
export GSDB_USER=install_user
export GSDB_GROUP=install_group
find ${GSDB_DATA}/cfg/zengine.ini -prune \( ! -user ${GSDB_USER} -o ! -group ${GSDB_GROUP} -o -
perm /u=x,g=rwx,o=rwx \)

Expected result: empty


Risk level: medium

2.2.6 Restricting the Permission for the SSL Certificate


Configuration description
If SSL is used, you need to configure the SSL certificate on the database server and
set the certificate permission. You are advised to set the permission for the private
key file to owner-readable-only.
Recommended value: 0400
Check method
export GSDB_USER=install_user
export GSDB_GROUP=install_group
find ${GSDB_HOME}/cacert.pem -prune \( ! -user ${GSDB_USER} -o ! -group ${GSDB_GROUP} -o -
perm /u=wx,g=rwx,o=rwx \)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Security Hardening Guide (Standalone) 2 OS Configuration

Expected result: empty


Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3 Database Configuration

You can perform security hardening on GaussDB 100. Do not run the database as
user root.

If the database is deployed in HA mode, perform security hardening on both the primary
and standby nodes.

3.1 Configuring the Database Connection


To protect information security of the database, configure the database
connection to prevent unauthorized clients from accessing the database. You are
not allowed to remotely connect to the database as user SYS.

3.1.1 Disabling the Use of 0.0.0.0 and :: for Listening


Configuration description

0.0.0.0 indicates that all available IPv4 addresses on the local host are listened,
and :: indicates that all available IPv6 addresses on the local host are listened.

Configuration method

Change the value of LSNR_ADDR in the zengine.ini configuration file to a local IP


address and restart the database for the change to take effect. The path of the
zengine.ini file is {GSDB_DATA}/cfg/zengine.ini.

Recommended value: a local IP address

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_ADDR' AND VALUE IN ('0.0.0.0', '::');

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------
0 rows fetched.

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3.1.2 Changing the Default Listening Port


Configuration description
Change the listening port from the default 1611 to another value, protecting the
database from malicious clients.
Configuration method
Change the value of LSNR_PORT in the zengine.ini configuration file and restart
the database for the change to take effect. The path of the zengine.ini file is
{GSDB_DATA}/cfg/zengine.ini.
Recommended value: a value other than 1611
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_PORT' AND VALUE = '1611';

Expected result:
NAME VALUE
---------------------------------------------------------------- ----------------
0 rows fetched.

Risk level: medium

3.1.3 Setting the Maximum Number of Connections


Configuration description
If the maximum number of online connections is set to a large value, the required
process socket handles and session pool memory may exceed the OS limit on the
server. You are advised to set the maximum number of concurrent connections to
200.
Configuration method
Change the value of SESSIONS in the zengine.ini configuration file and restart
the database for the change to take effect. The path of the zengine.ini file is
{GSDB_DATA}/cfg/zengine.ini.
Recommended value: 69–8192
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'SESSIONS';

Expected result:
NAME VALUE
---------------------------------------------------------------- --------------------------------------------
SESSIONS 200

Risk level: medium

3.1.4 Configuring Remote Connection Control


You can configure client access authentication to allow remote host access. You
can configure a user whitelist, IP address whitelist, or IP address blacklist to
control remote connections to GaussDB 100. By default, only local access is
allowed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

● User whitelist: You can add users to zhba.conf so that these users access the
database only through the IP addresses specified in zhba.conf.
● IP address whitelist: Only the IP addresses specified by TCP_INVITED_NODES
can be used to access the database.
● IP address blacklist: The IP addresses specified by TCP_EXCLUDED_NODES
cannot be used to access the database.
The IP address blacklist has the highest priority. If an IP address is configured in all
the three lists, it cannot be used for remote access.
When the user whitelist, IP address whitelist, and IP address blacklist are all
enabled:
● Users in the user whitelist can use the IP addresses in the user whitelist and IP
address whitelist to remotely connect to databases (the IP addresses must not
be in the IP address blacklist).
● If the IP address of a client is in the user whitelist (zhba.conf) or IP address
whitelist and not in the IP address blacklist, it will pass the verification for
login regardless of whether the user is in the user whitelist.

If user SYS locally logs in to a database in password-free mode, the login will not be limited
by the user whitelist, IP address whitelist, or IP address blacklist.
If user SYS logs in to a database using an encrypted password, the login will be limited by
the IP address blacklist.

3.1.4.1 Configuring the User Whitelist


Configuration description
To prevent account disclosure, you can configure a whitelist to specify users with
high-level permissions and client IP addresses allowed for database connections.

● During authentication, the system checks connection requests with records in the
zhba.conf file in sequence, so the record sequence is very important. You are advised to
configure the record with a weak connection mode (host) and strict connection
parameters ahead of the record with a strict connection mode (hostssl) and weak
connection parameters. For example, it is usually expected that the TCP/IP connection
on the local or trusted network is set up in host mode and the connection on the
remote or untrusted network is set up in hostssl mode. In this case, the record with the
host connection mode and the IP address 127.0.0.1 or the IP address of a trusted
network needs to be configured ahead of the record with the hostssl connection mode
and an IP address covering clients within a wider range.
● To log in to the database, add the whitelist to both the primary and standby DNs after a
primary/standby switchover. For details, see Configuring the IP Address Whitelist.

Configuration method

Step 1 Add an HBA entry (TYPE, USER, and ADDRESS) to the zhba.conf file. The save
path of zhba.conf is $GSDB_DATA/cfg/zhba.conf. host indicates a TCP or SSL
connection, and hostssl indicates an SSL connection. If SSL is enabled on the
server but is not configured on the client, the server rejects the SSL connection.
host user 127.0.0.1,192.168.3.222,20AB::9217:acff:feab:fcd0/64
hostssl user 192.168.2.223

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Step 2 Run the following statement to load the user whitelist. The whitelist takes effect
immediately after the statement is executed.
ALTER SYSTEM RELOAD HBA CONFIG;

----End
Recommended value: not empty
Check method
SELECT * FROM DV_HBA;

Expected result:
SQL> SELECT * FROM DV_HBA;
TYPE USER_NAME
ADDRESS
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
host USER
127.0.0.1/32,192.168.3.222/32,20ab::9217:acff:feab:fcd0/64
hostssl USER
192.168.2.223/32,20ab::9217:acff:feab:fcd0/64

2 rows fetched.

Risk level: medium

3.1.4.2 Configuring the IP Address Whitelist and Blacklist

3.1.4.2.1 Enabling IP Address Whitelist/Blacklist Checking


Configuration description
After IP address whitelist/blacklist checking is enabled, the server can control
client access based on a whitelist or blacklist.

NOTICE

Before enabling IP address whitelist/blacklist checking, ensure that at least one of


TCP_INVITED_NODES and TCP_EXCLUDED_NODES is set. Otherwise, the
following error message "GS-00254: For invited and excluded nodes is both empty,
ip whitelist function can't be enabled" is displayed.

Configuration method
Run the ALTER SYSTEM statement to enable IP address whitelist/blacklist
checking. The configuration takes effect immediately after the statement is
executed.
ALTER SYSTEM SET TCP_VALID_NODE_CHECKING = TRUE;

Recommended value: TRUE


Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_VALID_NODE_CHECKING';

Expected result:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

NAME VALUE
---------------------------------------------------------------- --------------------
TCP_VALID_NODE_CHECKING TRUE

Risk level: medium

3.1.4.2.2 Configuring the IP Address Whitelist


Configuration description
The IP address whitelist is configured by setting the TCP_INVITED_NODES
parameter. After IP address whitelist/blacklist checking is enabled and the IP
address whitelist is configured, only whitelisted clients can access the database.
Such a whitelist allows for IPv4 and IPv6 addresses, as well as a specified subnet
mask or prefix length, which indicates a network segment. Multiple addresses or
network segments can be separated by commas (,).

The value of TCP_INVITED_NODES cannot exceed 1024 bytes. Otherwise, an error will be
reported.

Configuration method
Run the ALTER SYSTEM statement to configure an IP address whitelist. The
configuration takes effect immediately after the statement is executed.
-- Add 127.0.0.1, 192.168.3.222, and 20ab::9217:acff:feab:fcd0 to the IP address whitelist.
ALTER SYSTEM SET TCP_INVITED_NODES = '(127.0.0.1/32,192.168.3.222/32,20ab::9217:acff:feab:fcd0/64)';
-- Add the 192.168.3.0/24 network segment to the IP address whitelist.
ALTER SYSTEM SET TCP_INVITED_NODES = '(192.168.3.0/24)';

Recommended value: not empty


Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_INVITED_NODES';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------
TCP_INVITED_NODES (127.0.0.1/32,192.168.3.222/32,20ab::9217:acff:feab:fcd0/64)

Risk level: medium

3.1.4.2.3 Configuring the IP Address Blacklist


Configuration description
The IP address blacklist is configured by setting the TCP_EXCLUDED_NODES
parameter. After IP address whitelist/blacklist checking is enabled and the IP
address blacklist is configured, the blacklisted clients cannot access the database.
Such a blacklist allows for IPv4 and IPv6 addresses, as well as a specified subnet
mask or prefix length, which indicates a network segment. Multiple addresses or
network segments can be separated by commas (,).

The value of TCP_INVITED_NODES cannot exceed 1024 bytes. Otherwise, an error will be
reported.

Configuration method

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Run the ALTER SYSTEM statement to configure an IP address blacklist. The


configuration takes effect immediately after the statement is executed.
-- Add 192.168.3.222 and 20ab::9217:acff:feab:fcd0 to the IP address blacklist.
ALTER SYSTEM SET TCP_EXCLUDED_NODES = '(192.168.3.222/32,20ab::9217:acff:feab:fcd0/64)';
-- Add the 192.168.3.0/24 network segment to the IP address blacklist.
ALTER SYSTEM SET TCP_EXCLUDED_NODES = '(192.168.3.0/24)';

Recommended value: not empty


Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_EXCLUDED_NODES';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------
TCP_EXCLUDED_NODES (192.168.3.222/32,20ab::9217:acff:feab:fcd0/64)

Risk level: low

3.1.5 Configuring the SSL Private Key


Configuration description
The database parameters _FACTOR_KEY and LOCAL_KEY must be updated in
time to ensure the security of SSL private key encryption.

The _FACTOR_KEY parameter can be modified only by running the ALTER SYSTEM SET
_FACTOR_KEY command. If you modify it in the zengine.ini file, the database will fail to be
started.

Recommended value: none


Configuration method
Log in to the server as the database installation user and use the zencrypt tool to
generate a key. Key indicates the factor key (_FACTOR_KEY), and WorkKey
indicates the work key (LOCAL_KEY).
zencrypt -g
Key: jQ4IAgxiJR1ezCPrvtZLUQ==
WorkKey: 8Vw4Gm2Ktu7B8XIzTlVRK9EOH
+lpSNbIlhfVbaJ0RDdbgyUyHsYT6UxYGSEbZg7BXki6gSP8slEU8haWxiUgNg==

Run the ALTER SYSTEM statement to configure the local login key and restart the
database for the configuration to take effect.
ALTER SYSTEM SET _FACTOR_KEY = 'jQ4IAgxiJR1ezCPrvtZLUQ==';
ALTER SYSTEM SET LOCAL_KEY = '8Vw4Gm2Ktu7B8XIzTlVRK9EOH
+lpSNbIlhfVbaJ0RDdbgyUyHsYT6UxYGSEbZg7BXki6gSP8slEU8haWxiUgNg==';

Check method
Run the following statement to check whether the values of _FACTOR_KEY and
LOCAL_KEY are different from the default values configured in the database:
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE (NAME = '_FACTOR_KEY' AND VALUE =
'dc4hoQWGQs7/Uv3AiherFw==') or (NAME = 'LOCAL_KEY' AND VALUE =
'UTiYlBoTC71MvTyBvWhVDodc0VAop1GMe135ZCov8Pv4xsnlEHn9Bs/pjRo7ZNM1BXq8Z4XuyRjfaNpY/
7McEQ==');

Expected result:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

NAME VALUE
---------------------------------------------------------------- ----------------
0 rows fetched.

Risk level: high

3.1.6 Configuring the Aging Time of Non-Authentication


Sessions
To prevent DOS attacks from malicious clients that occupy server resources. Set
the UNAUTH_SESSION_EXPIRE_TIME parameter to forcibly disconnect from the
server if no authentication is performed at the specified time after the TCP
connection is established.

Configuration method
You can configure the aging time in either of the following ways:
● Set the UNAUTH_SESSION_EXPIRE_TIME parameter in the zengine.ini
configuration file and restart the database for the setting to take effect. The
path of the zengine.ini file is {GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM statement to set UNAUTH_SESSION_EXPIRE_TIME.
ALTER SYSTEM SET UNAUTH_SESSION_EXPIRE_TIME = 60 SCOPE = BOTH;

Recommended value: 60
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'UNAUTH_SESSION_EXPIRE_TIME';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------
UNAUTH_SESSION_EXPIRE_TIME 60

Risk level: low

3.1.7 Disabling Local Trust Authentication


In local trust authentication mode, a database user can connect to the local
database in password-free mode using zsql after the local connection is
authenticated. Then, this user can maintain database accounts. You are advised to
disable the local trust authentication during service running.

Configuration method
You can disable local trust authentication in either of the following ways:
● Run the python zctl.py -t kill command to stop the database, change the
value of ENABLE_SYSDBA_LOGIN to FALSE in the zengine.ini configuration
file, and finally run the python zctl.py -t start command to start the
database. The path of the zengine.ini file is {GSDB_DATA}/cfg/zengine.ini.
● When the database is running, run the ALTER SYSTEM statement to set
ENABLE_SYSDBA_LOGIN to FALSE, and then run the python zctl.py -t kill
&& python zctl.py -t start command to restart the database for the
modification to take effect.
ALTER SYSTEM SET ENABLE_SYSDBA_LOGIN = FALSE;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Recommended value: FALSE


Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'ENABLE_SYSDBA_LOGIN';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------
ENABLE_SYSDBA_LOGIN FALSE

Risk level: medium

3.1.8 Establishing TCP/IP Connections in SSL Mode


Scenario
To ensure transmission security of sensitive data on the Internet, you can use SSL
to encrypt the communication between GaussDB 100 servers and clients.

Prerequisites
The formal certificates and keys for the server and client have been obtained from
the Certificate Authority (CA). Currently, only SSL certificates in PEM format are
supported. Assume the private key and certificate for the server are server.key and
server.crt, the private key and certificate for the client are client.key and
client.crt, and the CA root certificate is cacert.pem.

Related Concepts
GaussDB 100 supports the SSL protocol. As a highly secure protocol, SSL
authenticates bidirectional identification between the server and client using
digital signatures and digital certificates to enhance data transmission security.
GaussDB 100 supports the TLSv1.2 protocol. As a highly secure protocol, TLSv1.2
authenticates bidirectional identification between the server and client using
digital signatures and digital certificates to enhance data transmission security.

Precautions
In HA mode, enable the SSL function on both primary and standby nodes to
ensure the security of bidirectional data transmission.

Procedure
Assume that the path is /home/gaussdba/app. Replace it with the actual path.

Step 1 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.
Step 2 Set digital certificate parameters related to SSL authentication. For details, see
Table 3-1.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

● Set server parameters. The parameter settings take effect after the database
is restarted.
alter system set SSL_CA = '/home/gaussdba/app/cacert.pem';
alter system set SSL_CERT = '/home/gaussdba/app/server.crt';
alter system set SSL_KEY = '/home/gaussdba/app/server.key';
alter system set SSL_VERIFY_PEER = TRUE;

● Set client parameters.


export ZSQL_SSL_CERT="/home/gaussdba/app/client.crt"
export ZSQL_SSL_KEY="/home/gaussdba/app/client.key"
export ZSQL_SSL_CA="/home/gaussdba/app/cacert.pem"
export ZSQL_SSL_MODE="preferred"

NOTICE

You are advised to use bidirectional authentication for higher security.


When you set environment variables, use absolute paths of files.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Table 3-1 Authentication modes


Authen Description Setting Server Setting Maintenanc
ticatio Parameters Client e
n Environm Suggestion
Mode ent
Variables

Bidirect The client Copy the certificate, Set the This


ional verifies the private key, revoked following authenticati
authent server's certificate, and root environme on mode is
ication certificate certificate of the server to nt applicable
(recom and the the /home/gaussdba/app variables: to scenarios
mende server directory and set the ● ZSQL_S that require
d) verifies the following parameters: SL_CER high data
client's ● SSL_CA T security. In
certificate. this mode,
Connection ● SSL_CERT ● ZSQL_S you are
can be ● SSL_KEY SL_KEY advised to
established ● (Optional) SSL_CRL ● ZSQL_S set
after the SL_CA ZSQL_SSL_
bidirectional ● (Optional) MODE to
SSL_KEY_PASSWORD ● (Optio
verification nal) VERIFY_CA
is successful. ● SSL_VERIFY_PEER = ZSQL_S or
TRUE SL_CRL VERIFY_FUL
L, and set
● ZSQL_S the
SL_MO authenticati
DE on mode of
● (Optio the server to
nal) SSL_VERIFY
ZSQL_S _PEER=TRU
SL_KEY E. With the
_PASS settings,
WD only
authorized
clients and
servers can
use the
GaussDB
100 server
to transmit
data,
thereby
ensuring
high data
security. If
SSL_VERIFY
_PEER=FALS
E is set, SSL
connection
can be
established

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Authen Description Setting Server Setting Maintenanc


ticatio Parameters Client e
n Environm Suggestion
Mode ent
Variables

without
requiring
the client to
provide a
certificate,
which is not
recommend
ed.
Set
ZSQL_SSL_K
EY_PASSWD
to the actual
ciphertext. If
you do not
set this
parameter,
the system
prompts you
to enter the
private key
ciphertext
when you
set up a
connection
in
interactive
mode on
the client.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Authen Description Setting Server Setting Maintenanc


ticatio Parameters Client e
n Environm Suggestion
Mode ent
Variables

Unidire The client Copy the certificate and Set the To prevent
ctional verifies the private key of the server to following TCP-based
Authen server's the /home/gaussdba/app environme link
tication certificate, directory and set the nt spoofing,
whereas the following parameters: variables: you are
server does ● SSL_CERT ● ZSQL_S advised to
not verify SL_CA use the SSL
the client's ● SSL_KEY certificate
certificate. ● (Optio authenticati
The server nal) on. Besides
loads the ZSQL_S configuring
certificate SL_CRL the
information ● ZSQL_S certificate
and sends SL_MO and private
the DE key of the
information server, you
to the client. are advised
The client to set
verifies the variable
server's ZSQL_SSL_
certificate MODE to
according to VERIFY_CA
the root or
certificate. VERIFY_FUL
L.

Step 3 Log in to the server where GaussDB 100 is located as user root to change the
permissions of server and client keys.
Copy server.crt, server.key, and cacert.pem to the /home/gaussdba/app
directory. Ensure that the permission is 600, the owner is the database installation
user (for example, gaussdba), and the owner group is the group to which the
database installation user belongs (for example, dbgrp). Run the following
commands to modify the permissions:
cd /home/gaussdba/app
chown gaussdba:dbgrp server.crt server.key cacert.pem
chmod 600 server.crt server.key cacert.pem

Step 4 Switch to the database installation user, for example, gaussdba.


su - gaussdba

Step 5 If an encrypted private key has been configured, use the zencrypt tool to generate
the password ciphertext (SSL_KEY_PASSWORD).
1. Run the following command to generate the password ciphertext
(SSL_KEY_PASSWORD):
zencrypt -e aes256 -f jQ4IAgxiJR1ezCPrvtZLUQ== -k
8Vw4Gm2Ktu7B8XIzTlVRK9EOH
+lpSNbIlhfVbaJ0RDdbgyUyHsYT6UxYGSEbZg7BXki6gSP8slEU8haWxiUgNg==

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

-- Enter the plaintext password of the private key (for example, Aa123456) to generate password
ciphertext:
Please enter password to encrypt:
********
Please input password again:
********
Cipher: PLFJgfZwLSOJFRp6o7qsj604fFwPEu2MLxH7m/F/aMg=

– -e indicates that the generated private key is encrypted using the AES algorithm
(256-bit key). -f indicates the value of _FACTOR_KEY, and -k indicates the value of
LOCAL_KEY. For values of -f and -K, see Configuring the SSL Private Key.
– The private key is sensitive data. It is strongly recommended that users use
encrypted private keys and periodically use Zenith to update the encrypted keys,
which ensures data security.
– The requirements for ciphertext complexity are consistent with the database
password requirements.
– It is recommended that the private key ciphertext be a string containing no less
than 2048 characters.
2. When the database instance is running, update the SSL private key ciphertext
(for example: Aa123456), or update the configuration item in the
configuration file.
alter system set SSL_KEY_PASSWORD = 'PLFJgfZwLSOJFRp6o7qsj604fFwPEu2MLxH7m/F/aMg=';

Step 6 Restart the GaussDB 100 server to make the configuration take effect.
-- Stop the database service.
python $GSDB_HOME/bin/zctl.py -t stop
-- Start the database service.
python $GSDB_HOME/bin/zctl.py -t start

----End

Enabling and Disabling SSL


● Enable SSL.
Configure SSL parameters on the server by referring to the procedure above.
Restarting the database will verify the relevant parameters and certificate validity.
After the verification succeeds, SSL will be enabled automatically.
To check whether SSL has been enabled, run the zsql tool as user gaussdba to
connect to the server, and execute the show parameter HAVE_SSL command to
query for the SSL status. If the value of HAVE_SSL is TRUE, SSL has been enabled.
Otherwise, examine the server run log file to locate the reason for the SSL
enablement failure.
SQL> SHOW PARAMETER HAVE_SSL

NAME DATATYPE
VALUE
---------------------------------------------------------------- --------------------
----------------------------------------------------------------
HAVE_SSL GS_TYPE_BOOLEAN
TRUE

● Disable SSL.
Method 1: When the database instance is running, change the values of
parameters SSL_CA, SSL_CERT, SSL_KEY, and SSL_KEY_PASSWORD to null, and
then restart the database. This can disable SSL on servers.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

alter system set SSL_CA = '';


alter system set SSL_CERT = '';
alter system set SSL_KEY = '';
alter system set SSL_KEY_PASSWORD = '';

Method 2: Delete SSL parameters from the configuration file, or delete the SSL
certificate from the disk. Then, restart the database.

Reference
Set parameters related to SSL authentication in the zengine.ini file on the
GaussDB 100 server. For details, see Table 3-2.

Table 3-2 Server parameters


Parameter Description Value Range

SSL_VERIFY Whether to allow an SSL ● TRUE: The client must


_PEER connection to be established provide a valid certificate
without requiring the client to to establish an SSL
provide a certificate. This connection.
parameter is used together with ● FALSE: An SSL connection
SSL_CA. If SSL_CA is set, a client can be established
certificate is required. If the client without requiring the
does not provide the certificate, client to provide a
the SSL_VERIFY_PEER parameter certificate.
determines whether to reject the
connection. Default value: FALSE

SSL_CERT Server certificate file, including Refer to the actual certificate


the server public key. The name. You are advised to set
certificate proves the legal this parameter to the
identity of the server and the absolute path of the server
public key is sent to the peer end certificate file. Otherwise, the
for data encryption. certificate may fail to be
loaded.
Default value: empty,
indicating no server
certificate file is available.

SSL_KEY Server private key file used to Refer to the name of the
decrypt digital signatures and actual private key. You are
data encrypted using the public advised to set this parameter
key. to the absolute path of the
server private key file.
Otherwise, the private key
may fail to be loaded.
Default value: empty,
indicating no server private
key is available.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Parameter Description Value Range

SSL_CA Root certificate of the CA server. Refer to the name of the


This parameter is optional and actual root certificate of the
needs to be set only when the CA server. Set this parameter
certificate of a client must be to the absolute path of the
verified. CA certificate. Otherwise, the
CA certificate may fail to be
loaded.
Default value: empty,
indicating that the identities
of clients are not verified.
Note: The CA certificate must
be an X.509V3 digital
certificate, the Basic
Constraints extension must
be CA, and the Key Usage
extension must contain a
certificate signature. If the CA
certificate is also used for
certificate revocation, the
Key Usage extension must
contain a signature to be
revoked.

SSL_CRL Certificate revocation list (CRL). If Refer to the actual name of


the certificate of a client is in the the CRL. You are advised to
list, the certificate is invalid. set this parameter to the
absolute path of the CRL.
Otherwise, the certificates
may fail to be revoked.
Default value: empty,
indicating that there is no
certificate revocation list.

SSL_CIPHER Encryption algorithm used for SSL For details about encryption
communication. algorithms supported by
GaussDB 100, see Table 3-4.
Default value: empty,
indicating that the peer end
can use all encryption
algorithms supported by
GaussDB 100. The algorithms
are sorted based on security
strength.

SSL_KEY_PA Ciphertext of a server private key. Refer to the actual


SSWORD If a private key is encrypted ciphertext.
before being stored, use this Default value: empty,
parameter to set the ciphertext. indicating that the private
key is not encrypted.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Parameter Description Value Range

SSL_EXPIRE Threshold for alarming SSL Value range: 7 to 180


_ALERT_TH certificate expiration. If SSL has Default value: 30 (unit: day)
RESHOLD been enabled, there will be a log
reminder when the expiration
time is less than the threshold.
It is checked upon startup. After
startup,
SSL_PERIOD_DETECTION will be
periodically checked.

SSL_PERIOD Period for detecting SSL Default value: 7 (unit: day)


_DETECTIO certificate expiration. If SSL has The parameter value cannot
N been started, the system will be changed.
periodically check the time before
SSL expiration after an instance is
started. If the time is less than
the threshold, a log reminder will
be reported.

Set environment variables related to SSL authentication on the GaussDB 100


client. For details, see Table 3-3.

The path of environment variables is set to /home/gaussdba/app as an example. Replace


it with the actual path.

Table 3-3 Client parameters


Environm Description Value Range
ent
Variable

ZSQL_SSL Client certificate file, Absolute path of a certificate file, for


_CERT including the client example:
public key. The export ZSQL_SSL_CERT='/home/gaussdba/app/
client.crt'
certificate proves the
legal identity of the Default value: empty
client and the public
key is sent to the peer
end for data
encryption.

ZSQL_SSL Client private key file Absolute path of a certificate file, for
_KEY used to decrypt digital example:
signatures and data export ZSQL_SSL_KEY='/home/gaussdba/app/
client.key'
encrypted using the
public key. Default value: empty

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Environm Description Value Range


ent
Variable

ZSQL_SSL Whether to negotiate Values and description:


_MODE with the server about ● disabled: Try only non-SSL connection.
SSL connection and
specifies the priority of ● preferred: If the server supports SSL
SSL connection. connection, the SSL connection is
preferred.
● required: Try only SSL connection. If
there is a CA file, the verification is
performed in the same way it is
performed when SSL_MODE is set to
verify_ca.
● verify_ca: Try only SSL connection and
check whether the server certificate is
issued by a trusted CA.
● verify_full: Try only SSL connection,
and check whether the server
certificate is issued by a trusted CA
and whether the host name of the
server is the same as that in the
certificate.
export ZSQL_SSL_MODE='REQUIRED'

Default value: preferred

ZSQL_SSL Root certificate file for Absolute path of a certificate file, for
_CA issuing client example:
certificates. The root export ZSQL_SSL_CA='/home/gaussdba/app/
cacert.pem'
certificate is used to
verify the server Default value: empty
certificate.

ZSQL_SSL CRL file for checking Absolute path of a certificate file, for
_CRL whether the server example:
certificate is in the CRL. export ZSQL_SSL_CRL='/home/gaussdba/app/
root.crl'
If it is, the certificate is
invalid. Default value: empty, indicating no CRL

ZSQL_SSL Encryption algorithm For details about encryption algorithms


_CIPHER used for SSL supported by GaussDB 100, see Table
communication. 3-4.
Default value: empty, indicating that the
peer end can use all encryption
algorithms supported by GaussDB 100.
The algorithms are sorted based on
security strength.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Environm Description Value Range


ent
Variable

ZSQL_SSL Ciphertext of a client Refer to the actual ciphertext. For a local


_KEY_PAS private key. If a private login, refer to Step 5 to generate
SWD key is encrypted before ciphertext for the private key file
being stored, use this password by using zencrypt and the
parameter to set the server encryption key (_FACTOR_KEY/
ciphertext. LOCAL_KEY). Run the following
command to export environment
variables:
export
ZSQL_SSL_KEY_PASSWD='PLFJgfZwLSOJFRp6o7qsj604
fFwPEu2MLxH7m/F/aMg='
The ciphertext is an example only.
Replace it with the ciphertext generated
in Step 5.
Default value: empty

A series of encryption and authentication algorithms with different strength are


supported for GaussDB 100 SSL transmission. You can modify SSL_CIPHER in the
zengine.ini file to specify the encryption algorithm used by the database server.
Table 3-4 lists the encryption algorithms supported by GaussDB 100 SSL
transmission.

Table 3-4 Encryption algorithms


Encryption Security Encryption Algorithm Description
Strength

stronger high DHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-RSA-AES128-GCM- using the RSA
SHA256 encryption
algorithm

stronger high ECDHE-ECDSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high ECDHE-ECDSA-AES128-GCM- using the
SHA256 ECDSA
encryption
algorithm

stronger high ECDHE-RSA-AES256-GCM- Suitable for


SHA384 certificates
generated by
using the RSA

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Encryption Security Encryption Algorithm Description


Strength

stronger high ECDHE-RSA-AES128-GCM- encryption


SHA256 algorithm

stronger high DHE-DSS-AES256-GCM- Suitable for


SHA384 certificates
generated by
stronger high DHE-DSS-AES128-GCM- using the DSA
SHA256 encryption
algorithm

stronger medium DHE-RSA-AES256-SHA256 Suitable for


certificates
stronger medium DHE-RSA-AES128-SHA256 generated by
using the RSA
encryption
algorithm

stronger medium DHE-DSS-AES256-SHA256 Suitable for


certificates
stronger medium DHE-DSS-AES128-SHA256 generated by
using the DSA
encryption
algorithm

stronger high DHE-RSA-AES256-CCM Suitable for


certificates
stronger high DHE-RSA-AES128-CCM generated by
using the RSA
encryption
algorithm

● Currently, GaussDB 100 SSL transmission supports encryption algorithms with the
encryption strength higher than strong.
● The default value of SSL_CIPHER is empty, which indicates that all encryption
algorithms listed in the preceding table are supported. You are advised to retain the
default value, unless there are other special requirements on the encryption algorithm.
● If multiple encryption algorithms are specified, separate them with semicolons (;). For
example, use SSL_CIPHER=DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256
in zengine.ini.

Creating a Self-Authentication Certificate


This section describes how to use OpenSSL to create a self-authentication digital
certificate. In a test environment, you can use the certificate for tests. In a
customer's operating environment, only a digital certificate obtained from a CA
can be used.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

If the OpenSSL component is installed in the operating system by default, you can
directly create a self-signed certificate. Otherwise, you need to install the
component before creating a self-signed certificate.
The OpenSSL component is installed by default on SUSE 10/11. The following
describes how to create a server self-signed certificate on SUSE. The default
installation path of OpenSSL on SUSE is /usr/share/ssl.

● When creating a self-signed certificate fails, delete the index.txt file from /usr/
share/ssl/misc/demoCA and run the touch index.txt command to recreate index.txt.
● To generate a client certificate, perform Step 9 through Step 15. In addition, replace
server with client in the commands of Step 9, Step 12, and Step 14.

Step 1 Log in to the OS as user root.


Step 2 Change the value of keyUsage in [v3_ca] in the openssl.cnf configuration file.
The path of the openssl.cnf file is /etc/ssl/openssl.cnf.
keyUsage = cRLSign, keyCertSign

Step 3 Go to the misc directory and view the files in the directory.
cd /usr/share/ssl/misc
ls

CA.pl c_hash c_issuer CA.sh c_info c_name

Step 4 Run the following command to create a CA. The system will create a demoCA
folder in the current directory.
./CA.sh -newca

Step 5 Enter a password for protecting the root certificate. The password must contain a
minimum of four characters, for example, 1234.
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

Step 6 Set the following parameters:


1. Set the following parameters:
Country Name (2 letter code) [AU]:cn
State or Province Name (full name) [Some-State]:shanxi
Locality Name (eg, city) []:xian
Organization Name (eg, company) [Internet Widgits Pty Ltd]:company-A
Organizational Unit Name (eg, section) []:Unit-A
## Common Name can be randomly set.
Common Name (eg, YOUR name) []:john
2. The following parameters are optional:
Email Address []:
A challenge password []:
An optional company name []: company-A

Step 7 Enter a password for protecting the root certificate. The password must contain a
minimum of four characters, for example, 1234.
Enter pass phrase for ./demoCA/private/./cakey.pem:

Step 8 Run the following command to add a CA extension item for the root certificate:
openssl x509 -req -in ./demoCA/careq.pem -extfile /etc/ssl/openssl.cnf -extensions v3_ca -signkey ./demoCA/
private/cakey.pem -out ./demoCA/cacert.pem -CAcreateserial -days 365

Step 9 Run the following command to generate the server certificate request file
server.req and server private key server.key based on different encryption
algorithms:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

● Based on the RSA encryption algorithm:


openssl req -newkey rsa:2048 -out server.req -keyout server.key

● Based on the DSA encryption algorithm:


a. Generate a DSA parameter file and a private key file.
openssl dsaparam -out dsakey.par 2048
openssl gendsa dsakey.par -out server.key

b. Create a certificate signature request file based on the DSA private key
file.
openssl req -new -key server.key -out server.req

● Based on the ECDSA encryption algorithm:


a. Generate an ECDSA private key file.
openssl ecparam -name secp384r1 -genkey -out server.key

b. Create an ECDSA certificate signature request file based on the ECDSA


private key.
openssl req -new -key server.key -out server.req

Step 10 If only the RSA encryption algorithm is used, enter the protection password of the
server private key. The password must contain 8 to 64 characters, for example,
Aa123456.
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

Step 11 Set the following parameters:


1. The following information must be the same as the information set when the
CA is created in Step 6.
Country Name (2 letter code) [AU]:cn
State or Province Name (full name) [Some-State]:shanxi
Locality Name (eg, city) []:xian
Organization Name (eg, company) [Internet Widgits Pty Ltd]:company-A
Organizational Unit Name (eg, section) []:Unit-A

2. The following information can be randomly set:


## Common Name can be randomly set.
Common Name (eg, YOUR name) []:rose

3. The following parameters are optional:


Email Address []:
A challenge password []:
An optional company name []: company-A

Step 12 Run the following command to sign the generated server certificate request file.
Then, the official server certificate server.crt will be generated.
openssl ca -in server.req -out server.crt

Step 13 Determine whether to sign the certificate and whether to submit the certificate
request that has passed the authentication.
● Yes: Sign the certificate and submit the request.
● No: Does not sign the certificate or submit the request.
Step 14 Run the following command to remove the password protection for the server
private key:
● Based on the RSA encryption algorithm:
openssl rsa -in server.key -out server.key

● Based on the DSA encryption algorithm:


openssl dsa -in server.key -out server.key

● Based on the ECDSA encryption algorithm:


openssl ec -in server.key -out server.key

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

If password protection for the server private key is not removed, use the zencrypt tool to
encrypt the password.
zencrypt -e aes256 -k work_key -f factor_key
The work_key and factor_key are values of LOCAL_KEY and _FACTOR_KEY respectively
obtained from the server parameter view. Set SSL_KEY_PASSWORD based on the
generated ciphertext.

Step 15 If only the RSA encryption algorithm is used, enter the password of the server
private key, for example, Aa123456.

----End

3.2 Managing Users, Roles, and Permissions


GaussDB 100 supports role-based access control to improve database security by
managing users, roles, and permissions.

3.2.1 Checking for Unknown Users


Configuration description
Unknown users refer to those why they are created is unknown. Unknown users
threaten database security. Therefore, you need to periodically check users,
confirm the use of each user, and delete unnecessary users to ensure that no
unknown user exists.
SYS and PUBLIC are preset users.
● SYS is used to initially create database instances.
● Permissions of user PUBLIC are automatically granted to all users of the
database. For example, if you grant the SELECT permission for the T1 table to
user PUBLIC (GRANT SELECT ON USER1.T1 TO PUBLIC;), all users can
access the T1 table; if you grant the DBA permission to user PUBLIC (GRANT
DBA TO PUBLIC;), all users have the DBA permission.
Configuration method
DROP USER user_name CASCADE;

Recommended value: none


Check method
SELECT USERNAME FROM DB_USERS;

Expected result: all users in the system


Risk level: medium

3.2.2 Checking the DBA Role


Check Description
The DBA role has all system permissions. Therefore, use this role only when
absolutely necessary. You are advised to use a user not inheriting the DBA role to
connect to the database.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Configuration method
Revoke the DBA role from a user or from the roles inherited by this user.
REVOKE DBA FROM user_name;
REVOKE DBA FROM role_name;

Recommended value: none


Check method
1. Check whether the user is granted with the DBA role.
SELECT GRANTEE, GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name' AND
GRANTEE != 'SYS' AND GRANTED_ROLE = 'DBA';
2. Check whether the DBA role is granted to the roles inherited by this user.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name' ;

Step 2 Check whether the DBA role is granted to the inherited roles.
SELECT GRANTEE, GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name' AND
GRANTEE != 'SYS' AND GRANTED_ROLE = 'DBA';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: roles of the user
Risk level: medium

3.2.3 Checking the CREATE USER Permission


Check Description
A user with the CREATE USER permission can create other users. If this permission
is no longer necessary, revoke it.
Configuration method
Revoke the CREATE USER permission from a user or from the roles inherited by
this user.
REVOKE CREATE USER FROM user_name;
REVOKE CREATE USER FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the CREATE USER permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'CREATE USER';
2. Check whether the roles inherited by this user have the CREATE USER
permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name' ;

Step 2 Check whether the CREATE USER permission is granted to the inherited roles.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'CREATE USER';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: none
Risk level: medium

3.2.4 Checking the ALTER USER Permission


Check Description
A user with the ALTER USER permission can modify other users. If this permission
is no longer necessary, revoke it.
Configuration method
Revoke the ALTER USER permission from a user or from the roles inherited by this
user.
REVOKE ALTER USER FROM user_name;
REVOKE ALTER USER FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the ALTER USER permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'ALTER USER';
2. Check whether the roles inherited by this user have the ALTER USER
permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Step 2 Check whether the ALTER USER permission is granted to the inherited roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'ALTER USER';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: none
Risk level: medium

3.2.5 Checking the DROP USER Permission


Check Description
A user with the DROP USER permission can delete other users. If this permission
is no longer necessary, revoke it.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Configuration method
Revoke the DROP USER permission from a user or from the roles inherited by this
user.
REVOKE DROP USER FROM user_name;
REVOKE DROP USER FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the DROP USER permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'DROP USER';
2. Check whether the roles inherited by this user have the DROP USER
permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Step 2 Check whether the DROP USER permission is granted to the inherited roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'DROP USER';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: none
Risk level: medium

3.2.6 Checking the CREATE DATABASE Permission


Check Description
A user with the CREATE DATABASE permission can create a database. If this
permission is no longer necessary, revoke it.
Configuration method
Revoke the CREATE DATABASE permission from a user or from the roles inherited
by this user.
REVOKE CREATE DATABASE FROM user_name;
REVOKE CREATE DATABASE FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the CREATE DATABASE permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'CREATE DATABASE';
2. Check whether the roles inherited by this user have the CREATE DATABASE
permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Step 2 Check whether the CREATE DATABASE permission is granted to the inherited
roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'CREATE DATABASE';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: none
Risk level: medium

3.2.7 Removing the WITH GRANT OPTION Permission


Attribute
Configuration description
Users with the WITH GRANT OPTION permission attribute can grant object
permissions to other users. For database security, specify this permission attribute
only when absolutely necessary.
The WITH GRANT OPTION permission attribute cannot be directly revoked. You
can only revoke the permission for which the WITH GRANT OPTION attribute is
specified.
Recommended value: none
Configuration method

Step 1 Revoke an object permission with WITH GRANT OPTION specified from a user.
REVOKE ALL ON object_name FROM user_name;

Step 2 Grant the object permission to this user again, without WITH GRANT OPTION
specified.
GRANT privilege_name ON object_name TO user_name;

----End
Check method
SELECT * FROM ADM_TAB_PRIVS WHERE GRANTABLE = 'YES';

Expected result: none


Risk level: medium

3.2.8 Removing the GRANT ANY PRIVILEGE Permission


Check Description
Users with the GRANT ANY PRIVILEGE permission can grant any system
permission to any user. Therefore, grant this permission only when absolutely
necessary.
Configuration method

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Revoke the GRANT ANY PRIVILEGE permission from a user or from the roles
inherited by this user.
REVOKE GRANT ANY PRIVILEGE FROM user_name;
REVOKE GRANT ANY PRIVILEGE FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the GRANT ANY PRIVILEGE permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'GRANT ANY PRIVILEGE';
2. Check whether the roles inherited by this user have the GRANT ANY
PRIVILEGE permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Step 2 Check whether the GRANT ANY PRIVILEGE permission is granted to the inherited
roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'GRANT ANY PRIVILEGE';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End
Expected result: none
Risk level: medium

3.2.9 Removing the GRANT ANY ROLE Permission


Check Description
Users with the GRANT ANY ROLE permission can grant any role (including the
DBA role) in the system to other users. Therefore, grant this permission only when
absolutely necessary.
Configuration method
Revoke the GRANT ANY ROLE permission from a user or from the roles inherited
by this user.
REVOKE GRANT ANY ROLE FROM user_name;
REVOKE GRANT ANY ROLE FROM role_name;

Recommended value: none


Check method
1. Check whether the user has the GRANT ANY ROLE permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'GRANT ANY ROLE';
2. Check whether the roles inherited by this user have the GRANT ANY ROLE
permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Step 2 Check whether the GRANT ANY ROLE permission is granted to the inherited roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'GRANT ANY ROLE';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End

Expected result: none

Risk level: medium

3.2.10 Removing the GRANT ANY OBJECT PRIVILEGE


Permission
Check Description

Users with the GRANT ANY OBJECT PRIVILEGE permission can grant any object
permission to any user. Therefore, grant this permission only when absolutely
necessary.

Configuration method

Revoke the GRANT ANY OBJECT PRIVILEGE permission from a user or from the
roles inherited by this user.
REVOKE GRANT ANY OBJECT PRIVILEGE FROM user_name;
REVOKE GRANT ANY OBJECT PRIVILEGE FROM role_name;

Recommended value: none

Check method

1. Check whether the user has the GRANT ANY OBJECT PRIVILEGE permission.
SELECT USERNAME, PRIVILEGE FROM DB_USER_SYS_PRIVS WHERE USERNAME = 'user_name' AND
PRIVILEGE = 'GRANT ANY OBJECT PRIVILEGE';
2. Check whether the roles inherited by this user have the GRANT ANY OBJECT
PRIVILEGE permission.

Step 1 Query for the roles inherited by this user.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'user_name';

Step 2 Check whether the GRANT ANY OBJECT PRIVILEGE permission is granted to the
inherited roles.
SELECT ROLE, PRIVILEGE FROM ROLE_SYS_PRIVS WHERE ROLE = 'role_name' AND ROLE != 'DBA' AND
PRIVILEGE = 'GRANT ANY OBJECT PRIVILEGE';

Step 3 Check whether each inherited role inherits other roles.


SELECT GRANTED_ROLE FROM ADM_ROLE_PRIVS WHERE GRANTEE = 'role_name';

Step 4 Repeat step 2 and step 3 until no record is returned in step3.

----End

Expected result: none

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3.2.11 Removing All Object Permissions from User PUBLIC


Configuration description

Every user automatically belongs to user PUBLIC. For database security, do not
grant object permissions to user PUBLIC.

Configuration method
REVOKE ALL ON object_name FROM public;

Recommended value: none

Check method
SELECT * FROM ADM_TAB_PRIVS WHERE GRANTEE='PUBLIC';

Expected result: default permissions listed in Table 3-5

Risk level: medium

Table 3-5 Default permissions of user PUBLIC

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS DB_ARGU VIEW SELECT NO


MENTS

PUBLIC SYS DB_COL_C VIEW SELECT NO


OMMENTS

PUBLIC SYS DB_CONST VIEW SELECT NO


RAINTS

PUBLIC SYS DB_DBLINK VIEW SELECT NO


_TABLES

PUBLIC SYS DB_DBLINK VIEW SELECT NO


_TAB_COLU
MNS

PUBLIC SYS DB_DEPEN VIEW SELECT NO


DENCIES

PUBLIC SYS DB_VIEW_ VIEW SELECT NO


DEPENDEN
CIES

PUBLIC SYS DB_DISTRI VIEW SELECT NO


BUTE_RULE
S

PUBLIC SYS DB_DIST_R VIEW SELECT NO


ULE_COLS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS DB_HISTO VIEW SELECT NO


GRAMS

PUBLIC SYS DB_INDEXE VIEW SELECT NO


S

PUBLIC SYS DB_IND_C VIEW SELECT NO


OLUMNS

PUBLIC SYS DB_IND_PA VIEW SELECT NO


RTITIONS

PUBLIC SYS DB_OBJECT VIEW SELECT NO


S

PUBLIC SYS DB_PART_C VIEW SELECT NO


OL_STATIS
TICS

PUBLIC SYS DB_PART_K VIEW SELECT NO


EY_COLUM
NS

PUBLIC SYS DB_PART_S VIEW SELECT NO


TORE

PUBLIC SYS DB_PART_T VIEW SELECT NO


ABLES

PUBLIC SYS DB_PROCE VIEW SELECT NO


DURES

PUBLIC SYS DB_SEQUE VIEW SELECT NO


NCES

PUBLIC SYS DB_SOURC VIEW SELECT NO


E

PUBLIC SYS DB_SYNON VIEW SELECT NO


YMS

PUBLIC SYS DB_TABLES VIEW SELECT NO

PUBLIC SYS DB_TAB_C VIEW SELECT NO


OLS

PUBLIC SYS DB_TAB_C VIEW SELECT NO


OLUMNS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS DB_TAB_C VIEW SELECT NO


OL_STATIS
TICS

PUBLIC SYS DB_TAB_C VIEW SELECT NO


OMMENTS

PUBLIC SYS DB_TAB_DI VIEW SELECT NO


STRIBUTE

PUBLIC SYS DB_TAB_PA VIEW SELECT NO


RTITIONS

PUBLIC SYS DB_TAB_ST VIEW SELECT NO


ATISTICS

PUBLIC SYS DB_TRIGGE VIEW SELECT NO


RS

PUBLIC SYS DB_VIEWS VIEW SELECT NO

PUBLIC SYS DB_VIEW_C VIEW SELECT NO


OLUMNS

PUBLIC SYS DBMS_LOB PROCEDUR EXECUTE NO


E

PUBLIC SYS DBMS_OUT PROCEDUR EXECUTE NO


PUT E

PUBLIC SYS DBMS_RAF PROCEDUR EXECUTE NO


T E

PUBLIC SYS DBMS_RAN PROCEDUR EXECUTE NO


DOM E

PUBLIC SYS DBMS_SQL PROCEDUR EXECUTE NO


E

PUBLIC SYS DBMS_STA PROCEDUR EXECUTE NO


NDARD E

PUBLIC SYS DBMS_STA PROCEDUR EXECUTE NO


TS E

PUBLIC SYS DBMS_UTIL PROCEDUR EXECUTE NO


ITY E

PUBLIC SYS SYS_DUM TABLE SELECT NO


MY

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS NLS_SESSI VIEW SELECT NO


ON_PARA
METERS

PUBLIC SYS ROLE_SYS_ VIEW SELECT NO


PRIVS

PUBLIC SYS MY_ARGU VIEW SELECT NO


MENTS

PUBLIC SYS MY_COL_C VIEW SELECT NO


OMMENTS

PUBLIC SYS MY_CONST VIEW SELECT NO


RAINTS

PUBLIC SYS MY_CONS_ VIEW SELECT NO


COLUMNS

PUBLIC SYS MY_DEPEN VIEW SELECT NO


DENCIES

PUBLIC SYS MY_FREE_S VIEW SELECT NO


PACE

PUBLIC SYS MY_HISTO VIEW SELECT NO


GRAMS

PUBLIC SYS MY_INDEX VIEW SELECT NO


ES

PUBLIC SYS MY_IND_C VIEW SELECT NO


OLUMNS

PUBLIC SYS MY_IND_P VIEW SELECT NO


ARTITIONS

PUBLIC SYS MY_IND_ST VIEW SELECT NO


ATISTICS

PUBLIC SYS MY_JOBS VIEW SELECT NO

PUBLIC SYS MY_OBJEC VIEW SELECT NO


TS

PUBLIC SYS MY_PART_ VIEW SELECT NO


COL_STATI
STICS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS MY_PART_ VIEW SELECT NO


KEY_COLU
MNS

PUBLIC SYS MY_PART_S VIEW SELECT NO


TORE

PUBLIC SYS MY_PART_T VIEW SELECT NO


ABLES

PUBLIC SYS MY_PROCE VIEW SELECT NO


DURES

PUBLIC SYS MY_ROLE_ VIEW SELECT NO


PRIVS

PUBLIC SYS MY_SEGME VIEW SELECT NO


NTS

PUBLIC SYS MY_SEQUE VIEW SELECT NO


NCES

PUBLIC SYS MY_SOURC VIEW SELECT NO


E

PUBLIC SYS MY_SQL_M VIEW SELECT NO


APS

PUBLIC SYS MY_SYNO VIEW SELECT NO


NYMS

PUBLIC SYS MY_SYS_PR VIEW SELECT NO


IVS

PUBLIC SYS MY_TABLES VIEW SELECT NO

PUBLIC SYS MY_TAB_C VIEW SELECT NO


OLS

PUBLIC SYS MY_TAB_C VIEW SELECT NO


OLUMNS

PUBLIC SYS MY_TAB_C VIEW SELECT NO


OL_STATIS
TICS

PUBLIC SYS MY_TAB_C VIEW SELECT NO


OMMENTS

PUBLIC SYS MY_TAB_DI VIEW SELECT NO


STRIBUTE

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

User Object Object Object Permission Whether


Owner Name Type to Specify
WITH
GRANT
OPTION

PUBLIC SYS MY_TAB_M VIEW SELECT NO


ODIFICATI
ONS

PUBLIC SYS MY_TAB_PA VIEW SELECT NO


RTITIONS

PUBLIC SYS MY_TAB_PR VIEW SELECT NO


IVS

PUBLIC SYS MY_TAB_ST VIEW SELECT NO


ATISTICS

PUBLIC SYS MY_TRIGG VIEW SELECT NO


ERS

PUBLIC SYS MY_USERS VIEW SELECT NO

PUBLIC SYS MY_VIEWS VIEW SELECT NO

PUBLIC SYS MY_VIEW_ VIEW SELECT NO


COLUMNS

PUBLIC SYS DV_ME VIEW SELECT NO

PUBLIC SYS DV_USER_P VIEW SELECT NO


ARAMETER
S

PUBLIC SYS DB_VIEW_ VIEW SELECT NO


DEPENDEN
CIES

3.3 Configuring User Security Policies


For database security, GaussDB 100 provides security policies for password
management, account management, and other aspects.

3.3.1 Configuring the Number Of Days Before Which a


Password Cannot Be Reused
Configuration description
You must configure the number of days before which a password cannot be
reused. This configuration prevents password cracking caused by password reuse.
It is configured by setting the PASSWORD_REUSE_TIME parameter (unit: day).
After this parameter is set, the password can be reused only after the specified
number of days. Before setting this parameter, you can run the SELECT Username,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

PROFILE FROM ADM_USERS; statement to check the profile configuration of the


user.

Configuration method
ALTER PROFILE profile_name LIMIT PASSWORD_REUSE_TIME 60;

Recommended value: 60

Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='PASSWORD_REUSE_TIME';

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
PASSWORD_REUSE_TIME 60

Risk level: medium

3.3.2 Configuring the Number Of Password Changes Required


Before the Current Password Can Be Reused
Configuration description

Configure the number of password changes required before the current password
can be reused. The configuration prevents a password from being cracked due to
repeated use. Before setting this parameter, you can run the SELECT Username,
PROFILE FROM ADM_USERS; statement to check the profile configuration of the
user.

NOTICE

The PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX parameters must be


configured in conjunction. Set the two parameters as follows:
● If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to
UNLIMITED. The password can be reused without any restrictions.
● If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to specified
values, the password can be reused only when the conditions specified by both
the parameters are met.
● If either of PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME is set to a
specified value and the other is set to UNLIMITED, the password cannot be
reused. The value is a positive integer.

Configuration method
ALTER PROFILE profile_name LIMIT PASSWORD_REUSE_MAX 3;

Recommended value: 3

Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='PASSWORD_REUSE_MAX';

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
PASSWORD_REUSE_MAX 3

Risk level: medium

3.3.3 Configuring the Number of Failed Login Attempts


Configuration description
The FAILED_LOGIN_ATTEMPTS parameter specifies the maximum number of
login attempts allowed before an account is locked. If the number of an account's
login failures exceeds the value of this parameter, the system automatically locks
the account. The default value is 10. Before setting this parameter, you can run
the SELECT Username, PROFILE FROM ADM_USERS; statement to check the
profile configuration of the user.
Configuration method
ALTER PROFILE profile_name LIMIT FAILED_LOGIN_ATTEMPTS 10;

Recommended value: 10
Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='FAILED_LOGIN_ATTEMPTS';

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
FAILED_LOGIN_ATTEMPTS 10

Risk level: medium

3.3.4 Configuring the Account Lock Time


Configuration description
The PASSWORD_LOCK_TIME parameter specifies the number of days an account
will be locked after the specified number of consecutive failed login attempts. If
the account lock time exceeds the value of PASSWORD_LOCK_TIME (default: one
day), the system automatically unlocks the user. Larger parameter values bring
higher account security. However, if the value of this parameter is set too large,
inconvenience may occur.
Before setting this parameter, you can run the SELECT Username, PROFILE FROM
ADM_USERS; statement to check the profile configuration of the user.
Configuration method
ALTER PROFILE profile_name LIMIT PASSWORD_LOCK_TIME 1;

Recommended value: one day


Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='PASSWORD_LOCK_TIME';

Expected result:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
PASSWORD_LOCK_TIME 1

Risk level: medium

3.3.5 Changing the Password of the Initial User


Configuration description

The initial user SYS is a system administrator and has all system permissions. For
database security, change the password of SYS as soon as possible after the
database is installed.

Configuration method
ALTER USER user_name IDENTIFIED BY newpassword REPLACE oldpassword;

Recommended value: none

Check method

Use the new password to log in to the database. If the login is successful, the
password has been changed successfully.

Expected result: none

Risk level: high

3.3.6 Configuring the Password Lifetime


Configuration description

The PASSWORD_LIFE_TIME parameter specifies the number of days the same


password can be used. The default value is 180 days. After the configuration, the
system provides a password grace period after the password validity period
expires. In this case, you need to change the password before the expiration of the
password grace period. Otherwise, you will be promoted of password expiration
and cannot access the database.

Before setting this parameter, you can run the SELECT Username, PROFILE FROM
ADM_USERS; statement to check the profile configuration of the user.

Configuration method
ALTER PROFILE profile_name LIMIT PASSWORD_LIFE_TIME 60;

Recommended value: none

Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='PASSWORD_LIFE_TIME';

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
PASSWORD_LIFE_TIME 60

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3.3.7 Configuring the Password Grace Period


Configuration description
The password grace period is the days between password expiration warning and
password expiration. In this grace period, users can change their passwords before
password expiration, ensuring service continuity. Before setting this parameter, you
can run the SELECT Username, PROFILE FROM ADM_USERS; statement to check
the profile configuration of the user.
Configuration method
ALTER PROFILE profile_name LIMIT PASSWORD_GRACE_TIME 7;

Recommended value: 7
Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='PASSWORD_GRACE_TIME';

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
PASSWORD_GRACE_TIME 7

Risk level: medium

3.3.8 Configuring the Maximum Number of Connections of a


Single User
Configuration description
Configure the maximum number of connections of a single user to prevent login
failures due to insufficient system connections. Before the configuration, you can
run the SELECT User name, PROFILE FROM ADM_USERS; statement to check the
profile configuration of the user.
Configuration method
ALTER PROFILE profile_name LIMIT SESSIONS_PER_USER 100;
ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;

Recommended value: 30–800 (You can set is as needed.)


Check method
SELECT RESOURCE_NAME, THRESHOLD FROM ADM_PROFILES WHERE
RESOURCE_NAME='SESSIONS_PER_USER';
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME='RESOURCE_LIMIT';

Expected result:
RESOURCE_NAME THRESHOLD
---------------------------------------------------------------- --------------------
SESSIONS_PER_USER 100
NAME VALUE
----------------------------------------------------------------
----------------------------------------------------------------
RESOURCE_LIMIT TRUE

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3.4 Configuring Database Audit


For database security, certain operations of database users need to be audited.
GaussDB 100 allows you to audit specified users' certain operations, including
creation, login, authorization, and such operations as CREATE, UPDATE, and
DROP performed on database objects.

3.4.1 Enabling Database Audit


Configuration description
Audit logs are important in tracing data, locating faults, and clarifying
responsibilities after security events occur. Database audit is configured by setting
the AUDIT_LEVEL parameter. AUDIT_LEVEL = 0 disables audit logs. If
AUDIT_LEVEL is set to a value greater than 0, audit logs are enabled, and
requests for such operations as user login and logout requests are also audited. By
default, audit logs are enabled and the audit level is 3, indicating that DDL and
DCL operations are audited. You are advised to set the audit log level as needed.
Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 3;

Recommended value: 3
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 3

Risk level: medium

3.4.2 Enabling DDL Audit


Configuration description
If AUDIT_LEVEL is set to 1, only Data Definition Language (DDL) operations such
as CREATE, DROP, and ALTER are audited. DDL is used to define or modify
database objects, such as tables, indexes, views, synonyms, databases, sequences,
users, roles, tablespaces, profiles, and sessions. In addition, creation and deletion
of stored procedures (excluding anonymous blocks), customized functions, and
triggers are also audited.
Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 1;

Recommended value: 3
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME ='AUDIT_LEVEL';

Expected result:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 1

Risk level: medium

3.4.3 Enabling DCL Audit


Configuration description

If AUDIT_LEVEL is set to 2, only Data Control Language (DCL) operations are


audited. DCL is used to set or change the permissions for database sessions and
objects. DCL operations include COMMIT, ROLLBACK, GRANT, REVOKE,
SHUTDOWN, and LOCK TABLE.

Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 2;

Recommended value: 3

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 2

Risk level: medium

3.4.4 Enabling DML Audit


Configuration description

If AUDIT_LEVEL is set to 4, Data Manipulation Language (DML) operations, such


as INSERT, UPDATE, DELETE, and SELECT are audited. DML is used to manage
table data.

Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 4;

Recommended value: 3

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 4

Risk level: medium

3.4.5 Enabling PL Audit


Configuration description

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

If the audit level is set to 8, the parsing and execution of stored procedures are
audited, for example, EXECUTE (EXEC) and CALL. In addition, the definitions of
anonymous blocks in stored procedures are audited.

Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 8;

Recommended value: 3

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 8

Risk level: medium

3.4.6 Enabling DDL and DCL Audit


Configuration description

If AUDIT_LEVEL is set to 3, DDL and DCL operations are audited.

Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 3;

Recommended value: 3

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 3

Risk level: medium

3.4.7 Enabling DDL and DML Audit


Configuration description

If AUDIT_LEVEL is set to 5, DDL and DML operations are audited.

Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 5;

Recommended value: 3

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 5

Risk level: medium

3.4.8 Enabling DCL and DML Audit


Configuration description
If AUDIT_LEVEL is set to 6, DCL and DML operations are audited.
Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 6;

Recommended value: 3
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 6

Risk level: medium

3.4.9 Enabling Audit for All Operations


Configuration description
If AUDIT_LEVEL is set to 15, all operations are audited, including DDL, DCL, DML,
and PL operations.
Configuration method
ALTER SYSTEM SET AUDIT_LEVEL = 15;

Recommended value: 3
Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'AUDIT_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
AUDIT_LEVEL 15

Risk level: medium

3.4.10 Configuring the Audit File Path


Configuration description
The LOG_HOME parameter specifies the storage path of the audit file. By default,
the audit file is stored in the ${GSDB_DATA}/log/audit directory.
Configuration method
You can configure the audit file path in either of the following ways:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

● Change the value of LOG_HOME in the zengine.ini configuration file to the


specified path and restart the database for the change to take effect. The
path of the zengine.ini file is ${GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of LOG_HOME
and restart the database for the change to take effect. The path /home/
gaussdba/data/log is used as an example. Replace it with the actual path.
ALTER SYSTEM SET LOG_HOME = '/home/gaussdba/data/log' SCOPE=PFILE;

Recommended value: ${GSDB_DATA}/log/

Check method
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'LOG_HOME';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
LOG_HOME /home/gaussdba/data/log

Risk level: low

3.4.11 Configuring the Maximum Capacity of an Audit Log


File
Configuration description

The parameter _AUDIT_MAX_FILE_SIZE specifies the maximum capacity of an


audit log file. The default unit is byte and the default value is 10M. If the size of
an audit log file reaches the specified value, another audit log file is automatically
created.

Configuration method

You can configure the maximum capacity of an audit log file in either of the
following ways:

● Set the _AUDIT_MAX_FILE_SIZE parameter in the zengine.ini configuration


file and restart the database for the setting to take effect. The path of the
zengine.ini file is {GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of
_AUDIT_MAX_FILE_SIZE. The change takes effect immediately after the
statement is executed (it does not take effect for existing files).
ALTER SYSTEM SET _AUDIT_MAX_FILE_SIZE = 10M;

Recommended value: 10M

Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = '_AUDIT_MAX_FILE_SIZE';

Expected result:
NAME VALUE
---------------------------------------------------------------- ------------------------
_AUDIT_MAX_FILE_SIZE 10M

Risk level: low

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

3.4.12 Configuring the Maximum Number of Backup Audit


Files
Configuration description
The _AUDIT_BACKUP_FILE_COUNT parameter specifies the maximum number of
backup audit log files. If the number of backup files exceeds the specified value,
the earliest backup files are automatically deleted and the backup deletion
information is recorded in audit logs.
Configuration method
You can configure the maximum number of backup audit files in either of the
following ways:
● Set the _AUDIT_BACKUP_FILE_COUNT parameter in the zengine.ini
configuration file and restart the database for the setting to take effect. The
path of the zengine.ini file is {GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of
_AUDIT_BACKUP_FILE_COUNT. The change takes effect immediately after
the statement is executed.
ALTER SYSTEM SET _AUDIT_BACKUP_FILE_COUNT = 10;

Recommended value: 10
Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = '_AUDIT_BACKUP_FILE_COUNT';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
_AUDIT_BACKUP_FILE_COUNT 10

Risk level: medium

3.5 Configuring Error Reports and Logs


Logs and error reports help locate faults and restore the database.

3.5.1 Configuring the Log Path


Configuration description
The LOG_HOME parameter specifies the storage path of log files. By default, log
files are stored in the ${GSDB_DATA}/log/ directory.
Configuration method
You can configure the log path in either of the following ways:
● Change the value of LOG_HOME in the zengine.ini configuration file to the
specified path and restart the database for the change to take effect. The
path of the zengine.ini file is ${GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of LOG_HOME
and restart the database for the change to take effect. The path /home/
gaussdb/data/log is used as an example. Replace it with the actual path.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

ALTER SYSTEM SET LOG_HOME = '/home/gaussdb/data/log' SCOPE=PFILE;

Recommended value: ${GSDB_DATA}/log/


Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LOG_HOME';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
LOG_HOME /home/gaussdb/data/log

Risk level: medium

3.5.2 Configuring the Log File Permission


Configuration description
The _LOG_FILE_PERMISSIONS parameter specifies the log file permission.
Configuration method
You can configure the log file permission in either of the following ways:
● Change the value of _LOG_FILE_PERMISSIONS in the zengine.ini
configuration file to the specified permission and restart the database for the
change to take effect. The path of the zengine.ini file is {GSDB_DATA}/cfg/
zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of
_LOG_FILE_PERMISSIONS. The change takes effect immediately after the
statement is executed (it does not take effect for existing files).
ALTER SYSTEM SET _LOG_FILE_PERMISSIONS = 600;

Recommended value: 600


Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = '_LOG_FILE_PERMISSIONS';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
_LOG_FILE_PERMISSIONS 600

Risk level: medium

3.5.3 Configuring the Log Directory Permission


Configuration description
The _LOG_PATH_PERMISSIONS parameter specifies the log directory permission.
Configuration method
You can configure the log directory permission in either of the following ways:
● Change the value of _LOG_PATH_PERMISSIONS in the zengine.ini
configuration file to the specified permission and restart the database for the
change to take effect. The path of the zengine.ini file is {GSDB_DATA}/cfg/
zengine.ini.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

● Run the ALTER SYSTEM SET statement to change the value of


_LOG_PATH_PERMISSIONS. When a log file is backed up or a log file is
created, _LOG_PATH_PERMISSIONS dynamically takes effect to control the
directory permissions.
ALTER SYSTEM SET _LOG_PATH_PERMISSIONS = 700;

Recommended value: 700


Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = '_LOG_PATH_PERMISSIONS';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
_LOG_PATH_PERMISSIONS 700

Risk level: medium

3.5.4 Configuring Server Logging Levels


Configuration description
The _LOG_LEVEL parameter specifies the levels of run logs and debug logs to be
written into the server. The default value is 7, indicating that run logs in all levels
are written into the server. The log levels are described as follows:

Log Level Open Flag

RUN ERROR 0x00000001(1)

RUN WARNING 0x00000002(2)

RUN INFORMATION 0x00000004(4)

DEBUG ERROR 0x00000010(16)

DEBUG WARNING 0x00000020(32)

DEBUG INFORMATION 0x00000040(64)

To enable different levels of logging, set _LOG_LEVEL to a sum. For example, if


RUN ERROR and DEGBU ERROR logging needs to be enabled, set _LOG_LEVEL to
17, that is, 0x00000001(1) + 0x00000010(16).
If _LOG_LEVEL is set to 0, not only RUN and DEBUG logging, but also ALARM
logging will be disabled. This helps handle emergencies.
Configuration method
You can configure server logging levels in either of the following ways:
● Change the value of _LOG_LEVEL in the zengine.ini configuration file and
restart the database for the change to take effect. The path of the zengine.ini
file is {GSDB_DATA}/cfg/zengine.ini.
● Run the ALTER SYSTEM SET statement to change the value of _LOG_LEVEL.
The change takes effect immediately after the statement is executed.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
Security Hardening Guide (Standalone) 3 Database Configuration

ALTER SYSTEM SET _LOG_LEVEL = 7;

Recommended value: 7
Check method
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = '_LOG_LEVEL';

Expected result:
NAME VALUE
---------------------------------------------------------------- -------------------------
_LOG_LEVEL 7

Risk level: medium

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

4 Interface Mapping (GaussDB 100 Native


Interface Names vs. Mainstream Database
Interface Names)

4.1 Data Dictionary Tables


Table 4-1 Name mapping of data dictionary tables (GaussDB 100 native interface
names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

4.2 DBA Views


Table 4-2 Name mapping of DBA views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

4.3 User Views


Table 4-3 Name mapping of user views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_ARGUMENTS ALL_ARGUMENTS

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

4.4 Dynamic Performance Views


Table 4-4 Name mapping of dynamic performance views (GaussDB 100 native
interface names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100 4 Interface Mapping (GaussDB 100 Native Interface
Security Hardening Guide (Standalone) Names vs. Mainstream Database Interface Names)

4.5 Configuration Parameters


Table 4-5 Name mapping of configuration parameters (GaussDB 100 native
interface names vs. mainstream database interface names)
GaussDB 100 Native Interface Name Mainstream Database Interface
Name

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100
V300R001C00

Security Maintenance Guide


(Standalone)

Issue 04
Date 2019-12-28

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior
written consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and
the customer. All or part of the products, services and features described in this document may not be
within the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,
information, and recommendations in this document are provided "AS IS" without warranties, guarantees
or representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: https://e.huawei.com

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Security Maintenance Guide (Standalone) Contents

Contents

1 About This Document.............................................................................................................1


2 Security Maintenance Suggestions..................................................................................... 4
3 Database Security Maintenance.......................................................................................... 6
3.1 Configuring Client Access Authentication.......................................................................................................................6
3.2 Managing Users and Their Permissions........................................................................................................................ 10
3.2.1 Users and Roles.................................................................................................................................................................. 10
3.2.2 User List................................................................................................................................................................................ 11
3.2.3 Viewing Users..................................................................................................................................................................... 14
3.2.4 Managing User Permissions.......................................................................................................................................... 15
3.2.4.1 Creating a User and Granting Permissions........................................................................................................... 15
3.2.4.2 Viewing Permissions of a User or Role................................................................................................................... 17
3.2.4.3 Modifying a User and Its Permissions.................................................................................................................... 17
3.2.4.4 Deleting a User............................................................................................................................................................... 19
3.3 Configuring Password Security Policies......................................................................................................................... 20
3.4 Configuring Account Security Policies........................................................................................................................... 22
3.5 Configuring Database Audit Policies.............................................................................................................................. 24
3.5.1 Audit Overview................................................................................................................................................................... 24
3.5.2 Configuring Database Audit.......................................................................................................................................... 25
3.5.3 Viewing Audit Results...................................................................................................................................................... 27
3.5.4 Maintaining Audit Logs................................................................................................................................................... 27
3.6 Configuring File Permission Security Policies.............................................................................................................. 28

4 Linux Operating System Security Maintenance.............................................................33


4.1 Changing the System Password....................................................................................................................................... 33
4.2 Checking System Accounts................................................................................................................................................ 33
4.3 Checking System Processes............................................................................................................................................... 34
4.4 Checking Services and Ports..............................................................................................................................................34

5 Machine-to-Machine Interfaces.........................................................................................35
5.1 Common.py............................................................................................................................................................................. 35
5.2 Common.pyc........................................................................................................................................................................... 35
5.3 GaussLog.py............................................................................................................................................................................ 35
5.4 GaussLog.pyc.......................................................................................................................................................................... 35

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Security Maintenance Guide (Standalone) Contents

6 Interface Mapping (GaussDB 100 Native Interface Names vs. Mainstream


Database Interface Names)................................................................................................... 36
6.1 Data Dictionary Tables........................................................................................................................................................ 36
6.2 DBA Views............................................................................................................................................................................... 38
6.3 User Views............................................................................................................................................................................... 41
6.4 Dynamic Performance Views............................................................................................................................................ 43
6.5 Configuration Parameters.................................................................................................................................................. 46

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Security Maintenance Guide (Standalone) 1 About This Document

1 About This Document

Overview
GaussDB 100 is a high-performance and high-reliability distributed relational
database developed by Huawei Technologies Co., Ltd., breaking the storage and
performance bottlenecks of a single server.

The framework of GaussDB 100 is component-based and can be used for a


standalone database or a cluster. To enhance the security of GaussDB 100, a series
of security rules are formulated based on Huawei security requirements. This
document describes how to perform security maintenance on GaussDB 100 and
Linux where the database is running.

GaussDB 100 is compatible with the user habits of mainstream databases. You can
use native GaussDB 100 interface names or their corresponding names in the
mainstream databases. For details, see Interface Mapping (GaussDB 100 Native
Interface Names vs. Mainstream Database Interface Names). The interfaces
mentioned in this document use their native GaussDB 100 names.

Applicable Scope
This document is designed for all Huawei products that use GaussDB 100.

Intended Audience
This document is intended for all GaussDB 100 users.

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not


avoided, will result in death or serious injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in death or serious injury.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Security Maintenance Guide (Standalone) 1 About This Document

Symbol Description

Indicates a potentially hazardous situation which, if not


avoided, could result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not


avoided, could result in equipment damage, data loss,
performance deterioration, or unanticipated results.
NOTICE is used to address practices not related to personal
injury.

Calls attention to important information, best practices, and


tips.
NOTE is used to address information not related to personal
injury, equipment damage, and environment deterioration.

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are


in italics.

[] Items (keywords and parameters) in brackets [ ] are


optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more


options or no item is selected.

{ x | y | ... } Indicates that one item is selected from two or more


options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can


be selected. If multiple parameters are selected, separate
them with commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If


multiple parameters are selected, separate them with
commas (,).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Security Maintenance Guide (Standalone) 1 About This Document

Change History
Version Change Description Date

04 This issue is the fourth official release. 2019-07-18

03 Rectified known defects. 2019-06-26

02 Added: 2019-04-05
● Descriptions of users SYS and public
in Users and Roles
Modified:
● Role STATISTICS added to Users and
Roles
● Procedure in Viewing Permissions of
a User or Role
● Directory and file permissions in
Configuring File Permission Security
Policies
● Configuring Client Access
Authentication
● Descriptions about how to change a
password in Configuring Password
Security Policies

01 This issue is the first official release. 2018-10-30

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Security Maintenance Guide (Standalone) 2 Security Maintenance Suggestions

2 Security Maintenance Suggestions

Security threats are diverse and cannot be overcome by pure technologies. You
need to set up a security management system based on security maintenance
suggestions to safeguard your application systems.

Patch Management
A patch can fix system faults and expand system applications. You need to
manage program patches using special regulations and specify personnel to check
patches for the operating system and GaussDB 100. To install a patch, you must
contact Huawei technical support.

Self-Compiled Script Management


Self-compiled scripts that will run on GaussDB 100 must be first verified in users'
test environments before being implemented, which prevents compatibility issues.

Security Emergency Response Mechanism


You need to set up an emergency plan for timely handling security accidents. This
helps recover production, resolve problems, and minimize loss.

● Service recovery is the top priority.


When there is an emergency fault, maintenance personnel must keep calm
and contact Huawei technical support to confirm what operations have been
performed before the fault occurs as soon as possible, including but not
limited to:
– Modification to database configurations
– Upgrade
– Network cable removal and insertion
● Collect as much fault information as possible.
When there is an accident, collect information related to the accident in time
without delaying service recovery. Send the accident handling reports, device
alarm files, and log files to Huawei for analysis and location. This helps
determine the root cause of the accident, enabling Huawei to provide better
after-sales services.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Security Maintenance Guide (Standalone) 2 Security Maintenance Suggestions

Defect Reporting
When GaussDB 100 is attacked, Huawei uses different processing methods based
on the attack situation.
If a user reports a system attack, Huawei will use either of the following methods
to resolve the problem:
● If a security accident occurs on site, Huawei technical support engineers will
provide remote or onsite support and work together with the user to quickly
resolve the problem and minimize the attack impact on the system.
● If no security accident occurs, Huawei technical support engineers will report
the problem to the R&D team. After the R&D team provides a solution,
Huawei technical support engineers will analyze the solution impact on the
onsite services and propose corresponding suggestions.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

3 Database Security Maintenance

This chapter mainly describes how administrators set account permissions, file
permissions, and audit policies to ensure the high reliability and stability of a
database.

3.1 Configuring Client Access Authentication


Scenario
You can configure client access authentication to allow remote host access. You
can configure a user whitelist, IP address whitelist, or IP address blacklist to
control remote connections to GaussDB 100. By default, only local access is
allowed.

● User whitelist: You can add users to zhba.conf so that these users access the
database only through the IP addresses specified in zhba.conf.
● IP address whitelist: Only the IP addresses specified by TCP_INVITED_NODES
can be used to access the database.
● IP address blacklist: The IP addresses specified by TCP_EXCLUDED_NODES
cannot be used to access the database.

The IP address blacklist has the highest priority. If an IP address is configured in all
the three lists, it cannot be used for remote access.

When the user whitelist, IP address whitelist, and IP address blacklist are all
enabled:

● Users in the user whitelist can use the IP addresses in the user whitelist and IP
address whitelist to remotely connect to databases (the IP addresses must not
be in the IP address blacklist).
● If the IP address of a client is in the user whitelist (zhba.conf) or IP address
whitelist and not in the IP address blacklist, it will pass the verification for
login regardless of whether the user is in the user whitelist.

For details about remote access policies, see Figure 3-1.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Figure 3-1 Access authentication

If user SYS locally logs in to a database in password-free mode, the login will not be limited
by the user whitelist, IP address whitelist, or IP address blacklist.
If user SYS logs in to a database using an encrypted password, the login will be limited by
the IP address blacklist.

Precautions
● Before enabling IP address whitelist checking, ensure that at least one of
TCP_INVITED_NODES and TCP_EXCLUDED_NODES is set. Otherwise, the
error message "GS-00254: For invited and excluded nodes is both empty, ip
whitelist function can't be enabled" will be displayed.
● User SYS can only locally log in to a database.

Prerequisites
Before configuring a user whitelist, IP address blacklist, or IP address whitelist,
ensure that LSNR_ADDR and LSNR_PORT have been configured. Otherwise, the
configuration will not take effect. Do as follows:

Method 1:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Step 1 Check whether the listening IP address and port have been configured on the
server.
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_ADDR';
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_PORT';

● If they have been configured, finish the procedure.


Step 2 If they have not been configured, run the following statement to enable the
floating IP address of the database: (The setting takes effect immediately.)
ALTER SYSTEM ADD LSNR_ADDR '192.168.1.1';

----End
Method 2:

Step 1 Check whether the listening IP address and port have been configured on the
server.
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_ADDR';
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_PORT';

● If they have been configured, finish the procedure.


● If they have not been configured, run the following statements to configure
them, and then go to Step 2:
ALTER SYSTEM SET LSNR_ADDR='127.0.0.1,192.168.1.1';
ALTER SYSTEM SET LSNR_PORT = 1888;

Step 2 Restart the database for the configurations of the listening IP address and
listening port number to take effect.
cd ${GSDB_DATA}/bin
python zctl.py -t stop
python zctl.py -t start

----End

Procedure – User Whitelist Configuration


Assume that the IP address of a server is 192.168.1.1 and the listening port
number is 1888.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs
the GaussDB 100 database.

Step 2 Query for a configured user whitelist.


zsql gaussdba/database_123@127.0.0.1:1888
SELECT * FROM SYS.DV_HBA;

Step 3 Add an HBA entry (TYPE, USER, and ADDRESS) to the zhba.conf file.
cd ${GSDB_DATA}/cfg
vim zhba.conf
host user 127.0.0.1,192.168.3.222,20AB::9217:acff:feab:fcd0/64

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

● ADDRESS lists the IP addresses allowed for database connections. Separate multiple IP
addresses with commas (,). HBA entries are independent from each other and their
order in the whitelist does not affect the whitelist functionality.
● If a username contains special characters such as number sign (#) and tab characters,
enclose the name with double quotation marks (""). In host "#abc" 127.0.0.1 and host
"abc" 127.0.0.1, the strings enclosed in the double quotation marks are usernames.
● If a string is "*" or *, all users will be listed.
● The IP addresses can be IPv4 or IPv6 addresses, or a network segment with the subnet
mask or prefix length specified. All the following formats are valid:
– 192.168.3.222 indicates an IPv4 host.
– 192.168.3.0/24 indicates an IPv4 segment with the specified subnet mask length
24.
– 20AB::9217:acff:feab:fcd0 indicates an IPv6 host.
– 20AB::9217:acff:feab:fcd0/64 indicates an IPv6 segment with the specified subnet
prefix length 64.
● When editing the zhba.conf file, do not press Tab to enter a space. Otherwise, the error
message "GS-00220, hba line(20) format is not correct" will be displayed when you load
the user whitelist online.

Step 4 Load the user whitelist online.


1. Use zsql to connect to the database.
zsql gaussdba/database_123@127.0.0.1:1888

2. Run the following statement to load the user whitelist online. The whitelist
takes effect immediately after the statement is executed.
ALTER SYSTEM RELOAD HBA CONFIG;

3. Query the DV_HBA view to check whether the user whitelist is configured
successfully.
SELECT * FROM SYS.DV_HBA;

----End

Procedure – IP Address Whitelist and Blacklist Configuration


Assume that the IP address of a server is 192.168.1.1 and the listening port
number is 1888. Configure 192.168.2.* as whitelisted IP addresses and 192.168.10.*
and 192.168.2.225 as blacklisted IP addresses.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs
the GaussDB 100 database.
Step 2 Query for a configured IP address whitelist and a configured IP address blacklist.
zsql gaussdba/database_123@127.0.0.1:1888
SELECT VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_INVITED_NODES';
SELECT VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_EXCLUDED_NODES';

Step 3 Configure the IP address whitelist or blacklist online. The configuration takes
effect immediately, and you do not need to restart the database.

The IP addresses specified by TCP_INVITED_NODES cannot exceed 1024 bytes. Otherwise,


an error will be reported.

● Configure the IP address whitelist.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

ALTER SYSTEM SET TCP_INVITED_NODES = '(127.0.0.1,192.168.1.1, 192.168.2.*)';

● Configure the IP address blacklist.


ALTER SYSTEM SET TCP_EXCLUDED_NODES = '(192.168.10.*, 192.168.2.225)';

Step 4 Enable IP address whitelist checking online. The function takes effect immediately,
and you do not need to restart the database.
ALTER SYSTEM SET TCP_VALID_NODE_CHECKING = true;

Run the following command to check whether the function takes effect:
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_VALID_NODE_CHECKING';
NAME VALUE
---------------------------------------------------------------- --------------------
TCP_VALID_NODE_CHECKING TRUE

----End

3.2 Managing Users and Their Permissions


Role-based access is implemented in GaussDB 100 to simplify user permission
management and improve database security.

3.2.1 Users and Roles


In service design, roles are used to manage permissions and users are used to log
in to or access databases.

Database Permissions
● System permissions
With system permissions, users can create, modify, delete, and query database
objects, log in to a database, and grant permissions to other users.
For details about system permissions, see the system permission matrix table
in SQL Syntax Reference > SQL Syntax > GRANT in GaussDB 100
V300R001C00 R&D Documentation (Standalone).
By default, only database administrators (DBA) have the system permissions.
They can run the GRANT or REVOKE statement to grant system permissions
to or revoke system permissions from other users. If ADMIN OPTION is
contained in the GRANT statement for granting a permission to a user, the
user can grant this permission to other users.
For security purposes, grant system permissions only to reliable users.
● Object permissions
With object permissions, users can perform corresponding operations, such as
SELECT, INSERT, UPDATE, DELETE, EXECUTE, DROP, LOCK, TRUNCATE, and
ALTER on database objects.
Only object owners, database administrators, and authorized users with
GRANT OPTION can run the GRANT or REVOKE statement to grant or
revoke object permissions.
For details about object permissions, see the system permission matrix table
in SQL Syntax Reference > SQL Syntax > GRANT in GaussDB 100
V300R001C00 R&D Documentation (Standalone).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Database Roles
A role is a collection of users with the same database permissions. GaussDB 100
has the following preset roles:
● DBA
Database administrator role, who has all system permissions. You are advised
not to grant the DBA role to other users.
● RESOURCE
Base object creation role, who has permissions for CREATE PROCEDURE,
CREATE SEQUENCE, CREATE TABLE, and CREATE TRIGGER.
● CONNECT
Connection role, who has the permission for CREATE SESSION.
● STATISTICS
Has the permission to create, delete, and view WSR snapshots, and the
permission to generate WSR reports.

Suggestions on Permission Planning


GaussDB 100 users can be classified by permission into the following three types.
To ensure system security, grant permissions to database users based on the
following principles and service conditions:
● Database administrators
A database administrator has the highest-level database permissions, that is,
has all system and object permissions.
Grant database administrator permissions only when necessary.
● Security administrators
A security administrator has the CREATE USER and DROP USER permissions.
You are advised to specify only one security administrator.
● Common users
By default, a common user has only the permissions of user PUBLIC. Other
permissions need to be granted using the GRANT statement as a database
administrator.
Create different object operators based on service scopes to ensure minimum
user permissions.

3.2.2 User List


In service design, users are used to log in to and access the database. This section
describes users provided by GaussDB 100. System administrators should change
their passwords periodically. The default passwords are not recommended.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Table 3-1 Users provided by GaussDB 100


Type Username Initial Password Description

GaussDB 100 SYS Changeme_123 When GaussDB


database 100 is installed or
administrator initialized, a
default database
administrator SYS
is automatically
generated for
creating database
instances. User
SYS is a database
administrator
with the highest
permissions. Its
initial password is
Changeme_123.
After logging in to
the database for
the first time,
change the initial
password
immediately. For
details about how
to change the
initial password,
see Step 9 in
"Installation and
Deployment >
Installation
Preparation >
Standalone
Installation
(Simple Mode)" in
GaussDB 100
V300R001C00
User Guide
(Standalone).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Type Username Initial Password Description

Public user preset PUBLIC / A preset, public


in GaussDB 100 user of the system
and cannot be
used to log in to
the database. It
indicates the
collection of all
database users. If
a permission is
granted to user
PUBLIC, all
database users
will have this
permission. To
ensure database
security, do not
grant object
permissions to
user PUBLIC.

LREP/usrSample lrep User-defined LREP and


usrSample are
internal users
used by the
logical replication
tool. They are
created only when
the logical
replication tool is
enabled. For
details about their
permissions, see
"Minimum
permissions for
logical replication
users" in "Routine
O&M
Management >
HA Maintenance
> Logical
Replication" in
GaussDB 100
V300R001C00
User Guide
(Standalone).

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

3.2.3 Viewing Users


After GaussDB 100 is installed, a database administrator SYS will be automatically
generated. The default password for the administrator is Changeme_123, and the
password needs to be modified in time.

Procedure
Step 1 View all users.
SELECT * FROM DB_USERS;

Step 2 Change a user password.


ALTER USER gaussdba IDENTIFIED BY new_password REPLACE old_password;

The new password must meet the following password security requirements:

● Contain 8 to 64 characters.
● Start with a letter, number sign (#), or an underscore (_) if the password is
not enclosed in single quotation marks ('').
● Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
● Contain only the following four character types and at least three of them:
– Digits
– Lowercase letters
– Uppercase letters
– Spaces or special characters (For details about the list of special
characters supported by GaussDB 100, see the table below.)
● Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
● If the password contains the special character $, use the escape character \
when connecting to the database through zsql. Otherwise, the login will fail.

NOTICE

● You are advised to change the initial user password.


● The database does not display the plaintext passwords of users. Therefore,
make a note of the default usernames and passwords.

Table 3-2 Special characters

ID Chara ID Charac ID Charac ID Cha


cter ter ter ract
er

1 ` 9 & 17 \ 25 '

2 ~ 10 * 18 | 26 "

3 ! 11 ( 19 [ 27 ,

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

ID Chara ID Charac ID Charac ID Cha


cter ter ter ract
er

4 @ 12 ) 20 { 28 <

5 # 13 - 21 } 29 .

6 $ 14 _ 22 ] 30 >

7 % 15 = 23 ; 31 /

8 ^ 16 + 24 : 32 ?

----End

3.2.4 Managing User Permissions


A database may be accessed by multiple users. To ensure database security and
simplify permission management, you can define roles with different permissions.
Then, grant a role to a user based on levels of user permissions. In this way, the
user has all the permissions of this role, that is, the required permissions are
granted in batches to the user.

3.2.4.1 Creating a User and Granting Permissions

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.
Step 2 Create a user.
CREATE USER jessica IDENTIFIED BY database_123;

The username must meet the following requirements:


● A user name cannot contain spaces or the following special characters:
semicolon (;), vertical line (|), backquote (`), dollar sign ($), bit operator (&),
greater than (>), less than (<), double quotation mark ("), single quotation
mark ('), and exclamation point (!), space, and copyright symbol (©). In
addition, enclosing them in double quotation marks or backquotes is also
forbidden.
● If a user name contains special characters other than the preceding special
characters, enclose the name with double quotation marks ("") or backquotes
(``).
● Since SYSDBA and CLSMGR are database keywords, users with these names
cannot log in to the database. Such users are not recommended.
The password must comply with the following requirements:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

● Contain 8 to 64 characters.
● Start with a letter, number sign (#), or an underscore (_) if the password is
not enclosed in single quotation marks ('').
● Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
● Contain only the following four character types and at least three of them:
– Digits
– Lowercase letters
– Uppercase letters
– Spaces or special characters (For details about the list of special
characters supported by GaussDB 100, see the table below.)
● Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
● If the password contains the special character $, use the escape character \
when connecting to the database through zsql. Otherwise, the login will fail.

Table 3-3 Special characters


ID Chara ID Charac ID Charac ID Charact
cter ter ter er

1 ` 9 & 17 \ 25 "

2 ~ 10 * 18 | 26 ,

3 ! 11 ( 19 [ 27 <

4 @ 12 ) 20 { 28 .

5 # 13 - 21 } 29 >

6 $ 14 _ 22 ] 30 /

7 % 15 = 23 : 31 ?

8 ^ 16 + 24 ' - -

Step 3 Grant system permissions to the user.


GRANT CREATE SESSION TO Jessica;

For details about user permissions, see SQL Syntax Reference > SQL Syntax >
GRANT in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

----End

Examples
● Create a security administrator Tom, and grant the CREATE USER permission
to the administrator.
CREATE USER Tom IDENTIFIED BY '1234@abc';
GRANT CREATE USER TO Tom;
● Create a role role_r that has permission to query the films table, create a
user user_read, and grant role_r to user_read.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

-- Create the films table:


CREATE TABLE films(
id NUMBER(6) not null,
ADDRESS VARCHAR(40),
CITY VARCHAR(64)
);
-- Create the role_r role:
CREATE ROLE role_r;
-- Grant the query permission for films to role_r:
GRANT SELECT ON films TO role_r;
-- Create an object operator user_read:
CREATE USER user_read IDENTIFIED BY '1234@abc';
-- Grant the role to the object operator user_read:
GRANT ROLE_R TO user_read;

3.2.4.2 Viewing Permissions of a User or Role

Prerequisites
● You have read through Users and Roles.
● The user or role to be viewed exists.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.

Step 2 View all users.


SELECT * FROM SYS.DB_USERS;

Step 3 View the system permissions of a user.

For example, to view the system permissions of user joe, run the following
command:
SELECT * FROM ADM_SYS_PRIVS WHERE GRANTEE ='JOE';

GRANTEE PRIVILEGE ADMIN_OPTION


--------------------------------------- ---------------------------- ------------
JOE CREATE SESSION NO
JOE UPDATE ANY TABLE NO
JOE INSERT ANY TABLE NO
JOE DELETE ANY TABLE NO

4 rows fetched.

----End

3.2.4.3 Modifying a User and Its Permissions

Prerequisites
● You have read through Users and Roles.
● The user to be modified exists.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.

Step 2 Modify system permissions of the user.

You can run the GRANT or REVOKE statement to grant or revoke user
permissions.

● Grant permissions.
GRANT CREATE SESSION TO joe;

● Revoke permissions.
REVOKE CREATE SESSION FROM joe;

For details about the permissions, see SQL Syntax Reference > SQL Syntax >
GRANT in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

Step 3 Change the user password.


ALTER USER gaussdba IDENTIFIED BY new_password REPLACE old_password;

The new password must meet the following password security requirements:

● Contain 8 to 64 characters.
● Start with a letter, number sign (#), or an underscore (_) if the password is
not enclosed in single quotation marks ('').
● Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
● Contain only the following four character types and at least three of them:
– Digits
– Lowercase letters
– Uppercase letters
– Spaces or special characters (For details about the list of special
characters supported by GaussDB 100, see the table below.)
● Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
● If the password contains the special character $, use the escape character \
when connecting to the database through zsql. Otherwise, the login will fail.

NOTICE

● You are advised to change the initial user password.


● The database does not display the plaintext passwords of users. Therefore,
make a note of the default usernames and passwords.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Table 3-4 Special characters

ID Chara ID Charac ID Charac ID Charact


cter ter ter er

1 ` 9 & 17 \ 25 "

2 ~ 10 * 18 | 26 ,

3 ! 11 ( 19 [ 27 <

4 @ 12 ) 20 { 28 .

5 # 13 - 21 } 29 >

6 $ 14 _ 22 ] 30 /

7 % 15 = 23 : 31 ?

8 ^ 16 + 24 ' - -

----End

3.2.4.4 Deleting a User

Prerequisites
The user to be deleted exists.

Related Concepts
● When running DROP USER to delete a user, you must use CASCADE to delete
the referenced objects (excluding databases) of the user. The locked
referenced objects of a user cannot be deleted until they are unlocked or the
processes that lock them are killed.
● When DROP USER is used to delete a user, the user database will not be
deleted.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.

Step 2 Delete a user.

Run the following statement to delete user joe:


DROP USER joe CASCADE;

----End

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

3.3 Configuring Password Security Policies


For data security purposes, GaussDB 100 provides comprehensive password
security policies. Password security policies include password complexity, password
reuse, password validity period, password change, and password verification.

Password Complexity
You need to specify a password when creating a database, creating a user, or
modifying a user. The password complexity must meet requirements. Otherwise,
you will be prompted to enter the password again. The password complexity must
meet the following requirements:

● Contain 8 to 64 characters.
● Start with a letter, number sign (#), or an underscore (_) if the password is
not enclosed in single quotation marks ('').
● Cannot be the same as the username or the username spelled backwards
(case-insensitive in verification).
● Contain only the following four character types and at least three of them:
– Digits
– Lowercase letters
– Uppercase letters
– Spaces or special characters (For details about the list of special
characters supported by GaussDB 100, see the table below.)
● Enclose spaces and special characters excluding _#$ with single quotation
marks ('').
● If the password contains the special character $, use the escape character \
when connecting to the database through zsql. Otherwise, the login will fail.

Table 3-5 Special characters

ID Chara ID Charac ID Charac ID Charact


cter ter ter er

1 ` 9 & 17 \ 25 "

2 ~ 10 * 18 | 26 ,

3 ! 11 ( 19 [ 27 <

4 @ 12 ) 20 { 28 .

5 # 13 - 21 } 29 >

6 $ 14 _ 22 ] 30 /

7 % 15 = 23 : 31 ?

8 ^ 16 + 24 ' - -

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Password Reuse
A password can be reused only when it meets the requirements of reuse days
(PASSWORD_REUSE_TIME) and reuse times (PASSWORD_REUSE_MAX).

Large values of the two parameters bring higher security. However, if the values of the
parameters are set too large, inconvenience may occur. The default values of the two
parameters meet the security requirements. You can change the parameter values as
needed for higher security.
● PASSWORD_REUSE_TIME
Specifies the number of days during which a password cannot be reused.
The value is a positive number. The integral part indicates the number of days
and its decimal part can be converted into hours, minutes, and seconds.
If the parameter value is changed to a smaller one, new passwords will be
checked based on the new parameter value.
If the parameter value is changed to a larger one (for example, changed from
a to b), the historical passwords before b days probably can be reused
because these historical passwords may have been deleted. New passwords
will be checked based on the new parameter value. The absolute time is used.
Historical passwords are recorded using absolute time and do not recognize
time changes.
● PASSWORD_REUSE_MAX
Specifies the number of password changes required before the current
password can be reused. If the parameter value is changed to a smaller one,
new passwords will be checked based on the new parameter value. If the
parameter value is changed to a larger one (for example, changed from a to
b), the historical passwords before the last b passwords probably can be
reused because these historical passwords may have been deleted. New
passwords will be checked based on the new parameter value.
PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME must be set in
conjunction with each other.
Set the two parameters as follows:
– If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to
UNLIMITED. The password can be reused without any restrictions.
– If PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME are set to
specified values, the password can be reused only when the conditions
specified by both the parameters are met.
– If either of PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME is
set to a specified value and the other is set to UNLIMITED, the password
cannot be reused. The value is a positive integer.
For example, run the following commands:
-- View the configured PASSWORD_REUSE_TIME:
SELECT * FROM ADM_PROFILES WHERE RESOURCE_NAME = 'PASSWORD_REUSE_TIME';
-- Change the value of PASSWORD_REUSE_TIME to 60:
ALTER PROFILE DEFAULT LIMIT PASSWORD_REUSE_TIME 60;
-- View the configured PASSWORD_REUSE_MAX:
SELECT * FROM ADM_PROFILES WHERE RESOURCE_NAME='PASSWORD_REUSE_MAX';
-- Change the value of PASSWORD_REUSE_MAX to 3:
ALTER PROFILE DEFAULT LIMIT PASSWORD_REUSE_MAX 3;

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Password Validity Period


For example, run the following commands:
-- Check the PASSWORD_LIFE_TIME parameter:
SELECT * FROM ADM_PROFILES WHERE RESOURCE_NAME ='PASSWORD_LIFE_TIME';
-- Change the value of PASSWORD_LIFE_TIME to 90:
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME 90;

● PASSWORD_LIFE_TIME
Specifies the maximum number of days that a password can be used.
Default value: 180

Password Change
During database creation, the database administrator SYS is created. The
password of SYS needs to be periodically changed for account security. It is
recommended that the database administrators and common users periodically
change their own passwords to prevent password leakage. Database
administrators can change their own and common users' passwords. If common
users forget their passwords, they can ask the administrators to change their
passwords.
● A database administrator cannot change the password of another
administrator.
● A database administrator can change the password of a common user
without being required to provide the common user's old password.
● A database administrator can change its own password but is required to
provide the old password.
For example, to change the password of user Tom, run the following command:
ALTER USER Tom IDENTIFIED BY '1234@abc' REPLACE '5678@def';

1234@abc and 5678@def are the new password and old password of user Tom,
respectively. The new password must comply with the complexity requirements.
Otherwise, the password change will fail.

3.4 Configuring Account Security Policies


For data security purposes, GaussDB 100 provides a series of security measures,
such as automatically locking and unlocking accounts, manually locking and
unlocking abnormal accounts, and deleting accounts that are no longer used.
Security policies of an account are configured by setting parameters in the profile
associated with the account. Each account has an associated profile specified
during account creation. If no profile is specified, the default profile (DEFAULT)
will be used. You can change the parameter values in associated profiles to
configure account security policies.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Automatically Locking and Unlocking Accounts

NOTICE

The default values of the FAILED_LOGIN_ATTEMPTS and


PASSWORD_LOCK_TIME parameters comply with security standards. You can set
the parameters as required to improve the security level, but do not set them to 0.
You are advised to retain the default values.

● If the number of incorrect password attempts (FAILED_LOGIN_ATTEMPTS)


reaches the upper limit (default value: 10), the system automatically will lock
the account for security protection. A smaller parameter value brings higher
account security. However, if the value of this parameter is set too small,
inconvenience may occur.
● If the time during which a user is locked exceeds the preset value
(PASSWORD_LOCK_TIME) (default value: one day), the system will
automatically unlock the user. A larger parameter value brings higher account
security. However, if the value of this parameter is set too large,
inconvenience may occur. The integral part of the PASSWORD_LOCK_TIME
value indicates the number of days and its decimal part can be converted into
hours, minutes, and seconds.
● For example, run the following commands:
-- View the profile associated with the user and parameter settings in it:
SELECT * FROM ADM_PROFILES;
PROFILE RESOURCE_NAME RESOURCE_TYPE
THRESHOLD
---------------------- --------------------------------- -------------
----------------------------------------------------
DEFAULT SESSIONS_PER_USER KERNEL
UNLIMITED
DEFAULT FAILED_LOGIN_ATTEMPTS PASSWORD
10
DEFAULT PASSWORD_LIFE_TIME PASSWORD
180
DEFAULT PASSWORD_REUSE_TIME PASSWORD
UNLIMITED
DEFAULT PASSWORD_REUSE_MAX PASSWORD
UNLIMITED
DEFAULT PASSWORD_LOCK_TIME PASSWORD
1
DEFAULT PASSWORD_GRACE_TIME PASSWORD
7
7 rows fetched.
-- Change the value of FAILED_LOGIN_ATTEMPTS to 10:
ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS 10;

Manually Locking and Unlocking Accounts


Once detecting that an account is stolen or the account is used to access the
database without being authorized, administrators can manually lock the account.
Administrators can manually unlock the account if the account becomes normal
again.
For example, if you want to manually lock and unlock user Tom, run the following
statements:
● To manually lock the account:

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

ALTER USER Tom ACCOUNT LOCK;

● To manually unlock the account:


ALTER USER Tom ACCOUNT UNLOCK;

Deleting Accounts That Are No Longer Used


Administrators can delete an account that is no longer used. Deleted accounts
cannot be restored.
For example, if you want to delete user Tom, run the following statement:
DROP USER Tom CASCADE;

Active users cannot be deleted. You need to disconnect their sessions before deleting them.
When a user is deleted with CASCADE is use, all the objects belonging to the user are
deleted.

3.5 Configuring Database Audit Policies


For database security, certain operations of database users need to be audited.
GaussDB 100 allows you to audit specified users' certain operations, including
creation, login, authorization, and such operations as CREATE, UPDATE, and
DROP performed on database objects.

3.5.1 Audit Overview


Database security is essential for a database system. GaussDB 100 writes all user
operations in the database into audit logs. Database security administrators can
use the audit logs to reproduce a series of events that cause faults in the database
and identify unauthorized users, unauthorized operations, and the time when
these operations are performed.
The switch of each audit item supports dynamic loading. After changing the
switch status of an audit item when the database is running, the modification
takes effect immediately and you do not need to restart the database.

Table 3-6 Configuring audit items


Configuration Description
Item

AUDIT_LEVEL Parameter: AUDIT_LEVEL


Switch of auditing, which specifies the audit logging level.
The default value is 3, indicating that the audit for DDL
and DCL operations is enabled.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Configuration Description
Item

_AUDIT_MAX_FILE_ Parameter: _AUDIT_MAX_FILE_SIZE


SIZE Maximum size of a single log file. The default unit is byte
and the default value is 10M. For example, if
_AUDIT_MAX_FILE_SIZE is 1M, the maximum size of a log
file will be 1 MB. The value cannot exceed 4G.
You can run the ALTER SYSTEM SET statement to change
the value of _AUDIT_MAX_FILE_SIZE in real time. The
change takes effect immediately after the statement is
executed (the change does not take effect for existing
files).

_AUDIT_BACKUP_F Parameter: _AUDIT_BACKUP_FILE_COUNT


ILE_COUNT Maximum number of backup log files. The default value is
10 and maximum value is 128. If the size of a log file
reaches the value specified by _AUDIT_MAX_FILE_SIZE,
the file will be backed up. If the log file name is
zengine.aud, the backup log file will be named
zengine_yyyymmddhhmissfff.aud. If the number of
backup files reaches the value specified by
_AUDIT_BACKUP_FILE_COUNT, the earliest log files will
be deleted until the number of backup files is equal to the
value of _AUDIT_BACKUP_FILE_COUNT.

_LOG_FILE_PERMIS Parameter: _LOG_FILE_PERMISSIONS


SIONS Log file permission. The default value is 600. The write
permission for backup log files is automatically removed
from all users, including the owners, groups, and others.
You can run the ALTER SYSTEM SET statement to change
the value of _LOG_FILE_PERMISSIONS in real time. The
change takes effect immediately after the statement is
executed (the change does not take effect for existing
files).

_LOG_PATH_PERMI Parameter: _LOG_PATH_PERMISSIONS


SSIONS Log directory permission. The default value is 700. The
parameter setting takes effect for the run, debug, and
audit log directories and their parent directories, as well as
the alarm log directories.
You can run the ALTER SYSTEM SET statement to change
the value of _LOG_PATH_PERMISSIONS in real time.
When you back up or create a log file, the directory
permission is the value of _LOG_PATH_PERMISSIONS.

3.5.2 Configuring Database Audit


The default parameter value of each audit item meets security standards. You can
enable audit functions as needed, but system performance may be affected.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.
Step 2 Check the audit logging level.
SELECT * FROM SYS.DV_PARAMETERS WHERE NAME='AUDIT_LEVEL';

Step 3 Set the content to be written into audit logs.


To run the following statement, you must have the permission to do ALTER
SYSTEM.
ALTER SYSTEM SET AUDIT_LEVEL=7;

Table 3-7 lists the audit objects and the corresponding open flags. To audit
multiple objects, set AUDIT_LEVEL to a sum. For example, if DDL, DCL, and DML
operations need to be audited at the same time, set AUDIT_LEVEL to 7.

Table 3-7 Settings of AUDIT_LEVEL for audit logs

Log Type Decimal Value Binary Value

DDL 1 00000001

DCL 2 00000010

DML 4 00000100

PL 8 00001000

ALL 255 11111111

● When the value of AUDIT_LEVEL is 0, audit logging is disabled.


● When the value of AUDIT_LEVEL is greater than 0, it needs to be converted into a
binary value, with the last four bits in use. If the most significant bits are insufficient,
the value will be left padded with 0. From the most significant bit to the least significant
bit, each bit represents PL, DML, DCL, and DDL, respectively. Bit 1 indicates on, and bit 0
indicates off.
For example, if the parameter is set to 16, its binary value will be 10000. The last four
bits are 0000, indicating that PL, DML, DCL, and DDL audit logs are all disabled. In this
case, the PL, DML, DCL, and DDL audit logs are not recorded, but login requests, logout
requests, cancellation requests, and FREE statements are recorded.
● For details about the AUDIT_LEVEL parameter, see "Parameters" in GaussDB 100
V300R001C00 Database Reference (Standalone).

The change to the audit logging level takes effect immediately after the statement
is executed and you do not need to restart the database.

----End

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

3.5.3 Viewing Audit Results


Scenario
If a system failure or exception occurs, you can use audit logs to trace key system
operations, quickly locate the fault cause, and rectify the fault in a timely manner,
ensuring normal database running.

Prerequisites
● Audit has been enabled.
● GaussDB 100 is running properly and operations such as addition,
modification, deletion, and queries have been performed in the database.
Otherwise, no audit results will be available.

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs
the GaussDB 100 database.
Step 2 Go to the audit log directory.
cd $GSDB_DATA/log/audit

Step 3 View audit logs.


cat zengine.aud

----End

3.5.4 Maintaining Audit Logs


Scenario
After audit is enabled, a large number of audit logs are generated, occupying large
storage space. You can customize an audit log maintenance policy based on the
size of available storage space.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/gaussdb_123@192.168.0.1:1888

gaussdba/gaussdb_123 indicates the database administrator created after the


installation and the modified administrator password. 192.168.0.1 indicates the IP
address of the database server. 1888 indicates the connected port.
Step 2 Configure the automatic deletion of audit logs.
If the storage space occupied by an audit file or the number of audit files exceeds
the upper limit, the system will automatically delete the earliest audit files and
record deletion information to the run logs. By default, the maximum storage
space that can be occupied by a single audit file is 10 MB. Users can change the
value based on the disk size. The number of audit files is specified by the
_AUDIT_BACKUP_FILE_COUNT parameter. The value range is [0, 128], and the

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

default value is 10. Users can increase the value as required, but the performance
will be affected.

● Run the following commands to set the disk space for each audit file:
-- View the currently configured space:
SELECT NAME, VALUE FROM SYS.DV_PARAMETERS WHERE NAME='_AUDIT_MAX_FILE_SIZE';
NAME VALUE
------------------------------ ----------------------------------------------------------------
_AUDIT_MAX_FILE_SIZE 1M
1 rows fetched.
-- Change the value of _AUDIT_MAX_FILE_SIZE to 10M:
ALTER SYSTEM SET _AUDIT_MAX_FILE_SIZE=10M;

● Run the following commands to set the maximum number of audit files:
-- View the currently configured number:
SELECT NAME, VALUE FROM SYS.DV_PARAMETERS WHERE NAME='_AUDIT_BACKUP_FILE_COUNT';

NAME VALUE
------------------------------ ----------------------------------------------------------------
_AUDIT_BACKUP_FILE_COUNT 2
1 rows fetched.
-- Change the value of _AUDIT_BACKUP_FILE_COUNT to 5:
ALTER SYSTEM SET _AUDIT_BACKUP_FILE_COUNT=5;

----End

3.6 Configuring File Permission Security Policies


GaussDB 100 adopts permission management rules for directories and files to
ensure their security in daily operations.

Related Concepts
When being installed, GaussDB 100 automatically configures the permissions for
its files, including files (such as log files) generated during the running process.
File permissions are configured as follows:

● The permission for program directories in the database is set to 0700.


● The permission for data file directories in the database is set to 0700.
● The permission for data files and audit logs of the database, as well as data
files generated by other database programs, is set to 0600. The permission for
run logs is no higher than 0640 by default.
● Common OS users are not allowed to modify or delete database files and log
files.

Database Directory and File Permissions


Table 3-8 lists permissions for program directories and files after GaussDB 100 is
installed, and Table 3-9 lists permissions for data directories and files.

Table 3-8 Program directory and file permissions

Directory or File Permission Attribute

app 700 Directory

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Directory or File Permission Attribute

app/add-ons 700 Directory

app/admin 700 Directory

app/bin 700 Directory

app/lib 700 Directory

app/admin/script 700 Directory

app/admin/script/ 700 Directory


sql_dialect

app/add-ons/libpcre.so. 500 File


1.2.10

app/add-ons/libuuid.so. 500 File


1.0.0

app/add-ons/libz.so. 500 File


1.2.11

app/add-ons/liblz4.so. 500 File


1.8.3

app/add-ons/libzstd.so. 500 File


1.3.5

app/admin/script/ 400 File


add_standby_log.sample.
sql

app/admin/script/ 400 File


create_database.sample.s
ql

app/admin/script/ 400 File


initdb.sql

app/admin/script/ 400 File


initplsql.sql

app/admin/script/ 400 File


initview.sql

app/admin/script/ 400 File


initwsr.sql

app/admin/script/ 400 File


readme.md

app/admin/script/ 700 Folder


sql_dialect

app/admin/script/ 400 File


sql_dialect/package.xml

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Directory or File Permission Attribute

app/admin/script/ 400 File


sql_dialect/ora-dialect.sql

app/bin/Common.py 500 File

app/bin/Common.pyc 400 File (dynamically


generated during
runtime)

app/bin/GaussLog.py 500 File

app/bin/GaussLog.pyc 400 File (dynamically


generated during
runtime)

app/bin/shutdowndb.sh 500 File

app/bin/sql_process.py 500 File

app/bin/uninstall.py 500 File

app/bin/zctl.py 500 File

app/bin/zencrypt 500 File

app/bin/zengine 500 File

app/bin/zsql 500 File

app/lib/libzeclient.so 500 File

app/lib/libzecommon.so 500 File

app/lib/libzeprotocol.so 500 File

app/package.xml 400 File

Table 3-9 Data file and directory permissions

Directory or File Permission Attribute

data 700 Directory

data/archive_log 700 Directory

data/cfg 700 Directory

data/data 700 Directory

data/dbs 700 Directory

data/log 700 Directory

data/protect 700 Directory

data/trc 700 Directory

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Directory or File Permission Attribute

data/log/audit 700 Directory

data/log/debug 700 Directory (dynamically


generated during
runtime)

data/log/oper 700 Directory

data/log/run 700 Directory

data/archive_log/* 600 File (dynamically


generated during
runtime)

data/cfg/zengine.ini 600 File

data/cfg/zengine.ini_bak 600 File

data/cfg/zhba.conf 600 File

data/data/user* 600 File

data/data/log* 600 File (dynamically


generated during
runtime)

data/data/temp* 600 File

data/data/cntl* 600 File

data/data/undo 600 File

data/data/system 600 File

data/dbs/zenith_key1 600 File

data/dbs/zenith_key2 600 File

data/log/audit/* 600 File (dynamically


generated during
runtime)

data/log/debug/* 600 File (dynamically


generated during
runtime)

data/log/oper/* 600 File (dynamically


generated during
runtime)

data/log/run/* 600 File (dynamically


generated during
runtime)

data/log/ 600 File (dynamically


zenith_alarm.log generated during
runtime)

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Security Maintenance Guide (Standalone) 3 Database Security Maintenance

Directory or File Permission Attribute

data/log/zenithstatus.log 600 File (dynamically


generated during
runtime)

data/log/zctl* 600 File (dynamically


generated during
runtime)

data/protect/workerstore 400 File

data/protect/privilege 400 File

data/protect/factorstore 400 File

data/protect/ 600 File


gsdb_uds_emerg.server

data/trc/* 600 File

Suggestions
When being installed, GaussDB 100 automatically configures the permissions for
its files, including files (such as log files) generated during the running process.
The specified permissions meet requirements in most scenarios. If you have any
special requirements for the related permissions, you are advised to periodically
check the permission settings to ensure that the permissions meet the product
requirements.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Security Maintenance Guide (Standalone) 4 Linux Operating System Security Maintenance

4 Linux Operating System Security


Maintenance

This chapter describes how administrators change the system password and check
system accounts, processes, services, and ports to ensure normal running of the
operating system and database.

4.1 Changing the System Password


The system password is necessary for logging in to the system. Changing the
system password prevents password disclosure.

You are advised to update the password periodically for the privileged user root of
the Linux operating system. A new password must comply with secure password
policies.

The password policies are as follows:

● The password must contain at least eight characters.


● The password must contain three of the following four types: special
characters, digits, lowercase letters, and uppercase letters.
● The password cannot be the same as the username or the username spelled
backwards.
● The password cannot be completely or partially the same as a previously used
password.

4.2 Checking System Accounts


The are many accounts in the operating system and application system.
Periodically checking these accounts can prevent them from being illegally spread
or disclosed, avoiding security risks.

You are advised to quarterly check running accounts in the operating system and
application system to detect unsuitable accounts or account permissions,
periodically update account passwords, and delete unnecessary accounts.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Security Maintenance Guide (Standalone) 4 Linux Operating System Security Maintenance

Step 1 Log in to the server as user root.


Step 2 View group and account information.
● Enter cat /etc/group to view the information about all groups.
● Enter cat /etc/passwd to view the information about all accounts.
Step 3 Delete unnecessary accounts.

----End

4.3 Checking System Processes


While the system is running, many processes are triggered. Unnecessary processes
may mitigate system performance and security. Periodically checking and handling
system processes can prevent security risks.
Administrators need to check for unsuitable processes and promptly handle them
for system security purposes.

Step 1 Log in to the server as user root.


Step 2 Enter ps -ef to check for unsuitable processes of accounts.

----End

4.4 Checking Services and Ports


The system provides a variety of services and ports to facilitate operations.
However, unnecessary services and ports may reduce system security and must be
disabled as soon as possible.
Periodically check for and stop unnecessary services and ports to prevent security
risks.
For details about the services and ports provided by the system, see GaussDB 100
V300R001C00 Communication Matrix (Standalone).
Step 1 Log in to a server as user root.
Step 2 Check services and ports.
● Check TCP services and ports.
netstat -an |grep LISTEN |grep tcp

● Check UDP services and ports.


netstat -an |grep udp

----End

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Security Maintenance Guide (Standalone) 5 Machine-to-Machine Interfaces

5 Machine-to-Machine Interfaces

5.1 Common.py
Description
Common.py is used to check whether directories exist and delete temporary files.
It is a common function library for other tools and cannot be executed
independently.

5.2 Common.pyc
Description
Common.pyc is a bytecode file. Invoking Common.py generates a Common.pyc
file, which cannot be executed independently.

5.3 GaussLog.py
Description
GaussLog.py is used to define log levels, read and write logs, as well as enable
and disable logging. It is a common function library for other tools and cannot be
executed independently.

5.4 GaussLog.pyc
Description
GaussLog.pyc is a bytecode file. Invoking GaussLog.py generates a GaussLog.pyc
file, which cannot be executed independently.

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

6 Interface Mapping (GaussDB 100 Native


Interface Names vs. Mainstream Database
Interface Names)

6.1 Data Dictionary Tables


Table 6-1 Name mapping of data dictionary tables (GaussDB 100 native interface
names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

6.2 DBA Views


Table 6-2 Name mapping of DBA views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

6.3 User Views


Table 6-3 Name mapping of user views (GaussDB 100 native interface names vs.
mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_ARGUMENTS ALL_ARGUMENTS

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

6.4 Dynamic Performance Views


Table 6-4 Name mapping of dynamic performance views (GaussDB 100 native
interface names vs. mainstream database interface names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

GaussDB 100 Native Interface Name Mainstream Database Interface


Name

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100 6 Interface Mapping (GaussDB 100 Native Interface
Security Maintenance Guide (Standalone) Names vs. Mainstream Database Interface Names)

6.5 Configuration Parameters


Table 6-5 Name mapping of configuration parameters (GaussDB 100 native
interface names vs. mainstream database interface names)
GaussDB 100 Native Interface Name Mainstream Database Interface
Name

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 04 (2019-12-28) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
V300R001C00

Troubleshooting Guide (Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
Troubleshooting Guide (Standalone) Contents

Contents

1 About This Document.................................................................................................................. 1


2 Troubleshooting Process.............................................................................................................. 5
3 Fault Demarcation......................................................................................................................... 6
4 Fault Locating................................................................................................................................. 8
4.1 Locating Network Faults................................................................................................................................................ 8
4.2 Locating OS Faults......................................................................................................................................................... 9
4.3 Locating Database Faults..............................................................................................................................................11
4.4 Locating Disk Faults.....................................................................................................................................................12

5 Database Emergency Handling................................................................................................ 14


6 Common Faults............................................................................................................................ 16
6.1 Database Installation Faults..........................................................................................................................................16
6.1.1 Primary and Standby Connection Fails After Installation.........................................................................................16
6.2 Database Operation Faults............................................................................................................................................17
6.2.1 Database Startup Failure............................................................................................................................................17
6.2.1.1 Message "Can not get instance '/date_directory' process pid" Is Displayed...........................................................17
6.2.1.2 Message "Failed to load params instance startup failed." Is Displayed................................................................. 18
6.2.1.3 Message "Error, open Log file failed:backup trace catch an exception." Is Displayed..........................................18
6.2.1.4 Message "WARNING: could not create listen socket for "LOCALHOST" (postmaster.c:1245)." Is Displayed
............................................................................................................................................................................................ 19
6.2.1.5 Message "database directory "/software_package_directory" does not exist." Is Displayed................................. 20
6.2.1.6 Message "Can not get dn '/software_package_directory' process pid." Is Displayed............................................ 20
6.2.1.7 Message "Log replay stopped at 1:2, it did not reach the least recovery point (LRP) 1:3." Is Displayed............. 21
6.2.1.8 Message "invalid log file head checksum" Is Displayed........................................................................................22
6.2.2 Database Stop Failure................................................................................................................................................ 23
6.2.3 Database Down..........................................................................................................................................................24
6.2.3.1 Database Startup Fails Due to the Failure of Residual Transaction Rollback........................................................24
6.2.3.2 Database Stops Due to a Disk Page Fault...............................................................................................................25
6.2.4 Log Problems.............................................................................................................................................................27
6.2.4.1 Archive Log Generation Failure.............................................................................................................................27
6.2.4.2 Audit Log Generation Failure.................................................................................................................................28
6.2.5 Data Backup and Restoration Failures...................................................................................................................... 28

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
Troubleshooting Guide (Standalone) Contents

6.2.5.1 Data Backup Failure............................................................................................................................................... 29


6.2.5.2 Data Restoration Failure......................................................................................................................................... 29
6.2.6 Configuration File Modification Failure................................................................................................................... 30
6.2.7 Database Hangs......................................................................................................................................................... 30
6.3 Primary and Standby Database Failures....................................................................................................................... 31
6.3.1 Standby Database Cannot Connect to the Primary Database.................................................................................... 31
6.3.2 Two Primary Databases Exist....................................................................................................................................32
6.3.3 Standby Database Rebuild.........................................................................................................................................33
6.3.4 Standby Database Rebuild Failure............................................................................................................................ 34
6.3.5 Data Volumes in Primary and Standby Databases Are Different.............................................................................. 35
6.4 Data Loss...................................................................................................................................................................... 36
6.4.1 Table Data Insertion Failure...................................................................................................................................... 36
6.4.2 Tablespace Creation Failure...................................................................................................................................... 37
6.4.3 Table Creation Failure............................................................................................................................................... 37
6.5 Upgrade Tool Faults..................................................................................................................................................... 38
6.5.1 Pre-check Fails During Automatic HA Upgrade.......................................................................................................38

7 Interface Mapping (Basic Packages vs. Compatible Packages).......................................... 40


7.1 Data Dictionary Tables................................................................................................................................................. 40
7.2 DBA Views...................................................................................................................................................................42
7.3 User Views....................................................................................................................................................................44
7.4 Dynamic Performance Views....................................................................................................................................... 47
7.5 Configuration Parameters............................................................................................................................................. 49

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
Troubleshooting Guide (Standalone) 1 About This Document

1 About This Document

Overview
GaussDB 100 is an enterprise-level relational database engine developed by Huawei. It
features high performance, high availability, high scalability, and easy O&M; and can run
stably and efficiently on the x86 open architecture. GaussDB 100 supports SQL standards and
the syntax of mainstream commercial databases, facilitating application development and
migration. Using the secure, reliable storage provided by GaussDB 100 for relational and
structured data, you can develop and manage highly available, high-performance service
applications in finance, telecom, cloud, and industry digitalization fields. The framework of
GaussDB 100 is component-based and can be used for a standalone database or a cluster.
This document applies to the following scenarios:
l The communication with the server is normal. A serious database fault or service
exception occurs. For example:
– Database fault
– OS fault
– Hardware fault
l The communication with the server is abnormal. The server cannot be remotely
connected.
– Network fault
– Other hardware fault
GaussDB 100 software packages are classified into basic and compatible packages. They
differ in the names of various interfaces. A compatible package is used to offer compatibility
with the usage habits of mainstream databases in the industry. The interfaces mentioned in
this document use names from basic packages. If you have installed compatible packages, you
can use either the interface names of basic packages or those of compatible packages by
referring to Interface Mapping (Basic Packages vs. Compatible Packages). For details
about how to install the basic and compatible packages, see "Installation and Deployment" in
GaussDB 100 V300R001C00 User Guide (Standalone).

Intended Audience
The document is intended for GaussDB 100 database administrators and provides guidance
for emergency maintenance and troubleshooting.
The following information is mandatory for a database administrator:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
Troubleshooting Guide (Standalone) 1 About This Document

l Knowledge about a relational database. The theory helps you get familiar with GaussDB
100 and its usage.
l Knowledge about OSs, You will need it when you install, run, and maintain GaussDB
100.

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not avoided, will


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in equipment damage, data loss, performance deterioration, or
unanticipated results.
NOTICE is used to address practices not related to personal injury.

Calls attention to important information, best practices, and tips.


NOTE is used to address information not related to personal injury,
equipment damage, and environment deterioration.

Example Conventions
The following table describes some example information in this document. You can replace
the example information as needed.

Information Description

$GSDB_HOME Environment variable of the GaussDB 100 installation directory


that is automatically written when install.py is used for
installation. Assume that /opt/gaussdb/app is set as the
installation directory.

$GSDB_DATA Environment variable of the GaussDB 100 data directory that is


automatically written when install.py is used for installation.
Assume that /opt/gaussdb/data is set as the data directory.

gaussdba GaussDB 100 administrator manually created after the installation

database_123 Password of the database administrator gaussdba

192.168.0.1 IP address of the GaussDB 100 server

1888 Port number used by GaussDB 100 to listen to client connection


requests

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
Troubleshooting Guide (Standalone) 1 About This Document

Parameters of GaussDB 100 tools are parsed in sequence. If a parameter is specified for
multiple times, the last value takes effect.

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are in


italics.

[] Items (keywords and parameters) in brackets [ ] are optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more options or no
item is selected.

{ x | y | ... } Indicates that one item is selected from two or more options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with commas (,).

Change History
Issue Change Time
Description

03 Added: 2019-06-06
Pre-check Fails
During Automatic
HA Upgrade

02 This issue is the 2019-04-05


second official
release.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
Troubleshooting Guide (Standalone) 1 About This Document

Issue Change Time


Description

01 This issue is the first 2018-10-30


official release.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
Troubleshooting Guide (Standalone) 2 Troubleshooting Process

2 Troubleshooting Process

This section describes the common process for troubleshooting.


Figure 2-1 shows the troubleshooting process.

Figure 2-1 Troubleshooting flowchart

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
Troubleshooting Guide (Standalone) 3 Fault Demarcation

3 Fault Demarcation

When a fault occurs, identify fault location, for example, hardware, network, OS, or database,
and take troubleshooting measures accordingly to restore database services. To locate a fault,
perform the following steps:

Step 1 Log in to the server where GaussDB 100 is deployed using SSH or other remote login tools.

If the OS encounters a kernel panic (an internal fatal error is detected), the system takes about
20 minutes to restart. Try to connect to the server again every 5 minutes. If the connection
fails for 20 minutes, it indicates that the server fails to respond due to a fault or the network
connectivity is abnormal. In this case, contact the administrator for further fault locating on
site.

If the connection fails, follow the instructions provided in Locating Network Faults.

Step 2 Locally log in to a server where GaussDB 100 is deployed as user root.

If you cannot log in to the server, follow the instructions provided in Locating OS Faults.

Step 3 Check whether the GaussDB 100 service is started.


ps ux | grep zengine

If the zengine status is open, mount, or nomount, it indicates that the database service is
started.
gaussdba 14342 2.5 6.8 1059336 510404 ? Sl May21 104:44 /home/
gaussdba/app/bin/zengine open -D /home/gaussdba/data

If the process is not displayed, follow the instructions provided in Locating Database Faults.

Step 4 Check the disk status.

Common disk faults include insufficient disk space, bad blocks of disks, and unmounted
disks.
1. Check whether any unmounted disks exist.
fdisk -l

2. Check whether the disk space is sufficient.


df -h

Ensure that the GaussDB 100 disk space is sufficient.


3. Try to write to the file to determine whether the disk is normal.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
Troubleshooting Guide (Standalone) 3 Fault Demarcation

If the disk has the preceding problems, follow the instructions provided in Locating Disk
Faults.

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

4 Fault Locating

This section describes how to locate faults after determining the fault types by referring to
Fault Demarcation.

4.1 Locating Network Faults


The communications network layer is the basic component of a database. When the database
runs normally, the network layer is transparent to upper-layer users. However, during the
long-term operation of a database cluster, network exceptions or errors may occur.
When the network is faulty, you can run the ifconfig, ping, netstat, and lsof commands to
check whether the network interface card (NIC) is normal.
netstat

If the network is normal, try connecting to the database.


l If a standalone database fails to be connected, check whether the configuration items in
the zenith.ini file are correct based on the error information.
l If the connection between the primary and standby databases fails, see Standby
Database Cannot Connect to the Primary Database.

System Hang Occurs During Database Connection or Query


Handling procedure:

Step 1 Locally log in to a server where GaussDB 100 is deployed as user root.
If you cannot log in to the server, follow the instructions provided in Locating OS Faults.
Step 2 Log in to the GaussDB 100 database.
zsql
conn jack/database_123@192.168.0.1:1888

jack/database_123 indicates the username and password used for logging in to the database.
192.168.0.1 indicates the IP address of the database server. 1888 indicates the connected port.
Step 3 Run the following SQL statement to query running SQL statements:
SELECT SID,SERIAL#, EVENT, PROGRAM, CLIENT_IP, (SYSDATE - SQL_EXEC_START)*86400,
WAIT_SID, CURRENT_SQL,SQL_ID, MODULE FROM DV_SESSIONS WHERE STATUS = 'ACTIVE';

Where,

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

l WAIT_SID indicates the ID of the blocked session. If it is empty, it indicates that no


sessions are blocked.
l (SYSDATE - SQL_EXEC_START)*86400 indicates the elapsed time of the current
SQL statement. The unit is second.
Step 4 Take countermeasures.
l If stopping the blocked session does not affect the normal running of the database, run
the following command to stop it:
ALTER SYSTEM KILL SESSION 'SID,SERIAL#';

l If stopping the blocked session affects the normal running of the database, you are
advised to contact Huawei technical support to confirm whether the session can be
stopped.

----End

4.2 Locating OS Faults


After you log in to the OS, if the system responds slowly during operations, check the running
status of the system and perform subsequent handling procedures, including but are not
limited to collecting system information, and checking the system version, hardware,
parameter settings, and login users.
The machine does not respond to external connections possibly because system resources are
insufficient (for example, CPU or I/O resources are overloaded). In this case, try again. If the
server fails to work for 5 minutes, contact the administrator for further locating on site.

Figure 4-1 OS fault

If the login is successful and the system responds slowly, collect the following information:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

l Online users
-- View online users.
who

l CPU usage
Check whether any processes cause high CPU usage.
top -H

l I/O usage
iostat -x 1 3
Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz
avgqu-sz await r_await w_await svctm %util
xvda 0.01 1.10 0.07 1.01 0.83 10.25
20.40 0.03 24.88 4.04 26.36 1.38 0.15
xvde 0.00 0.39 0.13 1.62 3.47 33.83
42.78 0.03 18.01 4.94 19.05 1.21 0.21
dm-0 0.00 0.00 0.13 2.01 3.47 33.83
34.94 0.03 15.71 4.95 16.40 0.99 0.21
– rrqm/s: number of merge read operations per second, that is, delta(rmerge)/s
– wrqm/s: number of merge write operations per second, that is, delta(wmerge)/s
– r/s: number of read I/O on devices per second, that is, delta(rio)/s
– w/s: number of write I/O on devices per second, that is, delta(wio)/s
– rKB/s: number of Kbytes read per second, which is half of rsec/s because the size
of each sector is 512 bytes
– wKB/s: number of Kbytes written per second, which is half of wsec/s
– avgrq-sz: average size of data (sectors) of each I/O operation performed on a
device, that is, delta(rsect + wsect)/delta(rio + wio)
– avgqu-sz: average I/O queue length, that is, delta(aveq)/s/1000 (the unit of aveq is
ms)
– await: average wait time (in ms) for each I/O operation, that is, delta(ruse + wuse)/
delta(rio + wio)
– svctm: average service time (in ms) for each I/O operation, that is, delta(use)/
delta(rio + wio)
– %util: what percentage of a second is used for I/O operations, or in what
percentage of a second the I/O queue is not empty, that is, delta(usr)/s/1000 (the
unit of usr is ms)
l Memory usage
Use the top command to check which processes occupy more memory than expected.
vmstat 1 3

l OS status
– View system log information (/var/log/messages) or dmesg information as user
root to check whether errors occurred in the OS.
– Run the sysctl –a and cat /etc/sysctl.conf commands as user root to obtain system
parameter information.
– Run uname -a to query system kernel information.
– Run the required command to query the OS version.
n To check the SUSE Linux OS version, run cat /etc/SuSE-release.
n To check the Red Hat version, run cat /etc/redhat-release.
n To check the EulerOS version, run cat /etc/euleros-release.
– Use the cat /proc/cpuinfo and cat /proc/meminfo commands to obtain CPU and
memory information.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

4.3 Locating Database Faults


When a database fault occurs, collect information about logs, views, error codes, and black
boxes (or core files) to analyze the cause of the fault.

Viewing Error Code Information


GaussDB 100 provides various error code display mechanisms, and enriches possible causes
and troubleshooting methods of every error code, helping users quickly and efficiently locate
and rectify the faults they encountered.

For details about error codes, see GaussDB 100 V300R001C00 Error Code Reference.

Locating Faults Based on Logs


During the running of GaussDB 100, a large number of logs are generated, including run,
audit, debug, and alarm logs. If a database is faulty, you can use these logs to locate the fault
and restore the database. For details about the log content, see "Database System Management
> Managing Logs > Viewing Logs" in GaussDB 100 V300R001C00 User Guide (Standalone).

l Run Logs
A run log prints GaussDB 100 running information. When a database is faulty, examine
the zengine.rlog file.
The log directory is $GSDB_DATA/log/run/zengine.rlog by default.
l Debug Logs
A debug log prints debug information during GaussDB 100 running. When a database is
faulty and debug logging has been enabled, examine the zengine.dlog file.
The log directory is $GSDB_DATA/log/debug/zengine.dlog by default.
l Alarm Logs
An alarm log prints alarm information during GaussDB 100 running. For details about
the alarm information, see zenith_alarm.log.
The log directory is $GSDB_DATA/log/zenith_alarm.log.
l zctl Logs
A zctl log prints information about O&M operations performed by zctl.py. To obtain
complete O&M information of GaussDB 100, examine the zctl-yyyy-mm-dd_xxx.log file
and the zenithstatus.log file, which contains output information upon database startup.
The log directory is $GSDB_DATA/log/zctl-yyyy-mm-dd_xxx.log.
l Startup Logs
A startup log records output information upon database startup. For details, see
zenithstatus.log. To obtain complete O&M information of GaussDB 100, examine the
zctl-yyyy-mm-dd_xxx.log file and the zenithstatus.log file, which contains output
information upon database startup.
The log directory is $GSDB_DATA/log/zenithstatus.log.
l Trace Logs
A trace log records the information about database session deadlocks. For details about
session deadlocks, see zengine_03_xxxxxx.trc.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

Checking Information in Views


GaussDB 100 provides a variety of views. When locating a fault, you can check the views as
needed. For example, if the SQL statement does not respond for a long time, you can check
the DV_LOCKED_OBJECTS view.

Locating Faults Based on Core Files


Abnormal termination of a GaussDB 100 process will trigger a core dump. A core dump file
is helpful for determining the position and root cause of abnormal termination. Once a core
dump occurs during process running, collect the core file immediately for further analyzing
and locating the fault.

The OS has a core dump mechanism. If this mechanism is enabled, core files are generated
for each core dump, which has an impact on the OS performance and disk space. GaussDB
100 allows core files to be generated even if the core mechanism is not configured for the OS.
In this way, coredump problem locating does not affect other programs in the OS.

Run the following command to view the location of core files:


cat /proc/sys/kernel/core_pattern

4.4 Locating Disk Faults


Common disk faults include insufficient disk space, bad blocks of disks, and unmounted
disks.

l The disk space is insufficient.


Run the df -h command to check the disk space. If the disk usage is 100% as shown
below, the read and write errors are caused by insufficient disk space:
root:/> df -h
Filesystem Size Used Avail Use% Mounted on
/dev/xvda1 36G 5.9G 28G 18% /
devtmpfs 3.8G 0 3.8G 0% /dev
tmpfs 3.8G 0 3.8G 0% /dev/shm
tmpfs 3.8G 41M 3.7G 2% /run
tmpfs 3.8G 0 3.8G 0% /sys/fs/cgroup
tmpfs 730M 0 730M 0% /run/user/0
/dev/mapper/vg1-lv1 89G 89G 0G 100% /home
tmpfs 730M 0 730M 0% /run/user/1010

If the disk is RAID 5, run the df -h command to check whether the disk space is full.
Actually, the disk space may not be full, but multiple disks in a RAID group may be
faulty, or junk data may exist in the directory. You can use a third-party RAID controller
monitoring tool, such as MegaCLI, to monitor RAID disk faults, or check for and delete
redundant files (such as core files) in the disks.
l Disks have bad blocks. In this case, the OS rejects read and write operations to protect
the file system. You can use the bad block check tool, for example, badblocks, to check
whether bad blocks exist.
root:~ # badblocks /dev/xvda1 -s -v
Checking blocks 0 to 30681000
Checking for bad blocks (read-only test): 306809600674112/ 306810000000
30680964
30680973
...
done
Pass completed, 37 bad blocks found.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
Troubleshooting Guide (Standalone) 4 Fault Locating

l Disks are not mounted and need to be mounted again.


Run the df -h command to view all mounted disks. Run the fdisk -l command to check
all disks and find the unmounted disks. If the nvmeOn1 disk is not mounted, perform the
following operations to mount it:
Create a directory for mounting.
sudo mkdir /data

Mount nvmeOn1 to /data.


sudo mount /dev/nvmeOn1 /data

Check the disk mounting status and mount the unmounted disks. Otherwise, you need to
mount them again after the restart.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
Troubleshooting Guide (Standalone) 5 Database Emergency Handling

5 Database Emergency Handling

Emergency handling is an act of troubleshooting major and urgent accidents that occur during
system or device running, to quickly recover services and minimize loss caused by the
accidents.

For details about how to locate a database fault, see Locating Database Faults.

Guidelines
An emergency refers to a situation where unexpected faults affect a wide range of services or
devices or severely affect the QoS of a database. The emergency plan must be immediately
started if any of the following problems occur.

Table 5-1 Emergency impact

Fault Type Failed Object Impact Level

Database fault Parameter file damage Critical

Control file damage Critical

Key data file damage Critical

Common data file damage Critical

OS fault Insufficient file handles Major

Insufficient memory Major

Hardware fault High CPU usage Major

Insufficient disk space Major

Power failure Major

Network fault Network connection failure Major

Intermittent network Major


interruption

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
Troubleshooting Guide (Standalone) 5 Database Emergency Handling

When a major accident occurs, services must be recovered as soon as possible. Do not blindly
take actions, or the problem impact will become more severe.
The key to improving the efficiency of emergency handling is as follows:
l When there is an emergency fault, maintenance personnel must keep calm and contact
Huawei technical support.
l They should convene onsite maintenance personnel as soon as possible to confirm what
operations have been performed before the fault occurs, including but not limited to:
– Modification to data configurations
– Upgrade
– Network cable removal and insertion

Precautions for Emergency Maintenance


l Routine maintenance: Perform routine inspection and maintenance on the database to
ensure its health and identify risks in a timely manner. For details about routine
inspection and maintenance, see " Routine O&M Management > Routine Maintenance"
in GaussDB 100 V300R001C00 User Guide (Standalone).
l Data preparation: To quickly restore data after data exceptions occur, you need to back
up data regularly. For details about data backup, see "Database System Management >
Backup and Restoration" in GaussDB 100 V300R001C00 User Guide (Standalone).
l Hardware preparation: When locating and rectifying a fault, you may need to remove,
insert, or replace hardware. Therefore, you need to prepare and keep the spare parts
properly.
l Tools: phillips screwdriver, diagonal plier, and ESD wrist strap or ESD gloves

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

6 Common Faults

6.1 Database Installation Faults

6.1.1 Primary and Standby Connection Fails After Installation

Problem
The installation is successful and the parameter settings are correct, but the primary and
standby databases fail to be connected. The error information is as follows:
GS-00326, replica thread closed, replica agent error, remote ip [192.168.0.1] not
configured in archive destination [srv_replica.c:262]

Cause Analysis
The HA primary/standby connection relationship is determined by the link specified by the
ARCHIVE_DEST_N parameter (including the peer IP address and port number). The
initiator uses the parameter to send a connection. After receiving the connection, the receiver
parses the peer IP address and compares it with the peer IP address configured in the local
configuration file. If the two IP addresses are the same, the connection is accepted. Otherwise,
the connection is denied.

In most cases, this check works properly. If multiple NICs exist on the machine where the
connection initiator is located, or if multiple IP addresses are used by a NIC, the source IP
address used by the connection initiator may be different from the IP address configured on
the receiver. As a result, the connection fails, as illustrated in the following figure.

The source IP address used by A to connect to B may be ip2, but the IP address configured in
B is ip1. As a result, A fails to connect to B.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Procedure
Step 1 Log in to a server where GaussDB 100 is deployed as user root.

Step 2 Switch to user gaussdba.


su - gaussdba

Step 3 If multiple NICs exist on the machine, or if multiple IP addresses are used by a NIC,
determine the IP address in use and perform the following operations:
1. Set the LOCAL_HOST attribute of the ARCHIVE_DEST_N parameter in the
$GSDB_DATA/cfg/zengine.ini file of the local machine to the IP address in use.
2. Set the SERVICE IP address of the ARCHIVE_DEST_N parameter in the
$GSDB_DATA/cfg/zengine.ini file of the peer machine to the IP address in use.

----End

6.2 Database Operation Faults

6.2.1 Database Startup Failure

6.2.1.1 Message "Can not get instance '/date_directory' process pid" Is Displayed

Problem
The database cannot be started. The error information is as follows:
Can not get instance '/home/gaussdba/data' process pid.

/home/gaussdba/data is the data directory.

Cause Analysis
The database memory space is insufficient.

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Modify the SGA parameters in the zengine.ini file.
SGA_BUFF_SIZE must meet the following requirements:
114 MB ≤ SGA_BUFF_SIZE < shmmax, where shmmax is the Linux kernel parameter
defining the maximum size of a shared memory segment
SGA_BUFF_SIZE = LOG_BUFFER_SIZE + SHARED_POOL_SIZE +
DATA_BUFFER_SIZE + TEMP_BUFFER_SIZE
Set LOG_BUFFER_SIZE, SHARED_POOL_SIZE, DATA_BUFFER_SIZE, and
TEMP_BUFFER_SIZE as needed by referring to "Parameters" in GaussDB 100
V300R001C00 Database Reference Information (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

-- Check the value of shmmax.


vim /proc/sys/kernel/shmmax
-- Change the values of LOG_BUFFER_SIZE, SHARED_POOL_SIZE, DATA_BUFFER_SIZE, and
TEMP_BUFFER_SIZE in the zengine.ini file.
vim $GSDB_DATA/cfg/zengine.ini

Step 3 Start the database service.


python $GSDB_HOME/bin/zctl.py -t start

----End

6.2.1.2 Message "Failed to load params instance startup failed." Is Displayed

Problem
l The database cannot be started. The error information is as follows:
GS-00201: The parameter name "_LOG_LEVELS" was invalid
Failed to load params
instance startup failed

_LOG_LEVELS is an incorrect parameter name.


l The database cannot be started. The error information is as follows:
GS-00202: The parameter value "DATA_BUFFER_SIZE" was invalid
Failed to load params
instance startup failed

Cause Analysis
The database parameter name or value is incorrect.

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Open the run log file and view the log recorded when the database fails to be started.
If multiple parameter names are incorrect, only the first incorrect parameter name is displayed
in the command output. Therefore, you need to view run logs to find all incorrect parameter
names.
cd $GSDB_DATA/log/run
vim zengine.rlog

Based on the error information, correct the parameter names or values in the zenigne.ini file
by referring to "Parameters" in GaussDB 100 V300R001C00 Database Reference
(Standalone).

----End

6.2.1.3 Message "Error, open Log file failed:backup trace catch an exception." Is
Displayed

Problem
The database cannot be started. The error information is as follows:
Error, open Log file failed:backup trace catch an exception.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Cause Analysis
The redo log file permission is insufficient.

Procedure
Step 1 Go to the redo log directory.
cd $GSDB_DATA/data

Step 2 Assign permissions to all redo log files. The recommended permission is 0600.
chmod 0600 log1 log2 log3 log4 log5 log6

Step 3 Switch to user gaussdba.


su - gaussdba

Step 4 Start the database service.


python $GSDB_HOME/bin/zctl.py -t start

----End

6.2.1.4 Message "WARNING: could not create listen socket for "LOCALHOST"
(postmaster.c:1245)." Is Displayed

Problem
The database cannot be started. The error information is as follows:
HINT: Is another postmaster already running on port 1888? If not, wait a few
seconds and retry.
WARNING: could not create listen socket for "LOCALHOST" (postmaster.c:1245).

Cause Analysis
During the installation, the default listening port number 1888 is used for the database. The
port number has been occupied by another process.

Procedure
Step 1 Check the process that occupies the port number. Assume the process name is a.
netstat - anop | grep 1888

Step 2 Choose either of the following methods based on your service needs:
l Method 1: To start the database service first, forcibly stop the process that occupies port
1888.
a. Run the following command to check the PID that occupies port 1888:
ps -ef | grep a

b. Specify the PID to forcibly stop the process.


kill PID -9

c. Restart the database service.


Log in to the server where GaussDB 100 is deployed as the OS user who
installs the GaussDB 100 database.
cd $GSDB_HOME/bin
-- Start the database service.
python zctl.py -t start

l Method 2: To ensure that other services also run properly, change the listening port of the
database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

a. Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
b. Modify the zengine.ini file to replace the listening port number LSNR_PORT of
the database with an unoccupied port number.
-- Open the zengine.ini file.
vim $GSDB_DATA/cfg/zengine.ini
-- Change the value of LSNR_PORT.
LSNR_PORT = 1887

In HA mode, change the values of LSNR_PORT for both primary and standby
databases.
c. Restart the database service.
-- Start the database service.
python $GSDB_HOME/bin/zctl.py -t start

----End

6.2.1.5 Message "database directory "/software_package_directory" does not


exist." Is Displayed

Problem
The database cannot be started. The error information is as follows:
database directory "/opt/gaussdb/data" does not exist.

/opt/gaussdb/data is the software package directory.

Cause Analysis
The software package directory does not exist. It may have been deleted by mistake.

Procedure
Use the backup file to restore the data folder. The data file may vary according to the version.
If the restoration fails, contact Huawei technical support.

6.2.1.6 Message "Can not get dn '/software_package_directory' process pid." Is


Displayed

Problem
The database cannot be started. The error information is as follows:
Can not get dn '/opt/gaussdba/data' process pid.

Cause Analysis
The OS memory is insufficient.

Procedure
Step 1 Run the top command as user root to check whether the memory is sufficient.
GaussDB 100 requires that the size of each database instance be greater than or equals 8 GB.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

top
top - 19:16:18 up 2 days, 7:58, 3 users, load average: 0.08, 0.06, 0.05
Tasks: 501 total, 1 running, 500 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.1 us, 0.0 sy, 0.0 ni, 99.8 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 7471588 total, 746488 free, 2720100 used, 4005000 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 2691672 avail Mem

Step 2 Run the following command to check the shared memory:


ipcs -a

Step 3 If unreleased shared memory exists, run the following command to release it:
ipcrm -m 32768

32678 is the shared memory segment identified by shmid.


Step 4 Switch to user gaussdba.
su - gaussdba

Step 5 Start the database service.


python $GSDB_HOME/bin/zctl.py -t start

----End

6.2.1.7 Message "Log replay stopped at 1:2, it did not reach the least recovery
point (LRP) 1:3." Is Displayed

Problem
The database fails to be started. The run log records the information about the damaged log
file ("Checksum failed when read data from file").

NOTE

In the "Log replay stopped at 1:2, it did not reach the least recovery point (LRP) 1:3." message, "1:2"
(the actual log point where the replay stops) and "1:3" (the least log point where the replay is expected to
stop) are used as examples. The actual values vary according to the actual situation.
For details about the path of run logs, see "Database System Management > Managing Logs > Viewing
Logs" in GaussDB 100 V300R001C00 User Guide (Standalone).

Cause Analysis
When the database loads log files from disks, an error is reported and the system exits
loading. Possible causes are as follows:
l A silent fault occurs on the disk. As a result, the log file is damaged.
l The write operation is invalid. As a result, the log file is damaged.

Procedure
Step 1 Determine the location where the log is damaged. Open the run log and check the "Checksum
failed when read data from file" log recorded when the database is started. The following is an
example:
[RCY] current lfn 29429779, rcy point lfn 29408078, consistent point 29465711,
lrp point lfn 29465717,Checksum failed when read data from file;

Where,
l current lfn indicates the actual log point for replay.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

l rcy point lfn indicates the log point where the replay starts.
l consistent point indicates the log point that can ensure consistency.
l lrp point lfn indicates the least log point, until which logs must be replayed to ensure
zero data loss in the database.
Step 2 Take countermeasures.
l The replay fails because the redo log is damaged. current lfn (actual replay log point) is
greater than or equals consistent point (consistency log point) and less than lrp point
lfn (LRP point).
In this case, run the following command when the database is in MOUNT state. Some
lost data cannot be restored.
RECOVER DATABASE UNTIL CANCEL;
ALTER DATABASE OPEN RESETLOGS;

l The replay fails because the redo log is damaged. current lfn is less than consistent
point.
In this case, run the following command when the database is in MOUNT state.
However, database exceptions may occur, because data becomes inconsistent after the
database is started. Exercise caution when performing this operation. You are advised to
contact Huawei technical support to confirm whether the operation can be performed.
RECOVER DATABASE UNTIL CANCEL;
ALTER DATABASE OPEN FORCE IGNORE LOGS;

NOTE

To start the database in MOUNT mode, run the following commands:


cd $GSDB_HOME/bin
python zctl.py -t start -m MOUNT

----End

6.2.1.8 Message "invalid log file head checksum" Is Displayed

Problem
The database cannot be started. The "invalid log file head checksum" log is recorded in run
logs.

NOTE

For details about the path of run logs, see "Database System Management > Managing Logs > Viewing
Logs" in GaussDB 100 V300R001C00 User Guide (Standalone).

Cause Analysis
When the database loads log files from disks, an error is reported and the system exits
loading. Possible causes are as follows:
l A silent fault occurs on the disk. As a result, the log file is damaged.
l The write operation is invalid. As a result, the log file is damaged.

Procedure
Step 1 Start the database in MOUNT mode.
cd $GSDB_HOME/bin
python zctl.py -t start -m MOUNT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Step 2 Find the value of FILE_NAME in the "invalid log file head checksum file" log from the run
logs.
Step 3 Check the DV_LOG_FILES view and record the value of STATUS corresponding to the
FILE_NAME in Step 2.
SELECT ID, STATUS , FILE_NAME FROM DV_LOG_FILES;

Step 4 If STATUS is INACTIVE or UNUSED, go to Step 5. If STATUS is of other values, contact


Huawei technical support.
Step 5 Run the following command to fix redo logs:
ALTER DATABASE CLEAR LOGFILE 0;

Step 6 Run the following commands to restart the database:


cd $GSDB_HOME/bin
python zctl.py -t stop
python zctl.py -t start

----End

6.2.2 Database Stop Failure

Problem
If a database process fault occurs or permissions are incorrect, the database cannot be stopped.
The possible error information is as follows:
l The database process status is abnormal. The error information is as follows:
GS-00305, wait for server response timeout.

l The file permission is insufficient. The error information is as follows:


can't open file '/home/gaussdba/app/bin/zctl.py': [Errno 13] Permission
denied.

Cause Analysis
l The database process status is abnormal.
The database process status may be abnormal. You need to stop the abnormal process
and then stop the database.
l The file permission is insufficient.
Check whether the permission for the zctl.py file is sufficient. If not, you cannot run the
zctl.py command to stop the database.

Procedure
l The database process status is abnormal.
a. Log in to a server where GaussDB 100 is deployed as user root.
b. Run the following command to check the process status and record the PID of the
zengine process whose STAT is D:
ps aux

c. Run the following command to stop the faulty process. Assume that the PID of the
process is 324.
kill -9 324

l The file permission is insufficient.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

a. Log in to a server where GaussDB 100 is deployed as user root.


b. Run the following command to check the permission for the zctl.py file. If the
permission is less than 0500, go to 3.
cd $GSDB_HOME/bin
ll

c. Run the following command to change the zctl.py permission to 0500:


chmod 500 zctl.py

d. Switch to user gaussdba.


su - gaussdba

e. Stop the database service.


cd $GSDB_HOME/bin
python zctl.py -t stop

6.2.3 Database Down

6.2.3.1 Database Startup Fails Due to the Failure of Residual Transaction


Rollback

Problem
The database fails to be started. Analysis on run logs finds that the residual transaction fails to
be rolled back.

Cause Analysis
When the database is started, it goes through two important phases: log recovery and residual
transaction rollback. When a residual transaction is rolled back in the database, if the page of
the residual transaction is damaged, the residual transaction fails to be rolled back. As a result,
the database cannot be started. The residual transaction rollback is not controlled by the user.
Therefore, the user cannot choose to skip the damaged residual transaction. In this case, you
can run the COMMIT FORCE command to forcibly commit the residual transaction to start
the database.

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Start the database in MOUNT mode.


cd $GSDB_HOME/bin
python zctl.py -t start -m MOUNT

Step 3 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 4 Switch the database status to RESTRICT.


ALTER DATABASE OPEN RESTRICT;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Step 5 Query to obtain residual transaction information.


SELECT SEG_ID,SLOT,XNUM FROM DV_TRANSACTION;

Step 6 Forcibly commit the residual transaction.


COMMIT FORCE 'SEG_ID.SLOT.XNUM';

The value of SEG_ID.SLOT.XNUM consists of the values of SEG_ID, SLOT, and XNUM.
Ensure the value format is correct.

Step 7 Exit the current connection.


EXIT

Step 8 Restart the database.


python $GSDB_HOME/bin/zctl.py -t stop
python $GSDB_HOME/bin/zctl.py -t start

----End

6.2.3.2 Database Stops Due to a Disk Page Fault

Problem
Symptom 1: A client reports error GS-00880, indicating that pages are damaged. For
example:
GS-00880, Page 3-44 corrupted

Symptom 2: A database stops suddenly, and the run log records "ABORT INFO:page
corrupted". For example:
ERROR>[BUF] ABORT INFO:page corrupted(file 0, page 9632).checksum level 1, page
size 8192,cks 12745,from_disk 1, changed 0

Cause Analysis
If the database detects that the checksum value on a page does not match, the page has been
damaged. If the page damage does not affect the normal running of the database, the client
will return error GS-00880 and print the ID of the damaged page. If the database cannot run
properly due to the page damage, it will stop and record "ABORT INFO:page corrupted" in
the run log. Possible causes are as follows:

l There is a silent disk fault, resulting in the page damage.


l There is an invalid write operation with an unsupported data type, resulting in the page
damage.

Solution 1
If the disk pages of a standalone or HA primary database are faulty and the databases cannot
be started, you can back up files and replay logs to repair the damaged pages.

Prerequisites

l The database contains all redo logs generated from the time when the backup started to
the time when the disk data pages became faulty.
l The ztrst tool package GAUSSDB100-V300R001C00-RESTORE.tar.gz has been
obtained from the GAUSSDB100-V300R001C00-TOOLS.tar.gz package.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

l Environment variables required by ztrst have been configured. For details, see Step 4 in
"Database System Management > Backup and Restoration > Data Restoration Using
ztrst" in GaussDB 100 V300R001C00 User Guide (Standalone).
l There are no tmp_data and export_data directories in the temporary data directory
specified by parameter -D.
l The backup set specified by parameter -B must be valid, and the backup time must be
earlier than the time when bad pages are generated.
l The database version used in file backup must be the same as the tool version.
NOTE

Currently, the following types of pages cannot be restored:


l Data pages of temporary and nologging tablespaces
l Data pages for tablespace description information
l Data pages for database control files

Procedure

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 If the database already stops, start it in MOUNT mode. If the database status is normal, skip
this step.
cd $GSDB_HOME/bin
python zctl.py -t start -m MOUNT

Step 3 Obtain the data file and page sequence numbers of the damaged page.
l If the database status is normal, the numbers can be obtained from the error information
returned by the client. The following error information indicates that the sequence
number of the data file is 3 and that of the page is 44.
GS-00880, Page 3-44 corrupted

l If the database stops due to a disk fault, the numbers can be obtained from the run log.
The following log indicates that the sequence number of the data file is 0 and that of the
page is 9632.
ERROR>[BUF] ABORT INFO:page corrupted(file 0, page 9632).checksum level 1,
page size 8192,cks 12745,from_disk 1, changed 0

Step 4 Run the ztrst tool to repair the damaged disk page.
ztrst Changeme_123:1881 -D /temp -B /data/backup/bak1 -P 3_44 -S 192.168.0.1:1888

The meanings of the parameters are as follows:

l Changeme_123:1881: Changeme_123 indicates the password of the database


administrator SYS, and 1881 indicates the port number of the ztrst tool. This number
must be different from the database port number.
l -D /temp: -D specifies the temporary directory required for the ztrst tool to run. After
the damaged page is repaired, it will also be backed up in the /tmp_data/data folder in
this directory. This helps restore the original page in case of an exception. After page
repair succeeds, you need to manually delete the temporary directory.
l -B /data/backup/bak1: -B specifies the absolute path of the backup set.
l -P 3_44: -P specifies the ID of the page to be repaired. The value format is x_y, where x
indicates the data file sequence number and y indicates the page sequence number.
l -S 192.168.0.1:1888: -S specifies the IP address and port number of the database. It is
used by the ztrst tool to connect to the database instance.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

For details about ztrst parameters, see "Database Management Tools > ztrst" in GaussDB 100
V300R001C00 Operation Guide to Tools (Standalone).

Step 5 After page repair is complete, run the following command to restart the database if it has been
started in MOUNT mode; or skip this step if the database status is OPEN.
cd $GSDB_HOME/bin
python zctl.py -t stop
python zctl.py -t start

----End

Solution 2
In HA scenarios, if the primary database has a damaged page and it does not stop or can be
restarted after a stop, you can use a standby database to automatically repair the page.

Prerequisites

l The primary database is properly connecting to at least one standby database.


l The PAGE_CHECKSUM parameter of the primary database is not set to OFF.

Procedure

Step 1 If the primary database already stops, start it. Otherwise, skip this step.
cd $GSDB_HOME/bin
python zctl.py -t start

Step 2 Set BLOCK_REPAIR_ENABLE to TRUE on the primary database.


ALTER SYSTEM SET BLOCK_REPAIR_ENABLE = TRUE;

Step 3 Re-execute the database service that reports the error. The primary database will automatically
repair the damaged page.
NOTE

The automatic repair function can be enabled only on the primary database. If the primary database does
not receive a correct page from a standby database within the timeout period, it will stop, and the
location and details of the damaged page will be recorded in the run log. In this case, you can use the
backup set to manually repair the page.
You can change the value of BLOCK_REPAIR_TIMEOUT to adjust the timeout period for obtaining
correct pages from a standby node when the automatic data page repair function is enabled on the
primary database. The default timeout period is 60s.

----End

6.2.4 Log Problems

6.2.4.1 Archive Log Generation Failure

Problem
Fail to generate archive logs. The error information is as follows:
LOG: archive command failed with exit code 1
-bash: cd: archive_log/: Permission denied

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Cause Analysis
l Archive logs do not exist. As a result, the archive logs fail to be generated.
l The permission for archive logs is changed and becomes insufficient.
l The directory for storing archive logs is incorrectly modified.

Procedure
l The log file does not exist.
a. Obtain the backup file of the log file and restore the log file.
l The log file permission is insufficient.
a. Log in to a server where GaussDB 100 is deployed as user root.
b. Run the following command to change the permission for the log file.
The log file directory is $GSDB_DATA/archive_log.
-- The permission for the directory is 0700.
chmod 700 $GSDB_DATA/archive_log
-- The permission for the files in the directory is 0600.
chmod 600 $GSDB_DATA/archive_log/*

l The log file directory is incorrectly modified.


a. Correct the log file directory.

6.2.4.2 Audit Log Generation Failure

Problem
Audit logs cannot be generated during database running. The $GSDB_DATA/log/audit file is
empty, but no error message is displayed.

Cause Analysis
l The permission for archive logs is changed and becomes insufficient.
l The directory for storing archive logs is incorrectly modified.

Procedure
l The log file permission is insufficient.
a. Log in to a server where GaussDB 100 is deployed as user root.
b. Run the following command to change the permission for the log file.
The log file directory is $GSDB_DATA/log/audit.
-- The permission for the directory is 0700.
chmod 700 $GSDB_DATA/log/audit
-- The permission for the files in the directory is 0600.
chmod 600 $GSDB_DATA/log/audit/*

l The log file directory is incorrectly modified.


a. Correct the log file directory.

6.2.5 Data Backup and Restoration Failures

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

6.2.5.1 Data Backup Failure

Problem
The data of the primary database fails to be backed up. The error information is as follows:
GS-00719: session killed

Cause Analysis
Switchover is probably being performed on the standby database at the same time. As a result,
the primary database also performs a switchover and its backup fails.

Procedure
Step 1 After the switchover is complete on the standby database, back up data again.

----End

6.2.5.2 Data Restoration Failure

Problem
If data restoration by running the RESTORE command fails, the following error information
is displayed:

l If the log file permission is insufficient, the error information is as follows:


Error, open Log file failed:backup trace catch an exception.

l If the backup file is damaged or lost, the error information is as follows:


GS-00002: Failed to open the file , the error code was 2.

Cause Analysis
During data restoration, the database needs to read log file information and then restore data.
If the permissions for log files are insufficient, data restoration fails.

If the permissions for log files are sufficient and the data restoration still fails, the database
file to be backed up may be damaged or lost. In this case, you need to check the backup
database file information.

Procedure
l The log file permission is insufficient.
a. Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
b. Stop the database service.
python $GSDB_HOME/bin/zctl.py -t stop

c. Log in to a server where GaussDB 100 is deployed as user root.


d. Run the following command to change the permission for the log file to 705 so that
the user who performs the restoration operation has the read permission.
The log file directory is $GSDB_DATA/data.
chmod 705 $GSDB_DATA/data/log*

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

e. Switch to user gaussdba.


su - gaussdba

f. Run the following command to start the database service:


python $GSDB_HOME/bin/zctl.py -t start

l The backup file is damaged or lost.


Obtain the correct backup file and restore the data again.

6.2.6 Configuration File Modification Failure

Problem
Fail to modify the zengine.ini configuration file. The error information is as follows:
could not open configuration file "/home/gaussdba/data/cfg/zengine.ini":"No such
file or directory"

Cause Analysis
The configuration file fails to be modified because it is damaged or does not exist.

Procedure
Step 1 Obtain the backup file of the configuration file and restore the configuration file.

----End

6.2.7 Database Hangs

Problem
The database hangs during connection or query.

Procedure
Step 1 Locally log in to a server where GaussDB 100 is deployed as user root.

If you cannot log in to the server, follow the instructions provided in Locating OS Faults.

Step 2 Run the following SQL statement to query running SQL statements:
SELECT SID,SERIAL#, EVENT, PROGRAM, CLIENT_IP, (SYSDATE - SQL_EXEC_START)*86400,
WAIT_SID, CURRENT_SQL,SQL_ID, MODULE FROM DV_SESSIONS WHERE STATUS = 'ACTIVE';

Where,

l WAIT_SID indicates the ID of the blocked session. If it is empty, it indicates that no


sessions are blocked.
l (SYSDATE - SQL_EXEC_START)*86400 indicates the elapsed time of the current
SQL statement. The unit is second.

Step 3 Take countermeasures.


l If stopping the blocked session does not affect the normal running of the database, run
the following command to stop it:
ALTER SYSTEM KILL SESSION 'SID,SERIAL#';

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

l If stopping the blocked session affects the normal running of the database, you are
advised to contact Huawei technical support to confirm whether the session can be
stopped.

----End

6.3 Primary and Standby Database Failures

6.3.1 Standby Database Cannot Connect to the Primary Database

Problem
A standby database cannot connect to the primary database, raising error GS-00303 or
GS-00323.
GS-00303, failed to establish tcp connection to [192.168.1.12]:[2001],errno 111
GS-00323, RFS is not ready, can not get %s.
GS-00326, replica thread closed, replica agent error, remote ip [192.168.0.1] not
configured in archive destination [srv_replica.c:262]

Cause Analysis
l Cause 1: The configured IP address or port number is incorrect. As a result, the IP
address or port number used for connection is not the listening IP address or port number
of the peer end.
l Cause 2: The HA primary/standby connection relationship is determined by the link
specified by the ARCHIVE_DEST_N parameter (including the peer IP address and port
number). If multiple NICs exist on the machine where the connection initiator is located,
or if multiple IP addresses exist in a NIC, the source IP address used by the connection
initiator may be different from the IP address configured on the receiver. As a result, the
connection fails.

Procedure
Assume that the IP addresses of a primary database are 192.168.10.12 and 192.168.1.13 and
that the IP address of a standby database is 192.168.1.204.

NOTE

If the standby database cannot be connected to the primary database after a primary/standby switchover,
perform Step 1 through Step 5 again.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Stop the GaussDB 100 service.


python $GSDB_HOME/bin/zctl.py -t stop

Step 3 Add all the primary database IP addresses that can communicate with the standby database to
the configuration item REPL_TRUST_HOST in the zengine.ini file of the standby database.

The path of zengine.ini is $GSDB_DATA/cfg/zengine.ini. The number of IP addresses


cannot exceed 8.
REPL_TRUST_HOST = 192.168.10.12,192.168.10.13

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Step 4 Add all the primary database IP addresses that can communicate with the standby database to
the configuration item LSNR_ADDR in the zengine.ini file of the primary database.

The path of zengine.ini is $GSDB_DATA/cfg/zengine.ini. The number of IP addresses


cannot exceed 8.
LSNR_ADDR = 192.168.10.12,192.168.10.13

Step 5 Starts the GaussDB 100 service.


python $GSDB_HOME/bin/zctl.py -t start

Enable listening of the IP address used by the primary database to communicate with the
standby database so that the standby database can properly access the primary database.

----End

Solution 2
Assume that the IP addresses of a primary database are 192.168.10.12 and 192.168.1.12 and
that the IP address of a standby database is 192.168.1.204. The link configured in the primary
database is ARCHIVE_DEST_2=SERVICE=192.168.1.204:1612 SYNC, and that in the
standby database is ARCHIVE_DEST_2=SERVICE=192.168.1.12:1612 SYNC.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Add the LOCAL_HOST attribute to the configuration item ARCHIVE_DEST_2 in the
zengine.ini file on the primary database.
ARCHIVE_DEST_2 = LOCAL_HOST=192.168.1.12 SERVICE=192.168.1.204:1612 SYNC

Step 3 Restart the primary database.


-- Stop the primary database.
python $GSDB_HOME/bin/zctl.py -t stop
-- Start the primary database.
python $GSDB_HOME/bin/zctl.py -t start

In this case, the primary database explicitly binds to 192.168.1.12 before connecting to the
standby database, and the standby database obtains 192.168.1.12 after parsing. Therefore, the
standby database can be connected to the primary database.

----End

6.3.2 Two Primary Databases Exist

Problem
Two primary databases exist at the same time. They will both write data, resulting in data
inconsistency.

Cause Analysis
If primary and standby databases exist, the original standby is promoted to primary in a
failover, and the original primary is started again, there will be two primary databases at the
same time.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

NOTE

Log in to the GaussDB 100 from each server as the database administrator. Run the following command:
select DATABASE_ROLE from v$database;
If the database role is PRIMARY in all the command output, it indicates that two primary databases
exist. In this case, you need to perform demotion.
DATABASE_ROLE
------------------------------
PRIMARY

1 rows fetched.

Procedure
Step 1 Log in to the original primary GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Run the following command to stop the original primary database:
shutdown immediate;

Step 3 Exit the connection to the GaussDB 100 database.


EXIT

Step 4 Run the following command to start database loading, but do not open the database:
python $GSDB_HOME/bin/zctl.py -t start -m MOUNT

Step 5 Log in to the original primary GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.
Step 6 Run the following command on the original primary database:
ALTER DATABASE CONVERT TO PHYSICAL STANDBY;

----End

6.3.3 Standby Database Rebuild

Problem
The standby database needs to be rebuilt.

Cause Analysis
After the primary database is faulty, a failover occurs. the original primary is demoted to
standby. In this case, the standby may be in need repair state and needs to be rebuilt.
Notice that only in the maximum performance mode or the maximum availability mode can
the following method be used to rebuild the standby database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Run the following command to stop the new standby database:
shutdown immediate;

Step 3 Exit the connection to the GaussDB 100 database.


EXIT

Step 4 Delete contents in the archive directory and data directory of the new standby database.
Note that the data files in the directory must be deleted and all subdirectories must be
retained. Otherwise, the rebuilding fails. The directories are as follows:
l Archive directory: $GSDB_DATA/archive_log
l Data directory: $GSDB_DATA/data
Step 5 Run the following command to start database loading, but do not open the database:
python $GSDB_HOME/bin/zctl.py -t start -m MOUNT

Step 6 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.
Step 7 Run the build database command on the new standby database to rebuild the database.
build database;

----End

6.3.4 Standby Database Rebuild Failure


Problem
The standby database fails to be rebuilt.
l The configuration file is incorrect. The error information is as follows:
GS-00304, tcp connection is closed

l The data file on the primary database is abnormal. The error information is as follows:
GS-00002, Failed to open the file %s, the error code was %d.

l The permission for the data file is insufficient.


can't open file '%s': [Errno 13] Permission denied.

Cause Analysis
While the standby database is rebuilt, the configuration file information on the primary and
standby databases may be incorrect. As a result, the connection between the primary and
standby databases cannot be set up, and the standby database fails to be rebuilt. After a

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

connection is set up between the primary and standby databases, if the Data file of the primary
database is abnormal or the file permission is insufficient, the standby will also fail to be
rebuilt.

Procedure
l The configuration file is incorrect.
a. Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
b. Set parameters including LSNR_ADDR, LSNR_PORT, REPL_PORT,
ARCHIVE_DEST_2, and REPL_TRUST_HOST in the zengine.ini file of the
primary database.
The path of zengine.ini is $GSDB_DATA/cfg/zengine.ini.
c. Restart the primary database.
-- Stop the primary database.
python $GSDB_HOME/bin/zctl.py -t stop
-- Start the primary database.
python $GSDB_HOME/bin/zctl.py -t start

d. Set parameters including LSNR_ADDR, LSNR_PORT, REPL_PORT,


ARCHIVE_DEST_2, and REPL_TRUST_HOST in the zengine.ini file of the
standby database.
The path of zengine.ini is $GSDB_DATA/cfg/zengine.ini.
e. Restart the standby database.
-- Stop the standby database.
python $GSDB_HOME/bin/zctl.py -t stop
-- Start the standby database.
python $GSDB_HOME/bin/zctl.py -t start

l The data file of the primary database is abnormal.


a. Use the backup file to restore the Data folder.
l The permission for the data file is insufficient.
a. Log in to a server where GaussDB 100 is deployed as user root.
b. Assign permissions to each file. For details about the permissions for data files and
directories, see "Database Security Maintenance > Configuring File Permission
Security Policies" in GaussDB 100 V300R001C00 Security Maintenance Guide
(Standalone).
chmod 700 /home/gaussdba/data

6.3.5 Data Volumes in Primary and Standby Databases Are


Different
Problem
When users query the size of the data files on the primary and standby databases, it is found
that the data volume in the primary database largely differs from that in the standby database.
The data file size is the total size of data in the DB_TABLES and DB_INDEXES views.

NOTE

To query the data volume in the DB_TABLES and DB_INDEXES views, use the following statements:
SELECT SUM(BYTES) FROM DB_TABLES;
SELECT SUM(BYTES) FROM DB_INDEXES;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Cause Analysis
Data is not synchronized between the primary and standby databases. For example, if the logs,
archive logs, and data files are stored on the same disk, the I/O bottleneck of the disk affects
the replay speed of the logs on the standby database. As a result, the data volumes on the
primary and standby databases are different.

Procedure
Wait for the standby node to synchronize data. No operation is required.

6.4 Data Loss

6.4.1 Table Data Insertion Failure

Problem
Failed to insert data into the table. Error information:
GS-00786, could not find datafile to extend extent in tablespace test_tablespace.

Or
GS-00708: The table or the view test_table does not exist.

Cause Analysis
If the table object to be inserted does not exist or the tablespace is insufficient, data insertion
fails.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Check whether the table object exists.


-- Check whether the table exists.
SELECT TABLE_NAME FROM ADM_TABLES
-- Check whether the tablespace exists.
SELECT TABLESPACE_NAME FROM ADM_TABLESPACES;

If the object does not exist, create it or check whether the object name is correct.
If it exists, go to Step 3.
Step 3 Run the following command to check the tablespace usage:
SELECT * FROM DBA_TABLESPACES;

l If the tablespace is sufficient, contact Huawei technical support.


l If the tablespace is insufficient, go to Step 4.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Step 4 Expand the tablespace by using either of the following methods:


l Manually modify the tablespace and specify the size of the tablespace to be expanded.
ALTER TABLESPACE human_resource ADD DATAFILE 'new_datafile' SIZE 128M;

l The tablespace is automatically expanded. You can specify the size of each tablespace to
be expanded.
ALTER TABLESPACE human_resource AUTOEXTEND ON NEXT 5M;

Step 5 If the tablespace fails to be expanded, and the error "GS-00728: failed to find free space size"
is displayed, check the disk space and select a proper location to create data files, or free up
the disk space.
-- Query the disk space usage.
df -h

----End

6.4.2 Tablespace Creation Failure


Problem
Fail to create the tablespace. The error information is as follows:
GS-00003: Failed to create the file %s, the error code was %d.

Cause Analysis
If you do not have the read and write permissions for the directory where the tablespace is to
be created, the creation fails. In this case, you need to assign the required permission to the
directory.

Procedure
Step 1 Log in to a server where GaussDB 100 is deployed as user root.

Step 2 Change the owner of the tablespace directory to the user who installs the database.
Assume the database installation user is gaussdba and the tablespace directory is /home/
gaussdba/data/data1.
chown gaussdba /home/gaussdba/data/data1

Step 3 Grant the 700 permission to the tablespace directory.


chmod 700 /home/gaussdba/data/data1

----End

6.4.3 Table Creation Failure


Problem
Fail to create the table. The error information is as follows:
GS-00103: can't allocate page from test_user

Cause Analysis
When a table is created, the DC POOL space is insufficient. As a result, the table fails to be
created. In this case, you need to manually increase the value of SHARED_POOL_SIZE.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Modify the zengine.ini file and increase the value of SHARED_POOL_SIZE. The value
range is an integer, [82M,32T]. The unit is byte.
The path of zengine.ini is $GSDB_DATA/cfg/zengine.ini.
SHARED_POOL_SIZE = 128M

Step 3 Restart the database service.


-- Stop the database service.
python $GSDB_HOME/bin/zctl.py -t stop
-- Start the database service.
python $GSDB_HOME/bin/zctl.py -t start

----End

6.5 Upgrade Tool Faults

6.5.1 Pre-check Fails During Automatic HA Upgrade


Problem
During the automatic HA upgrade, the pre-check operation fails to be performed. The error
information is as follows:
Upgrade Failed: Check ssh connection failed, check your ssh configure file please.

Cause Analysis
The SSH configurations are different across OSs. As a result, trust fails to be established
through SSH connections. In this case, you need to manually modify the SSH configurations.

Procedure
Step 1 Log in to each server where GaussDB 100 is deployed as user root.

Step 2 Open the SSH configuration file /etc/ssh/sshd_config.


vi /etc/ssh/sshd_config

Press i to enter the edit mode.


Step 3 In the /etc/ssh/sshd_config SSH configuration file on each server, set
ChallengeResponseAuthentication to no.
Setting ChallengeResponseAuthentication to no indicates that the SSH does not allow
challenge/response authentication.
ChallengeResponseAuthentication no

Step 4 In the /etc/ssh/sshd_config SSH configuration file on each server, set


PasswordAuthentication to yes.
Setting PasswordAuthentication to yes indicates that SSH allows password authentication.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
Troubleshooting Guide (Standalone) 6 Common Faults

PasswordAuthentication yes

Step 5 Press Esc and enter :wq to save the changes and exit.

Step 6 Restart the SSH service.


service sshd restart

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

7 Interface Mapping (Basic Packages vs.


Compatible Packages)

7.1 Data Dictionary Tables


Table 7-1 Name mapping of data dictionary tables (basic packages vs. compatible packages)
Basic Package Compatible Package

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

7.2 DBA Views


Table 7-2 Name mapping of DBA views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

7.3 User Views


Table 7-3 Name mapping of user views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_ARGUMENTS ALL_ARGUMENTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

7.4 Dynamic Performance Views


Table 7-4 Name mapping of dynamic performance views (basic packages vs. compatible
packages)
Basic Package Compatible Package

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

7.5 Configuration Parameters


Table 7-5 Name mapping of configuration parameters (basic packages vs. compatible
packages)
Basic Package Compatible Package

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100 7 Interface Mapping (Basic Packages vs. Compatible
Troubleshooting Guide (Standalone) Packages)

Basic Package Compatible Package

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
V300R001C00

User Guide (Standalone)

Issue 03
Date 2019-06-06

HUAWEI TECHNOLOGIES CO., LTD.


Copyright © Huawei Technologies Co., Ltd. 2019. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any means without prior written
consent of Huawei Technologies Co., Ltd.

Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective
holders.

Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the
customer. All or part of the products, services and features described in this document may not be within the
purchase scope or the usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties, guarantees or
representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in the
preparation of this document to ensure accuracy of the contents, but all statements, information, and
recommendations in this document do not constitute a warranty of any kind, express or implied.

Huawei Technologies Co., Ltd.


Address: Huawei Industrial Base
Bantian, Longgang
Shenzhen 518129
People's Republic of China

Website: http://e.huawei.com

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. i


GaussDB 100
User Guide (Standalone) Contents

Contents

1 About This Document.................................................................................................................. 1


2 Installation and Deployment...................................................................................................... 6
2.1 Installation Overview..................................................................................................................................................... 6
2.2 Installation Preparation...................................................................................................................................................6
2.2.1 Environment Requirements......................................................................................................................................... 6
2.2.2 Obtaining and Verifying an Installation Package........................................................................................................ 8
2.2.3 Planning for Installation............................................................................................................................................ 16
2.3 Standalone Installation (Simple Mode)........................................................................................................................ 19
2.4 Standalone Installation (Compatible Mode).................................................................................................................24
2.5 Standalone HA Installation (Simple Mode)................................................................................................................. 29
2.6 Standalone HA Installation (Compatible Mode).......................................................................................................... 38
2.7 Uninstalling a Database................................................................................................................................................ 48
2.8 Upgrading a Database...................................................................................................................................................49
2.9 Downgrading a Database..............................................................................................................................................56
2.10 Rolling Back a Database.............................................................................................................................................65

3 Database System Management................................................................................................. 69


3.1 Risky Operations.......................................................................................................................................................... 69
3.2 Managing Sessions and Threads...................................................................................................................................70
3.3 Configuring a Database System................................................................................................................................... 72
3.4 Managing Database Status............................................................................................................................................77
3.5 Managing a Database....................................................................................................................................................80
3.6 Managing Logs............................................................................................................................................................. 82
3.6.1 Log Overview............................................................................................................................................................ 82
3.6.2 Configuring Logs.......................................................................................................................................................83
3.6.3 Viewing Logs.............................................................................................................................................................85
3.6.4 Deleting Logs............................................................................................................................................................ 90
3.7 Managing Transactions.................................................................................................................................................90
3.8 Backup and Restoration................................................................................................................................................91
3.8.1 Backup and Restoration Overview............................................................................................................................ 91
3.8.2 Backup and Restoration Solutions.............................................................................................................................92
3.8.3 Data Backup.............................................................................................................................................................. 94
3.8.4 Data Restoration........................................................................................................................................................ 96

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. ii


GaussDB 100
User Guide (Standalone) Contents

3.8.5 Data Restoration Using ztrst......................................................................................................................................98


3.8.6 Flashback................................................................................................................................................................. 100

4 Routine O&M Management....................................................................................................102


4.1 Starting or Stopping a Database................................................................................................................................. 102
4.2 HA Maintenance.........................................................................................................................................................104
4.2.1 Protection Modes..................................................................................................................................................... 104
4.2.2 HA Rebuilding.........................................................................................................................................................105
4.2.3 Status Query............................................................................................................................................................ 106
4.2.4 Logical Replication..................................................................................................................................................113
4.2.5 HA Switchovers.......................................................................................................................................................148
4.2.6 Common Troubleshooting Methods........................................................................................................................ 149
4.3 System Monitoring..................................................................................................................................................... 150
4.3.1 Monitoring Metrics..................................................................................................................................................150
4.3.2 Monitoring the Database Status...............................................................................................................................151
4.3.3 Monitoring Resource Usage.................................................................................................................................... 151
4.3.4 Monitoring Logs...................................................................................................................................................... 153
4.3.5 Collecting Statistics................................................................................................................................................. 153
4.3.5.1 Manual Collection................................................................................................................................................ 153
4.3.5.2 Automatic Collection............................................................................................................................................155
4.4 Routine Maintenance.................................................................................................................................................. 156

5 Database Usage.......................................................................................................................... 158


5.1 Configuring Client Access Authentication.................................................................................................................158
5.2 Connecting to a Database........................................................................................................................................... 162
5.3 Managing Database Objects....................................................................................................................................... 164
5.3.1 Managing Tablespaces.............................................................................................................................................164
5.3.2 Managing Tables......................................................................................................................................................167
5.3.2.1 Creating a Table....................................................................................................................................................167
5.3.2.2 Viewing Table Information...................................................................................................................................170
5.3.2.3 Modifying a Table.................................................................................................................................................170
5.3.2.4 Clearing a Table....................................................................................................................................................172
5.3.2.5 Deleting a Table....................................................................................................................................................173
5.3.3 Managing Partitioned Tables................................................................................................................................... 173
5.3.4 Managing Indexes....................................................................................................................................................179
5.3.5 Managing Views...................................................................................................................................................... 181
5.4 Exporting and Importing Data.................................................................................................................................... 182
5.4.1 Overview of Export and Import...............................................................................................................................182
5.4.2 Solution of Export and Import.................................................................................................................................183
5.4.3 Exporting Data.........................................................................................................................................................183
5.4.4 Importing Data.........................................................................................................................................................184
5.4.5 Logically Exporting Data........................................................................................................................................ 184
5.4.6 Logically Importing Data........................................................................................................................................ 185

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iii


GaussDB 100
User Guide (Standalone) Contents

6 Interface Mapping (Basic Packages vs. Compatible Packages)........................................ 187


6.1 Data Dictionary Tables............................................................................................................................................... 187
6.2 DBA Views.................................................................................................................................................................189
6.3 User Views..................................................................................................................................................................191
6.4 Dynamic Performance Views..................................................................................................................................... 194
6.5 Configuration Parameters........................................................................................................................................... 196

7 Glossary....................................................................................................................................... 198

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. iv


GaussDB 100
User Guide (Standalone) 1 About This Document

1 About This Document

GaussDB 100 is an enterprise-level relational database engine developed by Huawei. It


features high performance, high availability, high scalability, and easy O&M; and can run
stably and efficiently on the x86 or ARM open architecture. GaussDB 100 supports SQL
standards and the syntax of mainstream commercial databases, facilitating application
development and migration. Using the secure, reliable storage provided by GaussDB 100 for
relational and structured data, you can develop and manage high-availability, high-
performance data applications in finance, telecom, cloud, and industry digitalization fields.

The framework of GaussDB 100 is component-based and can be used for a standalone
database or a cluster. This document provides guidance for installing, configuring, working
with, and maintaining standalone GaussDB 100 and for using its tools.

GaussDB 100 software packages are classified into basic and compatible packages. They
differ in the names of various interfaces. A compatible package is used to offer compatibility
with the usage habits of mainstream databases in the industry. The interfaces mentioned in
this document use names from basic packages. If you have installed compatible packages, you
can use either the interface names of basic packages or those of compatible packages by
referring to Interface Mapping (Basic Packages vs. Compatible Packages). For details
about how to install the basic and compatible packages, see Installation and Deployment in
GaussDB 100 V300R001C00 User Guide (Standalone).

Intended Audience
The document is intended for GaussDB 100 database administrators and describes how to
create and maintain databases.

As a database administrator, your job may cover the following:

l Create and configure GaussDB 100 databases.


l Create objects, such as tables, indexes, and views.
l Routinely maintain GaussDB 100.
l Diagnose, fix, or report problems.

The following information is mandatory for a database administrator:

l Knowledge about a relational database. The theory helps you get familiar with GaussDB
100 and its usage.
l Knowledge about OSs. You will need it when you configure and run GaussDB 100.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 1


GaussDB 100
User Guide (Standalone) 1 About This Document

Symbol Conventions
The symbols that may be found in this document are defined as follows.

Symbol Description

Indicates an imminently hazardous situation which, if not avoided, will


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in death or serious injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in minor or moderate injury.

Indicates a potentially hazardous situation which, if not avoided, could


result in equipment damage, data loss, performance deterioration, or
unanticipated results.
NOTICE is used to address practices not related to personal injury.

Calls attention to important information, best practices, and tips.


NOTE is used to address information not related to personal injury,
equipment damage, and environment deterioration.

Example Conventions
The following table describes some example information in this document. You can replace
the example information as needed.

Information Description

$GSDB_HOME Environment variable of the GaussDB 100 installation directory


that is automatically written when install.py is used for
installation. Assume that /opt/gaussdb/app is set as the
installation directory.

$GSDB_DATA Environment variable of the GaussDB 100 data directory that is


automatically written when install.py is used for installation.
Assume that /opt/gaussdb/data is set as the data directory.

gaussdba GaussDB 100 administrator manually created after the installation

database_123 Password of the database administrator gaussdba

192.168.0.1 IP address of the GaussDB 100 server

1888 Port number used by GaussDB 100 to listen to client connection


requests

Parameters of GaussDB 100 tools are parsed in sequence. If a parameter is specified for
multiple times, the last value takes effect.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 2


GaussDB 100
User Guide (Standalone) 1 About This Document

CLI Format Conventions


Format Description

Boldface Command keywords are in boldface.

Uppercase letters Keywords must be in uppercase.

Italic Command parameters, paths, and file or folder names are in


italics.

[] Items (keywords and parameters) in brackets [ ] are optional.

... Indicates that preceding elements can appear repeatedly.

[ x | y | ... ] Indicates that one item is selected from two or more options or no
item is selected.

{ x | y | ... } Indicates that one item is selected from two or more options.

[ x | y | ... ] [ ... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
spaces.

[ x | y | ... ] [ ,... ] Indicates that multiple parameters or no parameter can be


selected. If multiple parameters are selected, separate them with
commas (,).

{ x | y | ... } [ ... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with spaces.

{ x | y | ... } [ ,... ] Indicates that at least one parameter can be selected. If multiple
parameters are selected, separate them with commas (,).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 3


GaussDB 100
User Guide (Standalone) 1 About This Document

Change History
Version Change Description Changed On

03 Added: 2019-06-06
l Flashback
l Data Restoration Using ztrst
Modified:
l Procedure in Logical Replication
l Descriptions of parameters of BUILD
DATABASE in HA Rebuilding
l Schema-specific restoration added in
Backup and Restoration Solutions
l Support for tablespace shrinking in
Managing Tablespaces
l Support for renaming indexes in Managing
Indexes
l Parallel backup and restoration added in
Backup and Restoration Solutions, Data
Backup, and Data Restoration
l Support for collecting index statistics in
Manual Collection
l Support for the -w parameter to set the
timeout interval for the client to wait for a
database response in Connecting to a
Database
l Alarm TablespaceUsage added in
Monitoring Alarms, with its alarm format
modified
l Method of configuring LSNR_ADDR in
Configuring Client Access
Authentication
l Descriptions of rollback transaction
scenarios in Managing Transactions
l Descriptions of the EXTENTS parameter
added in Managing Tablespaces
l Support for renaming constraints in
Modifying a Table
Optimized:
l Support for HA building by zctl.py in HA
Rebuilding

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 4


GaussDB 100
User Guide (Standalone) 1 About This Document

Version Change Description Changed On

02 Added: 2019-04-05
l Managing Logs
l Obtaining and Verifying an Installation
Package
l GaussDB 100 support for smooth upgrade
in Upgrading a Database
l OS parameter table in Environment
Requirements
Optimized:
l Procedure in Upgrading a Database
l Procedure in Standalone Installation
(Simple Mode)
l Procedure in Standalone HA Installation
(Simple Mode)
l Logical Replication
l Configuring Client Access
Authentication
Modified:
l Index types in Managing Indexes
l Descriptions of slow queries added in Log
Overview and Viewing Logs
l Operation steps in the OPEN child modes
in Managing Database Status
l Procedure in Uninstalling a Database
l Upgrading a Database
l High risk information added in Risky
Operations

01 This issue is the first official release. 2018-10-30

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 5


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

2 Installation and Deployment

GaussDB 100 supports multiple deployment modes. Choose the one suitable for your service
scenario.

2.1 Installation Overview


GaussDB 100 can be deployed in standalone or in standalone HA mode. In standalone mode,
multiple database instances can be deployed on a single host. However, this mode is not
recommended for data security purposes. The standalone HA system can contain one primary
database and at least one standby database, as well as a maximum of nine standby databases
and nine cascaded standby databases. A primary database provides read/write services for
applications, and a standby database provides only read services.

Both of the standalone deployment and standalone HA deployment support a simple mode
and a compatible mode. In simple mode, you can install a GaussDB 100 database and use it
properly. The compatible mode is an enhancement of the simple mode. After compatible
packages are installed, GaussDB 100 offers compatibility with the interface names of
mainstream databases.

2.2 Installation Preparation


Before installing GaussDB 100, ensure that the hardware and software environments meet the
installation requirements and plan the installation as needed.

2.2.1 Environment Requirements


This section describes the hardware and software requirements for GaussDB 100 installation.
When planning the hardware configuration of a product, consider the data scale and expected
database response speed.

Hardware Requirements
GaussDB 100 can be deployed and run on physical servers or in mainstream virtualization
environments, such as VMware, KVM, and Xen. For details about the hardware requirements,
see Table 2-1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 6


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-1 Hardware requirements


Item Minimum Configuration Recommended Configuration

Hard disk 709M l Reserve 25 GB for each database


instance.
l Reserve more than 70% of
available disk space for data
storage.
You are advised to configure RAID
1 for the system disk and RAID 5 or
RAID 10 for the data disk. For
details about how to configure
RAID, see the manual provided by
the hardware manufacturer.
Serial Attached SCSI (SAS) solid-
state drives (SSDs) can be used for
GaussDB 100 as the primary storage
devices of the database. SSDs must
be deployed in RAID mode.

Memory At least 218 MB free memory for Each database instance requires 8
each instance GB memory.

CPU Single core 4 cores

Network 10-Gigabit Ethernet or above -


requirement

Software Requirements
GaussDB 100 can be deployed on a Linux OS. Ensure that the OS is completely installed, or
database exceptions may occur.

Table 2-2 OS and user configuration requirements


Item Requirement

OS type and The x86 architecture supports the following operating systems:
version l Red Hat Enterprise Linux Server release 7.4 x86_64
l SUSE Linux Enterprise Server 11.3 (SUSE 11 for short), x86_64
l SUSE Linux Enterprise Server 12.4 (SUSE 12 for short), x86_64
l EulerOS Server V2.0SP3 x86_64
l EulerOS Server V2.0SP5 x86_64
The ARM architecture supports the following operating systems:
EulerOS Server V2.0SP8 ARM_64

File system Software: Ext4


Data storage: Ext4

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 7


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-3 OS parameters


Parameter Description Recommended Value

kernel.sem Amount of semaphores 50100 128256000 50100


2560

net.core.netdev_max_b Size of a receiver queue. This 1000


acklog parameter is used if the interface
receives data packets faster than
the kernel can handle them.

net.ipv4.tcp_max_syn_ Number of uncompleted requests 2048


backlog allowed by SYN

kernel.core_pattern Core file generation parameter /corefile/core.%p.%e

kernel.core_uses_pid Core file generation parameter 1

kernel.shmmni Maximum number of shared 4096


memory segments

net.ipv4.ip_local_port_r Port I allocated to communicate 9000 65500


ange with a user process when the
dedicated database server
process is started

net.core.rmem_default Default size of the socket data 262144


receiving buffer

net.core.wmem_default Default size of the socket data 262144


sending buffer

net.core.rmem_max Maximum size of the socket data 4194304


receiving buffer

net.core.wmem_max Maximum size of the socket data 1048576


sending buffer

fs.aio-max-nr Number of asynchronous I/O 1048576


requests that can be concurrently
processed

fs.file-max Maximum number of open file 6815744


handles

2.2.2 Obtaining and Verifying an Installation Package


To prevent network security threats caused by malicious tampering or damage during
installation package transfer, verify the integrity of an installation package after obtaining it.
Deployment can be started only after the package passes the verification.

Prerequisites
l You have obtained a simplified PGP verification tool, such as PGPVerify, and the public
key file as well.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 8


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l You have obtained the GaussDB 100 installation package and signature file, which must
be saved in the same directory, and each package corresponds to a verification file. The
signature file is released together with the corresponding installation package in .asc
format. Generally, the file name is the same as the package name. If the name of an
installation package is GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz, the name of the corresponding verification file will be
GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.asc.

Procedure
Step 1 Obtain the PGPVerify tool.

Run the tool without installation. You can download it in any of the following ways:
l From Huawei Support website:
http://support.huawei.com/carrier/digitalSignatureAction
The website may be displayed in Chinese. To change the language to English, click
English, as shown in Figure 2-1.
Decompress the downloaded package. Open the decompressed folder VerificationTools
to obtain the verification tools of different versions available for different platforms.

Figure 2-1 Download page on Huawei Support

l From Huawei Support website for enterprise users:


http://support.huawei.com/enterprise/toolsinfo?
idAbsPath=0602_ROOT&nameAbsPath=Tools
%20software&pid=0602_ROOT&show=showVDetail&toolId=TL1000000054
The website may be displayed in Chinese. To change the language to English, click
English, as shown in Figure 2-2.
Decompress the downloaded package. Open the decompressed folder VerificationTools
to obtain the verification tools of different versions available for different platforms.

Figure 2-2 Download page on Huawei Support for enterprise users

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 9


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l From Huawei Device Knowledge Base:


Chinese: http://app.huawei.com/tkb/#!tservice/common/base/digit.html?
resourceId=146681
English: http://app.huawei.com/tkb/#!tservice/common/base/digit.html?
resourceId=146680
Open the website of the corresponding language as required. Click Download to
download the OpenPGP verification guide. Figure 2-3 shows the download page on
Huawei Device Knowledge Base.
Decompress the downloaded package. Open the decompressed folder VerificationTools
to obtain the verification tools of different versions available for different platforms.

Figure 2-3 Download page on Huawei Device Knowledge Base

NOTE

If you have the access permission but an error is displayed after you click the URL, switch the
language.

Step 2 Obtain the public key file.


l From Huawei Support website:
– From Huawei Support website:
http://support.huawei.com/carrier/digitalSignatureAction
– From Huawei Support website for enterprise users:
http://support.huawei.com/enterprise/toolsinfo?
idAbsPath=0602_ROOT&nameAbsPath=Tools
%20software&pid=0602_ROOT&show=showVDetail&toolId=TL1000000054
– From Huawei Device Knowledge Base:
Chinese: http://app.huawei.com/tkb/#!tservice/common/base/digit.html?
resourceId=146681
English: http://app.huawei.com/tkb/#!tservice/common/base/digit.html?
resourceId=146680
NOTE

The verification tool and public key file are packed in one file. Therefore, their download
paths are the same. After decompression, the file named KEYS is the public key file.
l From the public key server:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 10


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

a. Access the following public key server URL:


https://zimmermann.mayfirst.org/pks/lookup?
op=vindex&search=0x27a74824&fingerprint=on
In this URL, 0x27A74824 is the ID of the public key, as shown in Figure 2-4.

Figure 2-4 Public key search results

b. Click the public key ID 27A74842 in the search results, and view complete
information of the public key, as shown in Figure 2-5.

Figure 2-5 Complete information of the public key

c. Copy the public key information to a text file, and name the file KEYS.
Step 3 Import the public key.
1. Log in to the server where the installation package to be verified resides as a common
user.
2. Run the following command to import the public key file (/home/openpgp/keys is an
example directory where the KEYS file is stored, and needs to be replaced with an actual
directory):
# gpg --import "/home/opengpg/keys/KEYS"

The following information will be displayed:


gpg: /home/openpgp/.gnupg/trustdb.gpg: trustdb created
gpg: key 27A74824: public key "OpenPGP signature key for Huawei software
(created on 30th Dec,2013) <support@huawei.com>" imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)

3. Run the following command to check the import status:


# gpg --fingerprint

If the following information is displayed, the public key is successfully imported:


/home/openpgp/.gnupg/pubring.gpg
---------------------------------
pub 2048R/27A74824 2013-12-30

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 11


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Key fingerprint = B100 0AC3 8C41 525A 19BD C087 99AD 81DF 27A7 4824
uid OpenPGP signature key for Huawei software (created on
30th Dec,2013) <support@huawei.com>

Step 4 Verify the public key.


1. Verify the validity of the OpenPGP public key by comparing the ID, fingerprint, and user
ID of the public key with those of the subject that releases the public key. Information
about the OpenPGP public key officially released by Huawei is as follows:
– Public key ID: 27A74824
– Public key fingerprint: B100 0AC3 8C41 525A 19BD C087 99AD 81DF 27A7
4824
– User ID: OpenPGP signature key for Huawei software (created on 30th Dec, 2013)
support@huawei.com
After the information is confirmed, you can set the trust level for the public key.
2. Run the following command to set the trust level for the public key:
# gpg --edit-key "OpenPGP signature key for Huawei" trust

Information similar to the following will be displayed, and the parts in bold must be
manually specified. Enter 5 following Your decision?, and y following Do you really
want to set this key to ultimate trust? (y/n).
gpg (GnuPG) 2.0.9; Copyright (C) 2008 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

pub 2048R/27A74824created: 2013-12-30 expires: never usage: SC


trust: unknown validity: unknown
[ unknown] (1). OpenPGP signature key for Huawei software (created on 30th
Dec,2013) <support@huawei.com>

pub 2048R/27A74824created: 2013-12-30 expires: never usage: SC


trust: unknown validity: unknown
[ unknown] (1). OpenPGP signature key for Huawei software (created on 30th
Dec,2013) <support@huawei.com>

Please decide how far you trust this user to correctly verify other users'
keys
(by looking at passports, checking fingerprints from different sources, etc.)

1 = I don't know or won't say


2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu
Your decision? 5
Do you really want to set this key to ultimate trust? (y/N) y
pub 2048R/27A74824 created: 2013-12-30 expires: never usage: SC
trust: ultimate validity: unknown
[ unknown] (1). OpenPGP signature key for Huawei software (created on 30th
Dec,2013) <support@huawei.com>
Please note that the shown key validity is not necessarily correct
unless you restart the program.

3. Run the following command to exit:


quit

Step 5 Verify the signature.

The signature file and installation package must be stored in the same directory. Assume that
they are both stored in /soft. Run the following command:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 12


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

gpg --verify "/home/opengpg/soft/GAUSSDB100-V300R001C00-DATABASE-


EULER20SP8-64bit.asc"
Information similar to the following will be displayed:
gpg: Signature made Thu 20 Jul 2017 09:55:58 AM CST using RSA key ID 27A74824
gpg: Good signature from "OpenPGP signature key for Huawei software (created on
30th Dec,2013) <support@huawei.com>"

If the RSA key ID in bold is the same as the public key ID and no WARN or FAIL is
displayed, the signature is valid.

Table 2-4 Examples of signature verification results


Verification Result Output Example Verification Result
Scenario

The signature passes gpg: Signature made Thu PASS


verification, with no Jan 9 15:29:06 2014 CST
exception. using RSA key ID
27A74824
gpg: Good signature from
"OpenPGP signature key for
Huawei software (created on
30th Dec,2013)
<support@huawei.com>"

The signature fails gpg: Signature made Thu FAIL


verification. Jan 9 15:29:06 2014 CST
using RSA key ID
27A74824
gpg: BAD signature from
"OpenPGP signature key for
Huawei software (created on
30th Dec,2013)
<support@huawei.com>"

The public key is not found. gpg: Signature made Thu FAIL
Jan 9 15:20:01 2014 CST
using RSA key ID
27A74824
gpg: Can't check signature:
public key not found

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 13


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Verification Result Output Example Verification Result


Scenario

The signature passes gpg: Signature made Thu WARNING


verification but the public Jan 9 15:29:06 2014 CST
key is not configured as a using RSA key ID
trusted one. 27A74824
gpg: Good signature from
"OpenPGP signature key for
Huawei software (created on
30th Dec,2013)
<support@huawei.com>"
gpg: WARNING: This key
is not certified with a trusted
signature!
gpg: There is no indication
that the signature belongs to
the owner.
Primary key fingerprint:
B100 0AC3 8C41 525A
19BD C087 99AD 81DF
27A7 4824

The corresponding source gpg: no signed data FAIL


file is not found. gpg: can't hash datafile: No
data

The signature has expired. gpg: Signature made FAIL


04/24/13 10:50:29 CST
using RSA key ID
133B64E5
gpg: Expired signature from
" OpenPGP signature test
key
<support@huawei.com>"
gpg: Signature expired
04/25/13 10:50:29 CST

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 14


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Verification Result Output Example Verification Result


Scenario

The signature passes gpg: Signature made WARNING


verification but the public 06/13/13 11:14:49 CST
key is revoked. using RSA key ID
133B64E5
gpg: Good signature from "
OpenPGP signature test key
<support@huawei.com>"
gpg: WARNING: This key
has been revoked by its
owner!
gpg: This could mean that
the signature is forged.
gpg: reason for revocation:
Key is no longer used
gpg: revocation comment:

No signature file is found None WARNING


for the source file.

If there are multiple files requiring signature verification in a version, the version will be
considered safe only when the verification results of all files are PASS and the trustiness of
the public key fingerprint source is confirmed. If the verification results contain WARN or
FAIL, the verification is not passed, indicating security risks. In this case, re-download the
installation package.

Step 6 Verify the installation package.


1. Decompress the installation package and check whether the installation directory and
files are complete.
Run the following command in the directory where the installation package is stored:
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

2. Go to the decompressed folder.


cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

3. Run the ls command.


During database installation, SHA-256 verification is automatically performed on the
database installation package.
ls -l

total 6660
-rw-r--r-- 1 gaussdba dbgrp 65 Apr 26 15:13 GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit.sha256
-rw-r--r-- 1 gaussdba dbgrp 6631944 Apr 26 15:12 GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit.tar.gz

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 15


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

-r-x------ 1 gaussdba dbgrp 78100 Apr 26 15:13 install.py


-r-x------ 1 gaussdba dbgrp 75955 Apr 26 15:13 upgrade.py

----End

2.2.3 Planning for Installation


Hosts and IP Addresses

Table 2-5 Host and IP address planning


Item Description

Host name l The primary server name must be unique within the local network.
Otherwise, the network will become faulty.
l The primary server name must contain more than two characters,
including letters, digits, and hyphens (-), excluding underscores (_).
l A name easy to remember and understand is recommended, such as
DBserver.

Server IP address Use a fixed IP address, such as 192.168.0.1.

Port No. Number of the TCP port to be listened by GaussDB 100, for example,
1888

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 16


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Users and Passwords

Table 2-6 Users and passwords

User/Group Type Suggestion on Planning


Name

gaussdba OS User gaussdba is used for running and maintaining


GaussDB 100. For security purposes, plan this user
as follows:
l Group: dbgrp
l Primary directory: /home/gaussdba
l shell: /bin/bash
l Password: For security purposes, you need to
change the password periodically. The password
must comply with the following rules:
– Contain a minimum of eight characters.
– Start with a letter, number sign (#), or an
underscore (_) if the password is not enclosed
in single quotation marks ('').
– Cannot be the same as the username or the
username spelled backwards.
– Can only contain digits, lowercase letters,
uppercase letters, spaces, and special
characters (for the special character list, see
Table 2-7; semicolons are not allowed in
passwords). At least three types of these
characters should be used.
– Enclose spaces and special characters
excluding _#$ with single quotation marks
('').

dbgrp OS Plan a separate user group, for example, dbgrp.

Table 2-7 Special characters

ID Chara ID Charact ID Charact ID Charact


cter er er er

1 ` 9 & 17 \ 25 '

2 ~ 10 * 18 | 26 "

3 ! 11 ( 19 [ 27 ,

4 @ 12 ) 20 { 28 <

5 # 13 - 21 } 29 .

6 $ 14 _ 22 ] 30 >

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 17


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

ID Chara ID Charact ID Charact ID Charact


cter er er er

7 % 15 = 23 ; 31 /

8 ^ 16 + 24 : 32 ?

Installation Directories

Table 2-8 Installation directories


Item Directory Description

Software /opt/software GaussDB 100 must be installed by user root,


package and the path must meet the following
directory requirement:
l Disk space ≥ 1 GB

GaussDB /opt/gaussdb Manually create this directory and set


100-dedicated permissions.
directory Pay attention to the following:
The umask values of OSs differ. Therefore,
after creating this directory, you are advised to
verify that the permission is less than or equal
to 0750.
l Owner: gaussdba
l Permission: ≤ 0750
l Disk space: > 20 GB

Installation /opt/gaussdb/app The install.py script automatically sets correct


directory permissions. It is recommended that this
directory be automatically created by
install.py. If you manually install a database,
ensure that the directory meet the following
requirements:
l Owner: gaussdba
l Permission: 0700
l Disk space: > 100 MB
l The directory is independent from the data
directory.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 18


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Item Directory Description

Data directory /opt/gaussdb/data The install.py script automatically sets correct


permissions. It is recommended that this
directory be automatically created by
install.py. If you manually install a database,
ensure that the directory meet the following
requirements:
NOTICE
l The umask values of OSs differ. Therefore, after
creating this directory, you are advised to check
the permissions and ensure they are 0700.
l Do not set the data file path to the run log
directory, log archiving directory, or any
directory that may be cleared.
l Owner: gaussdba
l Permission: 0700
l Disk space: > 20 GB

2.3 Standalone Installation (Simple Mode)


Scenario
GaussDB 100 provides the high-performance database service in standalone mode. This
section describes how to install the database on EulerOS 2.8 in simple mode. In simple mode,
you can install a GaussDB 100 database and use it properly.

Prerequisites
l The installation has been planned following instructions provided in Planning for
Installation.
l The installation package has been uploaded to the /opt/software/ directory.
l If a non-root user is used to install the database, ensure that this user is the owner of the
installation directory and has certain permissions (≤ 0750).

Precautions
l Before reinstalling GaussDB 100, ensure that operations in Uninstalling a Database
have been completed. Otherwise, the reinstallation may fail.
l To install multiple instances on the same server, plan different listening ports and data
directories.

Procedure
Assume that the IP address of the server where GaussDB 100 is installed is 192.168.0.1 and
the listening port number of the database is 1888.

Step 1 Log in to the server where GaussDB 100 is deployed as user root.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 19


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 2 Create an installation user and its user group, and configure their permissions to be less than
or equal to 0750.
groupadd dbgrp
useradd -g dbgrp -d /home/gaussdba -m -s /bin/bash gaussdba

Set the password for user gaussdba.


passwd gaussdba

Step 3 Create the /opt/software/gaussdb directory for storing the installation package and the
GaussDB 100 directory /opt/gaussdb as planned.
mkdir -p /opt/software/gaussdb
mkdir -p /opt/gaussdb

Step 4 Decompress the installation package.


cd /opt/software/gaussdb
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

Step 5 Go to the decompressed folder on the primary node and run the install.py script.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.1 -C LSNR_PORT=1888 -X

l Table 2-9 describes the parameters that need to be specified for install.py. For details
about install.py, see Database Management Tools > install.py in GaussDB 100
V300R001C00 Operation Guide to Tools (Standalone).

Table 2-9 install parameters

Parameter Description

-U Specifies the user and user group.

-R Specifies the installation directory.

-D Specifies the data file directory, that is, GAUSSDATA.

-C Specifies one or more configuration parameters. If no


parameter is specified, the default configuration in /home/
gaussdba/data/cfg/zengine.ini will be used.

-P If password-free login is disabled, you need to specify this


parameter at the end of the command line. During command
execution, you will be prompted to enter the username and
password for connecting to the database. The username is
SYS, and the default password is Changeme_123. If
password-free login is enabled, you do not need to specify
this parameter.

-X Specifies that no compatible package is installed because the


simple mode is used. The compatible package is used to offer
compatibility with the view names of mainstream databases.

l During installation, you can use the default optimized configuration of zengine.ini or use
the -C parameter to replace the initial configuration. Table 2-10 describes the parameters
that can be modified.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 20


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

NOTE

Running install.py will preliminarily check whether the memory size is valid. If the result does
not meet the installation requirements of GaussDB 100, the system will exit installation.
The memory size can be calculated as follows:
SGA_BUFF_SIZE = LOG_BUFFER_SIZE+SHARED_POOL_SIZE+DATA_BUFFER_SIZE
+TEMP_BUFFER_SIZE
The memory size (SGA_BUFF_SIZE) must be in the range [114 MB, shmmax) where shmmax
is a Linux kernel parameter and defines the maximum size of a single shared memory segment.
If -C is not used to specify the above four parameters during install.py running, their default
values will be used in the system check.

Table 2-10 zengine.ini configuration


Parameter Description Value Range Default Optimi
Value zation
Setting

TEMP_BUFFE Size of a temporary Integer (unit: 32M 1G


R_SIZE buffer byte)

DATA_BUFFE Size of a data buffer, Integer (unit: 128M 2G


R_SIZE which is used for byte)
recently accessed data

SHARED_PO Size of a shared pool Integer (unit: 128M 1G


OL_SIZE byte)

LOG_BUFFER Size of a log buffer, Integer (unit: 4M 64M


_SIZE which is used for redo byte)
logs

DBWR_PROC Number of background Integer 1 8


ESSES threads for writing
dirty pages. Increasing
the value improves
concurrency efficiency
but consumes more
resources.

LOG_BUFFER Number of log buffers Integer 4 8


_COUNT

LSNR_ADDR IPv4 address of the IP address 127.0.0.1 -


listening server

LSNR_PORT Number of the Integer, in the 1611 -


listening port range [1024,
65535]

SESSIONS Maximum number of Integer, in the 200 1500


concurrent sessions range [64, 8192]

For details about parameters, see section "Parameters" in GaussDB 100 V300R001C00
Database Reference (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 21


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l Running install.py creates an instance based on the database creation template. The
template requires that the data directory should have at least 20 GB space.
The save path of the template is /opt/software/gaussdb/GAUSSDB100-V300R001C00-
DATABASE-EULER20SP8-64bit/GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit/admin/scripts/create_database.sample.sql.
The database creation template is as follows:
CREATE DATABASE gauss CHARACTER SET binary CONTROLFILE
('?/data/cntl1',
'?/data/cntl2',
'?/data/cntl3')
LOGFILE
('?/data/log1' size 2G,
'?/data/log2' size 2G,
'?/data/log3' size 2G,
'?/data/log4' size 2G,
'?/data/log5' size 2G,
'?/data/log6' size 2G)
SYSTEM TABLESPACE DATAFILE
'?/data/system' size 1G
UNDO TABLESPACE DATAFILE
'?/data/undo' size 1G
DEFAULT TABLESPACE DATAFILE
'?/data/user1' size 1G autoextend on next 32M,
'?/data/user2' size 1G autoextend on next 32M,
'?/data/user3' size 1G autoextend on next 32M,
'?/data/user4' size 1G autoextend on next 32M,
'?/data/user5' size 1G autoextend on next 32M
TEMPORARY TABLESPACE TEMPFILE
'?/data/temp1' size 160M autoextend on next 32M,
'?/data/temp2' size 160M autoextend on next 32M
NOLOGGING TABLESPACE TEMPFILE
'?/data/temp2_01' size 160M autoextend on next 32M
NOLOGGING UNDO TABLESPACE TEMPFILE
'?/data/temp2_undo' size 160M autoextend on next 32M
ARCHIVELOG;

When you manually create a database creation template, the constraints on file
parameters are as follows:
– CONTROLFILE: Specifies a control file. The minimum number of control files is
2, and the file size is always 10 MB.
– LOGFILE: Specifies a log file. The minimum number of log files is 3, and the
minimum file size is 56 MB plus 16 KB plus the value of LOG_BUFFER_SIZE.
– SYSTEM TABLESPACE DATAFILE: Specifies the size of a data file in the
SYSTEM tablespace. The value range is [128 MB, 8 TB].
– UNDO TABLESPACE DATAFILE: Specifies the size of a data file in the UNDO
tablespace. The value range is [128 MB, 32 GB].
– DEFAULT TABLESPACE DATAFILE: Specifies the size of a data file in the
USERS tablespace (default). The value range is [1 MB, 8 TB].
– TEMPORARY TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP tablespace. The value range is [5 MB, 8 TB].
– NOLOGGING TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP2 tablespace. The value range is [1 MB, 8 TB].
– NOLOGGING UNDO TABLESPACE TEMPFILE: Specifies the size of a data
file in the TEMP2_UNDO tablespace. The value range is [128 MB, 32 GB].
– If AUTOEXTEND ON is specified, the following attributes can be set:
n NEXT: Specifies the extension size. If this parameter is not set, the default
value 16MB will be used.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 22


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

n MAXSIZE: Specifies the upper limit of extension.


○ If this parameter is omitted or is set to UNLIMITED, the maximum size
of the UNDO tablespace will be 32 GB, and that of other tablespaces will
be 8 TB.
○ The parameter value cannot be greater than 32 GB for the UNDO
tablespace, and cannot be greater than 8 TB for other tablespaces.
○ The value of MAXSIZE must be no less than that of NEXT.

Step 6 Check the installation result.


l If the installation is successful, the following information will be displayed:
Install successfully, for more detail information see /var/log/
zengineinstall.log.

l If the installation fails, rectify the fault based on the installation logs. The save path of
the installation logs is /var/log/zengineinstall.log.

After the installation succeeds, four environment variables will be added to the OS, as
described in the following table.

Table 2-11 Environment variables

Environment Description
Variable

GSDB_DATA GaussDB 100 data directory

GSDB_HOME GaussDB 100 installation directory, for example, the directory of


bin or Lib

PATH Path of the executable code of the database kernel

LD_LIBRARY_PAT l Library path


H l If you plan to back up your database using NetBackup (NBU),
add the NBU Lib path to environment variables. The default
path is /usr/openv/lib.

Step 7 Switch to user gaussdba and start the database service.


su - gaussdba

Open the folder where tools are stored.


cd /opt/gaussdb/app/bin
python zctl.py -t start

Step 8 Use zsql to connect to the database as the database administrator.


zsql SYS/Changeme_123@127.0.0.1:1888

The default administrator of GaussDB 100 is SYS and its default password is
Changeme_123. To ensure information security, change the password of SYS as soon as
possible. For more connection modes, see Connecting to a Database.

NOTE

For details about how to configure security hardening after a database is installed, see GaussDB 100
V300R001C00 Security Hardening Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 23


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 9 Change the password of the database administrator SYS.


ALTER USER SYS IDENTIFIED BY database_123 REPLACE Changeme_123;

In this command, database_123 is the new password of SYS.

----End

2.4 Standalone Installation (Compatible Mode)


Scenario
GaussDB 100 provides the high-performance database service in standalone mode. This
section describes how to install the database on EulerOS 2.8 in compatible mode. The
compatible mode is an enhancement of the simple mode. After compatible packages are
installed, GaussDB 100 offers compatibility with the interface names of mainstream
databases.

Prerequisites
l The installation has been planned following instructions provided in Planning for
Installation.
l The installation package has been uploaded to the /opt/software/ directory.
l The compatible package DIALECT-SCRIPT-xxxxx.tar.gz has been obtained and
uploaded to the same directory as the installation package.
l If a non-root user is used to install the database, ensure that this user is the owner of the
installation directory and has certain permissions (≤ 0750).

Precautions
l Before reinstalling GaussDB 100, ensure that operations in Uninstalling a Database
have been completed. Otherwise, the reinstallation may fail.
l To install multiple instances on the same server, plan different listening ports and data
directories.

Procedure
Assume that the IP address of the server where GaussDB 100 is installed is 192.168.0.1 and
the listening port number of the database is 1888.

Step 1 Log in to the server where GaussDB 100 is deployed as user root.

Step 2 Create an installation user and its user group, and configure their permissions to be less than
or equal to 0750.
groupadd dbgrp
useradd -g dbgrp -d /home/gaussdba -m -s /bin/bash gaussdba

Set the password for user gaussdba.


passwd gaussdba

Step 3 Create the /opt/software/gaussdb directory for storing the installation package and the
GaussDB 100 directory /opt/gaussdb as planned.
mkdir -p /opt/software/gaussdb
mkdir -p /opt/gaussdb

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 24


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 4 Upload the installation package and compatible package to the created directory. The
installation package and compatible package must be stored in the same directory.
Step 5 Decompress the installation package.
cd /opt/software/gaussdb
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

Step 6 Go to the decompressed folder on the primary node and run the install.py script.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.1 -C LSNR_PORT=1888

l Table 2-12 describes the parameters that need to be specified for install.py. For details
about install.py, see Database Management Tools > install.py in GaussDB 100
V300R001C00 Operation Guide to Tools (Standalone).

Table 2-12 install parameters


Parameter Description

-U Specifies the installation user and user group.

-R Specifies the installation directory.

-D Specifies the data file directory, that is, GAUSSDATA.

-C Specifies one or more configuration parameters. If no


parameter is specified, the default configuration in /home/
gaussdba/data/cfg/zengine.ini will be used.

-P If password-free login is disabled, you need to specify this


parameter at the end of the command line. During command
execution, you will be prompted to enter the username and
password for connecting to the database. The username is
SYS, and the default password is Changeme_123. If
password-free login is enabled, you do not need to specify
this parameter.

l During installation, you can use the default optimized configuration of zengine.ini or use
the -C parameter to replace the initial configuration. Table 2-13 describes the parameters
that can be modified.
NOTE

Running install.py will preliminarily check whether the memory size is valid. If the result does
not meet the installation requirements of GaussDB 100, the system will exit installation.
The memory size can be calculated as follows:
SGA_BUFF_SIZE = LOG_BUFFER_SIZE+SHARED_POOL_SIZE+DATA_BUFFER_SIZE
+TEMP_BUFFER_SIZE
The memory size (SGA_BUFF_SIZE) must be in the range [114 MB, shmmax) where shmmax
is a Linux kernel parameter and defines the maximum size of a single shared memory segment.
If -C is not used to specify the above four parameters during install.py running, their default
values will be used in the system check.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 25


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-13 zengine.ini configuration


Parameter Description Value Range Default Optimi
Value zation
Setting

TEMP_BUFFE Size of a temporary Integer (unit: 32M 1G


R_SIZE buffer byte)

DATA_BUFFE Size of a data buffer, Integer (unit: 128M 2G


R_SIZE which is used for byte)
recently accessed data

SHARED_PO Size of a shared pool Integer (unit: 128M 1G


OL_SIZE byte)

LOG_BUFFER Size of a log buffer, Integer (unit: 4M 64M


_SIZE which is used for redo byte)
logs

DBWR_PROC Number of background Integer 1 8


ESSES threads for writing
dirty pages. Increasing
the value improves
concurrency efficiency
but consumes more
resources.

LOG_BUFFER Number of log buffers Integer 4 8


_COUNT

LSNR_ADDR IPv4 address of the IP address 127.0.0.1 -


listening server

LSNR_PORT Number of the Integer, in the 1611 -


listening port range [1024,
65535]

SESSIONS Maximum number of Integer, in the 200 1500


concurrent sessions range [64, 8192]

For details about parameters, see section "Parameters" in GaussDB 100 V300R001C00
Database Reference (Standalone).
l Running install.py creates an instance based on the database creation template. The
template requires that the data directory should have at least 20 GB space.
The save path of the template is /opt/software/gaussdb/GAUSSDB100-V300R001C00-
DATABASE-EULER20SP8-64bit/GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit/admin/scripts/create_database.sample.sql.
The database creation template is as follows:
CREATE DATABASE gauss CHARACTER SET binary CONTROLFILE
('?/data/cntl1',
'?/data/cntl2',
'?/data/cntl3')
LOGFILE
('?/data/log1' size 2G,

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 26


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

'?/data/log2' size 2G,


'?/data/log3' size 2G,
'?/data/log4' size 2G,
'?/data/log5' size 2G,
'?/data/log6' size 2G)
SYSTEM TABLESPACE DATAFILE
'?/data/system' size 1G
UNDO TABLESPACE DATAFILE
'?/data/undo' size 1G
DEFAULT TABLESPACE DATAFILE
'?/data/user1' size 1G autoextend on next 32M,
'?/data/user2' size 1G autoextend on next 32M,
'?/data/user3' size 1G autoextend on next 32M,
'?/data/user4' size 1G autoextend on next 32M,
'?/data/user5' size 1G autoextend on next 32M
TEMPORARY TABLESPACE TEMPFILE
'?/data/temp1' size 160M autoextend on next 32M,
'?/data/temp2' size 160M autoextend on next 32M
NOLOGGING TABLESPACE TEMPFILE
'?/data/temp2_01' size 160M autoextend on next 32M
NOLOGGING UNDO TABLESPACE TEMPFILE
'?/data/temp2_undo' size 160M autoextend on next 32M
ARCHIVELOG;

When you manually create a database creation template, the constraints on file
parameters are as follows:
– CONTROLFILE: Specifies a control file. The minimum number of control files is
2, and the file size is always 10 MB.
– LOGFILE: Specifies a log file. The minimum number of log files is 3, and the
minimum file size is 56 MB plus 16 KB plus the value of LOG_BUFFER_SIZE.
– SYSTEM TABLESPACE DATAFILE: Specifies the size of a data file in the
SYSTEM tablespace. The value range is [128 MB, 8 TB].
– UNDO TABLESPACE DATAFILE: Specifies the size of a data file in the UNDO
tablespace. The value range is [128 MB, 32 GB].
– DEFAULT TABLESPACE DATAFILE: Specifies the size of a data file in the
USERS tablespace (default). The value range is [1 MB, 8 TB].
– TEMPORARY TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP tablespace. The value range is [5 MB, 8 TB].
– NOLOGGING TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP2 tablespace. The value range is [1 MB, 8 TB].
– NOLOGGING UNDO TABLESPACE TEMPFILE: Specifies the size of a data
file in the TEMP2_UNDO tablespace. The value range is [128 MB, 32 GB].
– If AUTOEXTEND ON is specified, the following attributes can be set:
n NEXT: Specifies the extension size. If this parameter is not set, the default
value 16MB will be used.
n MAXSIZE: Specifies the upper limit of extension.
○ If this parameter is omitted or is set to UNLIMITED, the maximum size
of the UNDO tablespace will be 32 GB, and that of other tablespaces will
be 8 TB.
○ The parameter value cannot be greater than 32 GB for the UNDO
tablespace, and cannot be greater than 8 TB for other tablespaces.
○ The value of MAXSIZE must be no less than that of NEXT.
Step 7 Check the installation result.
l If the installation is successful, the following information will be displayed:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 27


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Install successfully, for more detail information see /var/log/


zengineinstall.log.

l If the installation fails, rectify the fault based on the installation logs. The save path of
the installation logs is /var/log/zengineinstall.log.
After the installation succeeds, four environment variables will be added to the OS, as
described in the following table.

Table 2-14 Environment variables


Environment Description
Variable

GSDB_DATA GaussDB 100 data directory

GSDB_HOME GaussDB 100 installation directory, for example, the directory of


bin or Lib

PATH Path of the executable code of the database kernel

LD_LIBRARY_PAT l Library path


H l If you plan to back up your database using NetBackup (NBU),
add the NBU Lib path to environment variables. The default
path is /usr/openv/lib.

Step 8 Switch to user gaussdba and start the database service.


su - gaussdba

Open the folder where tools are stored.


cd /opt/gaussdb/app/bin
python zctl.py -t start

Step 9 Use zsql to connect to the database as the database administrator.


zsql SYS/Changeme_123@127.0.0.1:1888

The default administrator of GaussDB 100 is SYS and its default password is
Changeme_123. To ensure information security, change the password of SYS as soon as
possible. For more connection modes, see Connecting to a Database.

NOTE

For details about how to configure security hardening after a database is installed, see GaussDB 100
V300R001C00 Security Hardening Guide (Standalone).

Step 10 Change the password of the database administrator SYS.


ALTER USER SYS IDENTIFIED BY database_123 REPLACE Changeme_123;

In this command, database_123 is the new password of SYS.

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 28


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

2.5 Standalone HA Installation (Simple Mode)


Scenario
In GaussDB 100, you can deploy one primary database with multiple standby databases, or
one primary database with multiple standby and cascaded standby databases. A maximum of
nine standby databases and nine cascaded standby databases are supported.
The Primary role in GaussDB 100 is the primary database in a primary/standby relationship,
that is, the direct processing database of services. It communicates with a standby database
and synchronizes logs to the standby database. The Standby role is a standby database in a
primary/standby relationship, and is in the read-only state. It mainly receives logs from the
primary database and replays the service logs. When the primary database is faulty or
abnormally exits, the standby database can be promoted to primary to ensure the normal
running of services.
l One primary database with N standby databases
The primary database directly communicates with the standby databases.
– If a standby database is set to the SYNC mode, data on the standby database will be
synchronously updated when a transaction is committed on the primary database.
– If a standby database is set to the ASYNC mode, the primary database does not
wait for the standby database to receive logs when committing a transaction. When
the primary database is faulty, a standby database can be promoted to primary to
continue providing services.
l One primary database with N standby databases and N cascaded standby databases
The primary database communicates with standby databases, which in turn with
cascaded standby databases, effectively reducing the loads of the primary database.
The primary and standby databases can be set to either the SYNC or ASYNC mode, and
the standby and cascaded standby databases support only ASYNC replication. When the
primary database is faulty, a standby database can be promoted to primary. The cascaded
standby databases are only for DR purposes, and are placed remotely. They replicate data
from standby databases and have little impact on service environment performance. If
the primary database and all standby databases are faulty, a cascaded standby database
can also be promoted to primary.
This section uses one primary database, two standby databases, and one cascaded standby
database as an example to illustrate the standalone HA deployment, as shown in Figure 2-6.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 29


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Figure 2-6 One primary database, two standby databases, and one cascaded standby database

The following describes parameter configurations for the deployment of one primary database
with two standby databases and one cascaded standby database: (Instance A is used as an
example.)

l ARCHIVE_DEST_2=SERVICE=ipB:portB PRIMARY_ROLE: If instance A is


primary, it will connect to the IP address and port specified by SERVICE, that is,
instance B. If instance A is standby, the link will not be used.
l ARCHIVE_DEST_3=SERVICE=ipC:portC PRIMARY_ROLE: If instance A is
primary, it will connect to the IP address and port specified by SERVICE, that is,
instance C. If instance A is standby, the link will not be used.
l ARCHIVE_DEST_4=SERVICE=ipB:portB STANDBY_ROLE: If instance A is
standby, it will be connected to the IP address and port specified by SERVICE, that is,
instance B. If instance A is primary, the link will not be used.
NOTE

l If databases are deployed in HA DR mode, perform security hardening on both the primary and
standby databases.
l In simple mode, you can install a GaussDB 100 database and use it properly.

Prerequisites
l The installation has been planned following instructions provided in Planning for
Installation.
l The installation package has been uploaded to the /opt/software/ directory.
l If a non-root user is used to install the database, ensure that this user is the owner of the
installation directory and has certain permissions (≤ 0750).
l If the firewall service is enabled on servers, ensure that the primary and standby
databases have been added to the trust zones for each other.

Precautions
l To install multiple instances on the same server, plan different listening ports and data
directories.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 30


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l Before reinstalling GaussDB 100, ensure that operations in Uninstalling a Database


have been completed. Otherwise, the reinstallation may fail.
l It is recommended that the data and log directories of primary and standby databases be
the same. If they are different, you can use the DB_FILE_NAME_CONVERT and
LOG_FILE_NAME_CONVERT parameters for conversion. Assume that the data
directory of a primary database is /home/user1/zenith_home1/data and that of a
standby database is /home/user1/zenith_home2/data. Set
DB_FILE_NAME_CONVERT to /home/user1/zenith_home2/data,/home/user1/
zenith_home1/data on the primary database and to /home/user1/zenith_home1/data,/
home/user1/zenith_home2/data on the standby database. In this way, even if the
standby database is promoted to primary, the primary/standby relationship will not be
affected.

Procedure
Assume that the IP address of the primary database is 192.168.0.1, that of standby database 1
is 192.168.0.2, that of standby database 2 is 192.168.0.3, and that of the cascaded standby
database is 192.168.0.4; and assume that the database listening port is 1888 and the
communication port is 1889 for all the four databases. The procedure for installing the four
databases is as follows:

Step 1 Log in to the primary and standby databases of GaussDB 100 as user root to perform Step 2
to Step 4 below.
Step 2 Create an installation user and its user group, and configure permissions to be less than or
equal to 0750.
groupadd dbgrp
useradd -g dbgrp -d /home/gaussdba -m -s /bin/bash gaussdba

Set the password for user gaussdba.


passwd gaussdba

Step 3 Create the /opt/software/gaussdb directory for storing the installation package and the
GaussDB 100 directory /opt/gaussdb as planned.
mkdir -p /opt/software/gaussdb
mkdir -p /opt/gaussdb

Step 4 Decompress the installation package.


cd /opt/software/gaussdb
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

Step 5 On the primary node, go to the decompressed folder and run install.py.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.1 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2=SERVICE=192.168.0.2:1889 SYNC PRIMARY_ROLE" -C
"ARCHIVE_DEST_3=SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C
"ARCHIVE_DEST_4=SERVICE=192.168.0.2:1889 STANDBY_ROLE" -C CHECKPOINT_PERIOD=3 -C
SESSIONS=1500 -C REPL_WAIT_TIMEOUT=30000 -X

l Table 2-15 lists the install.py parameters that must be specified during installation. For
details about install.py, see Database Management Tools > install.py in GaussDB 100
V300R001C00 Operation Guide to Tools (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 31


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-15 install parameters


Parameter Description

-U Specifies the installation user and user group.

-R Specifies the installation path, that is, GSDB_HOME.

-D Specifies the data file path, that is, GSDB_DATA.

-C Specifies one or more configuration parameters. If no


parameter is specified, the default configuration in /home/
gaussdba/data/cfg/zengine.ini will be used.

-O Installs a single server without creating a database or starting


it.

-X Specifies that no compatible package is installed because the


simple mode is used. The compatible package is used to offer
compatibility with the view names of mainstream databases.

l During installation, you can use the default optimized configuration of zengine.ini or use
the -C parameter to replace the initial configuration. Table 2-16 describes the common
parameters that you need to pay attention to. Table 2-17 describes the parameters that
you need to pay attention to during the configuration of primary and standby databases.
NOTE

Running install.py will preliminarily check whether the memory size is valid. If the result does
not meet the installation requirements of GaussDB 100, the system will exit installation.
The memory size can be calculated as follows:
SGA_BUFF_SIZE = LOG_BUFFER_SIZE+SHARED_POOL_SIZE+DATA_BUFFER_SIZE
+TEMP_BUFFER_SIZE
The memory size (SGA_BUFF_SIZE) must be in the range [114 MB, shmmax) where shmmax
is a Linux kernel parameter and defines the maximum size of a single shared memory segment.
If -C is not used to specify the above four parameters during install.py running, their default
values will be used in the system check.

Table 2-16 zengine.ini configuration


Parameter Description Value Range Default Optimi
Value zation
Setting

TEMP_BUFFE Size of a temporary Integer (unit: 32M 1G


R_SIZE buffer byte)

DATA_BUFFE Size of a data buffer, Integer (unit: 128M 2G


R_SIZE which is used for byte)
recently accessed data

SHARED_PO Size of a shared pool Integer (unit: 128M 1G


OL_SIZE byte)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 32


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default Optimi


Value zation
Setting

LOG_BUFFER Size of a log buffer, Integer (unit: 4M 64M


_SIZE which is used for redo byte)
logs

DBWR_PROC Number of background Integer 1 8


ESSES threads for writing
dirty pages. Increasing
the value improves
concurrency efficiency
but consumes more
resources.

LOG_BUFFER Number of log buffers Integer 4 8


_COUNT

LSNR_ADDR IPv4 address of the IP address 127.0.0.1 -


listening server

LSNR_PORT Number of the Integer, in the 1611 -


listening port range [1024,
65535]

SESSIONS Maximum number of Integer, in the 200 1500


concurrent sessions range [64, 8192]

Table 2-17 Configuration parameters of primary and standby databases


Parameter Description Value Range Default
Value

REPL_PORT Specifies a port on a standby 0, or in the range 0,


node for primary-standby [1024, 65535] indicating
communication. that the
port is not
listened
and no
lsnr
thread is
started on
it. To
listen to
the port,
select a
value
from the
range
[1024,
65535].

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 33


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

ARCHIVE_DE Log archiving path. This String None


ST_2 parameter allows for two
attributes, LOCATION and
SERVICE. SERVICE is
applicable only to HA
clusters. It specifies the IP
address and port number of a
peer end as well as the log
synchronization mode. In an
HA cluster,
ARCHIVE_DEST_1 uses
LOCATION by default to set
a local destination for log
archiving; and
ARCHIVE_DEST_2 to
ARCHIVE_DEST_10 can
use SERVICE.
– SYNC: synchronous mode
– ASYNC: asynchronous
mode
– PRIMARY_ROLE:
ARCHIVE_DEST_n
takes effect only when an
instance is primary.
– STANDBY_ROLE:
ARCHIVE_DEST_n
takes effect only when an
instance is standby.
– ALL_ROLES:
ARCHIVE_DEST_n
takes effect no matter
whether an instance is
primary or standby.
– ZSTD: zstd compression
is enabled. (Logs are
compressed by using the
zstd compression
algorithm before being
sent.)
– LZ4: lz4 compression is
enabled. (Logs are
compressed by using the
lz4 compression algorithm
before being sent.)
Set this parameter for both the
primary and standby

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 34


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

databases. The IP address is


the IP address of the peer end.
If the machine where a
primary database resides has
multiple NICs or one NIC has
multiple IP addresses, you
need to configure the
LOCAL_HOST attribute to
specify the IP address bound
to the primary database when
it connects to a standby
database.
The format is as follows:
ARCHIVE_DEST_2={ SERV
ICE=ip:port [SYNC |
ASYNC] [PRIMARY_ROLE
| STANDBY_ROLE |
ALL_ROLES] [ZSTD | LZ4]
[LOCAL_HOST=ip] }

ARCHIVE_DE Availability status of the Value range: ENABLE


ST_STATE_n target ARCHIVE_DEST_n ARCHIVE_DEST_S
TATE_[1 | 2 | 3 | 4 | 5
| 6 | 7 | 8 | 9 | 10 ]=
{ ENABLE | DEFER
| ALTERNATE }
ENABLE indicates
that the destination
can be used for a
subsequent archiving
operation. DEFER
and ALTERNATE
indicate that the
destination does not
take effect.

CHECKPOINT Checkpoint execution interval Integer (unit: 300


_PERIOD second). The default
value is 300, and the
minimum value is 1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 35


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

REPL_WAIT_T If no message is exchanged an integer, in the 10


IMEOUT between primary and standby range [3, 2^32 – 1]
nodes within the period (unit: second)
specified by
REPL_WAIT_TIMEOUT,
the primary-standby link will
be considered abnormal, and
the primary or standby node
will proactively disconnect
from each other

For details about parameters, see section "Parameters" in GaussDB 100 V300R001C00
Database Reference (Standalone).
l Running install.py creates a default database based on the database creation template. If
you need to customize a database, modify the template first.
The save path of the template is /opt/software/gaussdb/GAUSSDB100-V300R001C00-
DATABASE-EULER20SP8-64bit/GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit/admin/scripts/create_database.sample.sql.
The database creation template is as follows:
CREATE DATABASE gauss CHARACTER SET binary CONTROLFILE
('?/data/cntl1',
'?/data/cntl2',
'?/data/cntl3')
LOGFILE
('?/data/log1' size 2G,
'?/data/log2' size 2G,
'?/data/log3' size 2G,
'?/data/log4' size 2G,
'?/data/log5' size 2G,
'?/data/log6' size 2G)
SYSTEM TABLESPACE DATAFILE
'?/data/system' size 1G
UNDO TABLESPACE DATAFILE
'?/data/undo' size 1G
DEFAULT TABLESPACE DATAFILE
'?/data/user1' size 1G autoextend on next 32M,
'?/data/user2' size 1G autoextend on next 32M,
'?/data/user3' size 1G autoextend on next 32M,
'?/data/user4' size 1G autoextend on next 32M,
'?/data/user5' size 1G autoextend on next 32M
TEMPORARY TABLESPACE TEMPFILE
'?/data/temp1' size 160M autoextend on next 32M,
'?/data/temp2' size 160M autoextend on next 32M
NOLOGGING TABLESPACE TEMPFILE
'?/data/temp2_01' size 160M autoextend on next 32M
NOLOGGING UNDO TABLESPACE TEMPFILE
'?/data/temp2_undo' size 160M autoextend on next 32M
ARCHIVELOG;
When you manually create a database creation template, the constraints on file
parameters are as follows:
– CONTROLFILE: Specifies a control file. The minimum number of control files is
2, and the file size is always 10 MB.
– LOGFILE: Specifies a log file. The minimum number of log files is 3, and the
minimum file size is 56 MB plus 16 KB plus the value of LOG_BUFFER_SIZE.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 36


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

– SYSTEM TABLESPACE DATAFILE: Specifies the size of a data file in the


SYSTEM tablespace. The value range is [128 MB, 8 TB].
– UNDO TABLESPACE DATAFILE: Specifies the size of a data file in the UNDO
tablespace. The value range is [128 MB, 32 GB].
– DEFAULT TABLESPACE DATAFILE: Specifies the size of a data file in the
USERS tablespace (default). The value range is [1 MB, 8 TB].
– TEMPORARY TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP tablespace. The value range is [5 MB, 8 TB].
– NOLOGGING TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP2 tablespace. The value range is [1 MB, 8 TB].
– NOLOGGING UNDO TABLESPACE TEMPFILE: Specifies the size of a data
file in the TEMP2_UNDO tablespace. The value range is [128 MB, 32 GB].
– If AUTOEXTEND ON is specified, the following attributes can be set:
n NEXT: Specifies the extension size. If this parameter is not set, the default
value 16MB will be used.
n MAXSIZE: Specifies the upper limit of extension.
○ If this parameter is omitted or is set to UNLIMITED, the maximum size
of the UNDO tablespace will be 32 GB, and that of other tablespaces will
be 8 TB.
○ The parameter value cannot be greater than 32 GB for the UNDO
tablespace, and cannot be greater than 8 TB for other tablespaces.
○ The value of MAXSIZE must be no less than that of NEXT.

Step 6 On standby node 1, go to the decompressed folder and run install.py with the -O parameter
specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.2 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.1:1889 STANDBY_ROLE" -O -X

Step 7 On standby node 2, go to the decompressed folder and run install.py with the -O parameter
specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.3 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.4:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.4:1889 STANDBY_ROLE" -O -X

Step 8 On the cascaded standby node, go to the decompressed folder and run install.py with the -O
parameter specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.4 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.3:1889 STANDBY_ROLE" -O -X

Step 9 Rebuild the databases on the two standby nodes and the cascaded standby node.
su - gaussdba
cd /opt/gaussdb/app/bin
python zctl.py -t build

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 37


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

NOTE

In this step, you must strictly follow the sequence of standby and cascaded standby nodes.

Step 10 Check whether the primary/standby relationship is successfully created on the primary,
standby, and cascaded standby nodes.
zsql SYS/Changeme_123@127.0.0.1:1888

The default administrator of GaussDB 100 is SYS and its default password is
Changeme_123. To ensure information security, change the password of SYS as soon as
possible. For more connection modes, see Connecting to a Database.
SELECT DATABASE_ROLE FROM DV_DATABASE;

l PRIMARY: primary database


l PHYSICAL_STANDBY: standby database
l CASCADED_PHYSICAL_STANDBY: cascaded standby database
NOTE

For details about how to configure security hardening after a database is installed, see GaussDB
100 V300R001C00 Security Hardening Guide (Standalone).

Step 11 Change the password of the database administrator SYS for the primary database.
ALTER USER SYS IDENTIFIED BY database_123 REPLACE Changeme_123;

In this command, database_123 is the new password of SYS. After the password is changed
for the primary database, the passwords of the users for standby and cascaded standby
databases will be automatically changed, and no manual change is needed.

----End

2.6 Standalone HA Installation (Compatible Mode)


Scenario
In GaussDB 100, you can deploy one primary database with multiple standby databases, or
one primary database with multiple standby and cascaded standby databases. A maximum of
nine standby databases and nine cascaded standby databases are supported.
The Primary role in GaussDB 100 is the primary database in a primary/standby relationship,
that is, the direct processing database of services. It communicates with a standby database
and synchronizes logs to the standby database. The Standby role is a standby database in a
primary/standby relationship, and is in the read-only state. It mainly receives logs from the
primary database and replays the service logs. When the primary database is faulty or
abnormally exits, the standby database can be promoted to primary to ensure the normal
running of services.
l One primary database with N standby databases
The primary database directly communicates with the standby databases.
– If a standby database is set to the SYNC mode, data on the standby database will be
synchronously updated when a transaction is committed on the primary database.
– If a standby database is set to the ASYNC mode, the primary database does not
wait for the standby database to receive logs when committing a transaction. When
the primary database is faulty, a standby database can be promoted to primary to
continue providing services.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 38


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l One primary database with N standby databases and N cascaded standby databases
The primary database communicates with standby databases, which in turn with
cascaded standby databases, effectively reducing the loads of the primary database.
The primary and standby databases can be set to either the SYNC or ASYNC mode, and
the standby and cascaded standby databases support only ASYNC replication. When the
primary database is faulty, a standby database can be promoted to primary. The cascaded
standby databases are only for DR purposes, and are placed remotely. They replicate data
from standby databases and have little impact on service environment performance. If
the primary database and all standby databases are faulty, a cascaded standby database
can also be promoted to primary.

This section uses one primary database, two standby databases, and one cascaded standby
database as an example to illustrate the standalone HA deployment, as shown in Figure 2-7.

Figure 2-7 One primary database, two standby databases, and one cascaded standby database

The following describes parameter configurations for the deployment of one primary database
with two standby databases and one cascaded standby database: (Instance A is used as an
example.)

l ARCHIVE_DEST_2=SERVICE=ipB:portB PRIMARY_ROLE: If instance A is


primary, it will connect to the IP address and port specified by SERVICE, that is,
instance B. If instance A is standby, the link will not be used.
l ARCHIVE_DEST_3=SERVICE=ipC:portC PRIMARY_ROLE: If instance A is
primary, it will connect to the IP address and port specified by SERVICE, that is,
instance C. If instance A is standby, the link will not be used.
l ARCHIVE_DEST_4=SERVICE=ipB:portB STANDBY_ROLE: If instance A is
standby, it will be connected to the IP address and port specified by SERVICE, that is,
instance B. If instance A is primary, the link will not be used.
NOTE

l If a database is deployed in HA mode, perform security hardening on both the primary and standby
databases.
l The compatible mode is an enhancement of the simple mode. After compatible packages are
installed, GaussDB 100 offers compatibility with the interface names of mainstream databases.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 39


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Prerequisites
l The installation has been planned following instructions provided in Planning for
Installation.
l The installation package has been uploaded to the /opt/software/ directory.
l The compatible package DIALECT-SCRIPT-xxxxx.tar.gz has been obtained and
uploaded to the same directory as the installation package.
l If a non-root user is used to install the database, ensure that this user is the owner of the
installation directory and has certain permissions (≤ 0750).
l If the firewall service is enabled on servers, ensure that the primary and standby
databases have been added to the trust zones for each other.

Precautions
l To install multiple instances on the same server, plan different listening ports and data
directories.
l Before reinstalling GaussDB 100, ensure that operations in Uninstalling a Database
have been completed. Otherwise, the reinstallation may fail.
l It is recommended that the data and log directories of primary and standby databases be
the same. If they are different, you can use the DB_FILE_NAME_CONVERT and
LOG_FILE_NAME_CONVERT parameters for conversion. Assume that the data
directory of a primary database is /home/user1/zenith_home1/data and that of a
standby database is /home/user1/zenith_home2/data. Set
DB_FILE_NAME_CONVERT to /home/user1/zenith_home2/data,/home/user1/
zenith_home1/data on the primary database and to /home/user1/zenith_home1/data,/
home/user1/zenith_home2/data on the standby database. In this way, even if the
standby database is promoted to primary, the primary/standby relationship will not be
affected.

Procedure
Assume that the IP address of the primary database is 192.168.0.1, that of standby database 1
is 192.168.0.2, that of standby database 2 is 192.168.0.3, and that of the cascaded standby
database is 192.168.0.4; and assume that the database listening port is 1888 and the
communication port is 1889 for all the four databases. The procedure for installing the four
databases is as follows:

Step 1 Log in to the primary, standby, and cascaded standby databases of GaussDB 100 as user root
to perform Step 2 to Step 5 below.

Step 2 Create an installation user and its user group, and configure permissions to be less than or
equal to 0750.
groupadd dbgrp
useradd -g dbgrp -d /home/gaussdba -m -s /bin/bash gaussdba

Set the password for user gaussdba.


passwd gaussdba

Step 3 Create the /opt/software/gaussdb directory for storing the installation package and the
GaussDB 100 directory /opt/gaussdb as planned.
mkdir -p /opt/software/gaussdb
mkdir -p /opt/gaussdb

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 40


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 4 Upload the installation package and compatible package to the created directory. The
installation package and compatible package must be stored in the same directory.
Step 5 Decompress the installation package.
cd /opt/software/gaussdb
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

Step 6 On the primary node, go to the decompressed folder and run install.py.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.1 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2=SERVICE=192.168.0.2:1889 SYNC PRIMARY_ROLE" -C
"ARCHIVE_DEST_3=SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C
"ARCHIVE_DEST_4=SERVICE=192.168.0.2:1889 STANDBY_ROLE" -C CHECKPOINT_PERIOD=3 -C
SESSIONS=1500 -C REPL_WAIT_TIMEOUT=30000

l Table 2-18 lists the install.py parameters that must be specified during installation. For
details about install.py, see Database Management Tools > install.py in GaussDB 100
V300R001C00 Operation Guide to Tools (Standalone).

Table 2-18 install parameters


Parameter Description

-U Specifies the installation user and user group.

-R Specifies the installation path, that is, GSDB_HOME.

-D Specifies the data file path, that is, GSDB_DATA.

-C Specifies one or more configuration parameters. If no


parameter is specified, the default configuration in /home/
gaussdba/data/cfg/zengine.ini will be used.

-O Installs a single server without creating a database or starting


it.

l During installation, you can use the default optimized configuration of zengine.ini or use
the -C parameter to replace the initial configuration. Table 2-19 describes the common
parameters that you need to pay attention to. Table 2-20 describes the parameters that
you need to pay attention to during the configuration of primary and standby databases.
NOTE

Running install.py will preliminarily check whether the memory size is valid. If the result does
not meet the installation requirements of GaussDB 100, the system will exit installation.
The memory size can be calculated as follows:
SGA_BUFF_SIZE = LOG_BUFFER_SIZE+SHARED_POOL_SIZE+DATA_BUFFER_SIZE
+TEMP_BUFFER_SIZE
The memory size (SGA_BUFF_SIZE) must be in the range [114 MB, shmmax) where shmmax
is a Linux kernel parameter and defines the maximum size of a single shared memory segment.
If -C is not used to specify the above four parameters during install.py running, their default
values will be used in the system check.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 41


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-19 zengine.ini configuration


Parameter Description Value Range Default Optimi
Value zation
Setting

TEMP_BUFFE Size of a temporary Integer (unit: 32M 1G


R_SIZE buffer byte)

DATA_BUFFE Size of a data buffer, Integer (unit: 128M 2G


R_SIZE which is used for byte)
recently accessed data

SHARED_PO Size of a shared pool Integer (unit: 128M 1G


OL_SIZE byte)

LOG_BUFFER Size of a log buffer, Integer (unit: 4M 64M


_SIZE which is used for redo byte)
logs

DBWR_PROC Number of background Integer 1 8


ESSES threads for writing
dirty pages. Increasing
the value improves
concurrency efficiency
but consumes more
resources.

LOG_BUFFER Number of log buffers Integer 4 8


_COUNT

LSNR_ADDR IPv4 address of the IP address 127.0.0.1 -


listening server

LSNR_PORT Number of the Integer, in the 1611 -


listening port range [1024,
65535]

SESSIONS Maximum number of Integer, in the 200 1500


concurrent sessions range [64, 8192]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 42


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Table 2-20 Configuration parameters of primary and standby databases


Parameter Description Value Range Default
Value

REPL_PORT Specifies a port on a standby 0, or in the range 0,


node for primary-standby [1024, 65535] indicating
communication. that the
port is not
listened
and no
lsnr
thread is
started on
it. To
listen to
the port,
select a
value
from the
range
[1024,
65535].

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 43


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

ARCHIVE_DE Log archiving path. This String None


ST_2 parameter allows for two
attributes, LOCATION and
SERVICE. SERVICE is
applicable only to HA
clusters. It specifies the IP
address and port number of a
peer end as well as the log
synchronization mode. In an
HA cluster,
ARCHIVE_DEST_1 uses
LOCATION by default to set
a local destination for log
archiving; and
ARCHIVE_DEST_2 to
ARCHIVE_DEST_10 can
use SERVICE.
– SYNC: synchronous mode
– ASYNC: asynchronous
mode
– PRIMARY_ROLE:
ARCHIVE_DEST_n
takes effect only when an
instance is primary.
– STANDBY_ROLE:
ARCHIVE_DEST_n
takes effect only when an
instance is standby.
– ALL_ROLES:
ARCHIVE_DEST_n
takes effect no matter
whether an instance is
primary or standby.
– ZSTD: zstd compression
is enabled. (Logs are
compressed by using the
zstd compression
algorithm before being
sent.)
– LZ4: lz4 compression is
enabled. (Logs are
compressed by using the
lz4 compression algorithm
before being sent.)
Set this parameter for both the
primary and standby

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 44


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

databases. The IP address is


the IP address of the peer end.
If the machine where a
primary database resides has
multiple NICs or one NIC has
multiple IP addresses, you
need to configure the
LOCAL_HOST attribute to
specify the IP address bound
to the primary database when
it connects to a standby
database.
The format is as follows:
ARCHIVE_DEST_2={ SERV
ICE=ip:port [SYNC |
ASYNC] [PRIMARY_ROLE
| STANDBY_ROLE |
ALL_ROLES] [ZSTD | LZ4]
[LOCAL_HOST=ip] }

ARCHIVE_DE Availability status of the Value range: ENABLE


ST_STATE_n target ARCHIVE_DEST_n ARCHIVE_DEST_S
TATE_[1 | 2 | 3 | 4 | 5
| 6 | 7 | 8 | 9 | 10 ]=
{ ENABLE | DEFER
| ALTERNATE }
ENABLE indicates
that the destination
can be used for a
subsequent archiving
operation. DEFER
and ALTERNATE
indicate that the
destination does not
take effect.

CHECKPOINT Checkpoint execution interval Integer (unit: 300


_PERIOD second). The default
value is 300, and the
minimum value is 1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 45


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Parameter Description Value Range Default


Value

REPL_WAIT_T If no message is exchanged an integer, in the 10


IMEOUT between primary and standby range [3, 2^32 – 1]
nodes within the period (unit: second)
specified by
REPL_WAIT_TIMEOUT,
the primary-standby link will
be considered abnormal, and
the primary or standby node
will proactively disconnect
from each other

For details about parameters, see section "Parameters" in GaussDB 100 V300R001C00
Database Reference (Standalone).
l Running install.py creates a default database based on the database creation template. If
you need to customize a database, modify the template first.
The save path of the template is /opt/software/gaussdb/GAUSSDB100-V300R001C00-
DATABASE-EULER20SP8-64bit/GAUSSDB100-V300R001C00-RUN-
EULER20SP8-64bit/admin/scripts/create_database.sample.sql.
The database creation template is as follows:
CREATE DATABASE gauss CHARACTER SET binary CONTROLFILE
('?/data/cntl1',
'?/data/cntl2',
'?/data/cntl3')
LOGFILE
('?/data/log1' size 2G,
'?/data/log2' size 2G,
'?/data/log3' size 2G,
'?/data/log4' size 2G,
'?/data/log5' size 2G,
'?/data/log6' size 2G)
SYSTEM TABLESPACE DATAFILE
'?/data/system' size 1G
UNDO TABLESPACE DATAFILE
'?/data/undo' size 1G
DEFAULT TABLESPACE DATAFILE
'?/data/user1' size 1G autoextend on next 32M,
'?/data/user2' size 1G autoextend on next 32M,
'?/data/user3' size 1G autoextend on next 32M,
'?/data/user4' size 1G autoextend on next 32M,
'?/data/user5' size 1G autoextend on next 32M
TEMPORARY TABLESPACE TEMPFILE
'?/data/temp1' size 160M autoextend on next 32M,
'?/data/temp2' size 160M autoextend on next 32M
NOLOGGING TABLESPACE TEMPFILE
'?/data/temp2_01' size 160M autoextend on next 32M
NOLOGGING UNDO TABLESPACE TEMPFILE
'?/data/temp2_undo' size 160M autoextend on next 32M
ARCHIVELOG;
When you manually create a database creation template, the constraints on file
parameters are as follows:
– CONTROLFILE: Specifies a control file. The minimum number of control files is
2, and the file size is always 10 MB.
– LOGFILE: Specifies a log file. The minimum number of log files is 3, and the
minimum file size is 56 MB plus 16 KB plus the value of LOG_BUFFER_SIZE.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 46


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

– SYSTEM TABLESPACE DATAFILE: Specifies the size of a data file in the


SYSTEM tablespace. The value range is [128 MB, 8 TB].
– UNDO TABLESPACE DATAFILE: Specifies the size of a data file in the UNDO
tablespace. The value range is [128 MB, 32 GB].
– DEFAULT TABLESPACE DATAFILE: Specifies the size of a data file in the
USERS tablespace (default). The value range is [1 MB, 8 TB].
– TEMPORARY TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP tablespace. The value range is [5 MB, 8 TB].
– NOLOGGING TABLESPACE TEMPFILE: Specifies the size of a data file in
the TEMP2 tablespace. The value range is [1 MB, 8 TB].
– NOLOGGING UNDO TABLESPACE TEMPFILE: Specifies the size of a data
file in the TEMP2_UNDO tablespace. The value range is [128 MB, 32 GB].
– If AUTOEXTEND ON is specified, the following attributes can be set:
n NEXT: Specifies the extension size. If this parameter is not set, the default
value 16MB will be used.
n MAXSIZE: Specifies the upper limit of extension.
○ If this parameter is omitted or is set to UNLIMITED, the maximum size
of the UNDO tablespace will be 32 GB, and that of other tablespaces will
be 8 TB.
○ The parameter value cannot be greater than 32 GB for the UNDO
tablespace, and cannot be greater than 8 TB for other tablespaces.
○ The value of MAXSIZE must be no less than that of NEXT.

Step 7 On standby node 1, go to the decompressed folder and run install.py with the -O parameter
specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.2 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.1:1889 STANDBY_ROLE" -O

Step 8 On standby node 2, go to the decompressed folder and run install.py with the -O parameter
specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.3 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.4:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.4:1889 STANDBY_ROLE" -O

Step 9 On the cascaded standby node, go to the decompressed folder and run install.py with the -O
parameter specified.
cd GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
python install.py -U gaussdba:dbgrp -R /opt/gaussdb/app -D /opt/gaussdb/data -C
LSNR_ADDR=127.0.0.1,192.168.0.4 -C LSNR_PORT=1888 -C REPL_PORT=1889 -C
"ARCHIVE_DEST_2 = SERVICE=192.168.0.3:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_3
= SERVICE=192.168.0.1:1889 SYNC PRIMARY_ROLE" -C "ARCHIVE_DEST_4 =
SERVICE=192.168.0.3:1889 STANDBY_ROLE" -O

Step 10 Rebuild the databases on the two standby nodes and the cascaded standby node.
su - gaussdba
cd /opt/gaussdb/app/bin
python zctl.py -t build

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 47


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

NOTE

In this step, you must strictly follow the sequence of standby and cascaded standby nodes.

Step 11 Check whether the primary/standby relationship is successfully created on the primary,
standby, and cascaded standby nodes.
zsql SYS/Changeme_123@127.0.0.1:1888

The default administrator of GaussDB 100 is SYS and its default password is
Changeme_123. To ensure information security, change the password of SYS as soon as
possible. For more connection modes, see Connecting to a Database.
SELECT DATABASE_ROLE FROM DV_DATABASE;

l PRIMARY: primary database


l PHYSICAL_STANDBY: standby database
l CASCADED_PHYSICAL_STANDBY: cascaded standby database
NOTE

For details about how to configure security hardening after a database is installed, see GaussDB
100 V300R001C00 Security Hardening Guide (Standalone).

Step 12 Change the password of the database administrator SYS for the primary database.
ALTER USER SYS IDENTIFIED BY database_123 REPLACE Changeme_123;

In this command, database_123 is the new password of SYS. After the password is changed
for the primary database, the passwords of the users for standby and cascaded standby
databases will be automatically changed, and no manual change is needed.

----End

2.7 Uninstalling a Database


Scenario
This section describes how to uninstall GaussDB 100 when it is not required or needs to be
reinstalled. If you need to retain the data in GaussDB 100, back up its data directory before
uninstalling it.

Prerequisites
The database has been correctly installed.

Procedure
Step 1 Log in to a server where GaussDB 100 is deployed as user gaussdba.

Step 2 Go to the bin folder in the installation directory and execute the uninstallation script
uninstall.py:
cd $GSDB_HOME/bin
python uninstall.py -U gaussdba -F -D $GSDB_DATA -g withoutroot

If the uninstallation is successful, the following information will be printed:


Zengine was successfully removed from your computer, for more message please see /
home/gaussdba/zengineuninstall.log.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 48


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

The uninstallation log is ~/zengineuninstall.log. For details about uninstall.py, see Database
Management Tools > uninstall.py in GaussDB 100 V300R001C00 Operation Guide to Tools
(Standalone).

----End

2.8 Upgrading a Database


Scenario
GaussDB 100 supports minor version upgrades, that is, the versions before and after an
upgrade must be adjacent C versions. To ensure database security and stability, upgrade the
database version each time a patch package is released. An upgrade involves both binary files
and system catalogs. For details about upgrade procedures, see Procedure (Standalone
Automatic Upgrade), Procedure (HA Automatic Upgrade), Procedure (Standalone
Manual Upgrade), and Procedure (HA Manual Upgrade).

Prerequisites
l Upgrades are supported only between adjacent C versions. Ensure that the target and
source versions are adjacent C versions. If an upgrade across multiple versions is needed,
perform an upgrade for each version in sequence. If the database versions before and
after an upgrade are the same, the upgrade is not supported.
l Reserve 10 to 60 minutes for an upgrade. Upgrade time depends on hardware
performance in the product environment, service load before service stop, and network
performance between primary and standby databases.
l Back up important data before an upgrade. A full backup is recommended.
l Ensure that the reserved space of a disk where the target database is deployed is no less
than the space occupied by system catalog files. (The reserved space is for backup
operations.) Otherwise, the upgrade will fail.
l The lsof tool has been installed in the system.
l The Python version is 2.7.*.
l Before an upgrade, prepare the installation package for the upgrade and verify the
integrity of the installation package. For details about how to verify an installation
package, see Obtaining and Verifying an Installation Package.
l Ensure that the database user (for example, gaussdba) has certain permissions for the
upgrade installation package (≤ 0750). Otherwise, the upgrade will fail and rollback will
be needed.
l Before an upgrade, ensure that the database instance is running properly, can be started
and stopped, and can perform services. Otherwise, the upgrade will fail and rollback will
be needed.
l Services must be stopped before an upgrade.
l No other control software (such as CloudSOP or DBM) is used to stop or start database
instances; perform primary/standby switchovers, disaster recovery, and backup; or
trigger scheduled jobs. If there is such software, the upgrade may fail and rollback
cannot be performed.
l Ensure that the network between primary and standby databases is normal before an HA
upgrade. Otherwise, the upgrade will fail and rollback will be needed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 49


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l For an HA manual upgrade, ensure a consistent password for user SYS of different
database instances started from the same program directory. Otherwise, the upgrade will
fail.
l For an HA automatic upgrade, ensure a consistent password for user SYS of different
database instances that need to be upgraded on all nodes. Otherwise, the upgrade will
fail.
l For an HA automatic upgrade, the mutual trust relationships must be consistently
configured between nodes. That is, each node must either have or not have a mutual trust
relationship. If there is an inconsistency, the upgrade will fail.
l For an HA automatic upgrade, the value of ChallengeResponseAuthentication
in /etc/ssh/sshd_config must be no. Otherwise, the execution of pre-check will fail.
l A compatible package must be installed for an upgraded database. The package is
compatible with the view names of mainstream databases, without affecting users.

Precautions
If password-free login is disabled on zsql, you need to use the formal parameter -P to enter
the password for an upgrade.

Procedure (Standalone Automatic Upgrade)


Automatic upgrade is supported in standalone scenarios. During an automatic upgrade, you
need to run the upgrade command for only once on the node.
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the installation package of the target version and the compatible package DIALECT-
SCRIPT-xxxxx.tar.gz to the same directory.
Step 3 Decompress the installation package of the target version and obtain the upgrade script
upgrade.py.
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).
Step 4 Configure an upgrade file config_file.ini.
The config_file.ini file needs to be created manually. Assume that the IP address of the node
where the standalone database resides is 192.168.0.1. The format of the node configuration is
as follows:
192.168.0.1=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data

l 192.168.0.1 is the IP address of the database server.


l /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz is the absolute path of the upgrade package.
l /opt/gaussdb/app is the installation path of the database.
l /opt/gaussdb/backup is the directory for storing backup files during the upgrade.
l /opt/gaussdb/data is the data file directory of the database instance. When multiple
instances are installed, the database instances that are started from the same installation
directory must be upgraded at a time. In this case, you need to specify the data
directories of multiple database instances. Use commas (,) to separate the directories.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 50


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 5 Go to the directory where upgrade.py is stored.


cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

Step 6 (Optional) Obtain the upgrade type before the upgrade.


When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the
data directories of multiple database instances, separated by commas (,). The /opt/gaussdb/
backup directory specified by --backupdir needs to be manually created.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 Check the upgrade environment.


python upgrade.py -s pre-check --config-file=/opt/gaussdb/config_file.ini
--upgrade-mode=single

Step 8 Perform a one-click upgrade.


python upgrade.py -s run --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=single

If the upgrade fails, you need to perform rollback and then run the upgrade command again.
For details about the rollback procedure, see Procedure (Standalone Automatic Rollback).

Step 9 Delete the configurations.


python upgrade.py -s cleanup --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=single

----End

Procedure (HA Automatic Upgrade)


Automatic upgrade is supported in HA scenarios. During an automatic upgrade, you need to
run the upgrade command for only once on the primary node. During an automatic upgrade,
the upgrade tool automatically checks whether mutual trust relationships have been
established between nodes in the HA environment. If no relationship has been established, the
upgrade tool will automatically establish the relationships for the nodes.

The following steps must be performed on the same node.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the installation package of the target version and the compatible package DIALECT-
SCRIPT-xxxxx.tar.gz to the same directory.
Step 3 Decompress the installation package of the target version and obtain the upgrade script
upgrade.py.
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Step 4 Configure an upgrade file config_file.ini.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 51


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

The config_file.ini file needs to be created manually. For an HA automatic upgrade, you need
to add information about each node. The configuration information of each node is in a
separate line, and the configuration information in the first line must be about the node for
running the upgrade command. Information behind the equal sign (=) must be arranged in the
following sequence: Upgrade package path, Database installation path, Backup path,
Database instance data file path.
Assume that the HA deployment involves nodes 192.168.0.1, 192.168.0.2, and 192.168.0.3
and that the upgrade command will be executed on node 192.168.0.1. The format of the node
configuration is as follows:
192.168.0.1=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data
192.168.0.2=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data
192.168.0.3=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data

l 192.168.0.1, 192.168.0.2, and 192.168.0.3 are the IP addresses of database servers.


l /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz is the absolute path of the upgrade package.
l /opt/gaussdb/app is the installation path of the database.
l /opt/gaussdb/backup is the directory for storing backup files during the upgrade.
l /opt/gaussdb/data is the data file directory of the database instance. When multiple
instances are installed, the database instances that are started from the same installation
directory must be upgraded at a time. In this case, you need to specify the data
directories of multiple database instances. Use commas (,) to separate the directories.

Step 5 Go to the directory where upgrade.py is stored.


cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

Step 6 (Optional) Obtain the upgrade type before the upgrade.


When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the
data directories of multiple database instances, separated by commas (,). The /opt/gaussdb/
backup directory specified by --backupdir needs to be manually created.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 Perform the upgrade check and prepare the upgrade package and environment for remote
nodes.
python upgrade.py -s pre-check --config-file=/opt/gaussdb/config_file.ini --
upgrade-mode=ha

Step 8 Perform a one-click upgrade.


python upgrade.py -s run --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=ha

If the upgrade fails, you need to perform rollback and then run the upgrade command again.
For details about the rollback procedure, see Procedure (HA Automatic Rollback).

Step 9 Delete the configurations.


python upgrade.py -s cleanup --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=ha

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 52


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Procedure (Standalone Manual Upgrade)


Manual upgrade is supported in standalone scenarios. During a manual upgrade, you need to
separately perform several upgrade steps.

A standalone manual upgrade consists of nine steps: pretest, precheck, prepare, replace,
start, upgrade, sync, dbcheck, and flush. The specific procedure is as follows:

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Upload the installation package of the target version and the compatible package DIALECT-
SCRIPT-xxxxx.tar.gz to the same directory.

Step 3 Decompress the installation package of the target version and obtain the upgrade script
upgrade.py.
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In 5 through 14, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The two
parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment variables.
If the first two parameters are not specified, the default configuration in the environment variables
will be used.
l The generated log file is upgrade.log, which is stored in the backup directory specified by --
backupdir=/opt/gaussdb/backup. Rollback is needed if any step from 7 to 14 in a standalone
manual upgrade fails. It is not needed if 6 (pretest) fails. For details about the rollback procedure,
see Procedure (Standalone Manual Rollback).

Step 4 Go to the directory where upgrade.py is stored.


cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

Step 5 (Optional) Run the upgrade-type command to obtain the upgrade type.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 6 (Optional) Run the pretest command to examine whether the current database environment is
suitable for the upgrade.
python upgrade.py -t pretest --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 Run the precheck command.


python upgrade.py -t precheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Run the prepare command.


python upgrade.py -t prepare --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 9 Run the replace command.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 53


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

python upgrade.py -t replace --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/


gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 10 Run the start command.


python upgrade.py -t start --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 11 Run the upgrade command.


python upgrade.py -t upgrade --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 12 Run the sync command.


python upgrade.py -t sync --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 13 Run the dbcheck command.


python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 14 Run the flush command.


python upgrade.py -t flush --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

----End

Procedure (HA Manual Upgrade)


Manual upgrade is supported in HA scenarios. During a manual upgrade, you need to perform
several upgrade steps on each node involved in the HA deployment.
An HA manual upgrade consists of nine steps: pretest, precheck, prepare, replace, start,
upgrade, sync, dbcheck, and flush. The specific procedure is as follows:

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the installation package of the target version and the compatible package DIALECT-
SCRIPT-xxxxx.tar.gz to the same directory on all physical machines where primary and
standby databases are installed.

Step 3 Decompress the installation package of the target version and obtain the upgrade script
upgrade.py on all physical machines where primary and standby databases are installed.
tar -zxvf GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.tar.gz

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 54


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In 5 through 14, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The two
parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment variables.
If the first two parameters are not specified, the default configuration in the environment variables
will be used.
l The generated log file is upgrade.log, which is stored in the backup directory specified by --
backupdir=/opt/gaussdb/backup. Rollback is needed if any step from 7 to 14 in an HA manual
upgrade fails. It is not needed if 6 (pretest) fails. For details about the rollback procedure, see
Procedure (HA Manual Rollback).

Step 4 Go to the directory where upgrade.py is stored on all physical machines where primary and
standby databases are installed.
cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

Step 5 (Optional) Run the upgrade-type command on the current physical machine to obtain the
upgrade type.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 6 (Optional) Run the pretest command on all physical machines where primary and standby
databases are installed to check whether the current database environment is suitable for the
upgrade.
python upgrade.py -t pretest --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 Run the precheck command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t precheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Run the prepare command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t prepare --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 9 Run the replace command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t replace --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 10 Run the start command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t start --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 11 Run the upgrade command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t upgrade --GSDB_HOME=/home/gaussdba/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 55


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 12 Run the sync command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t sync --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 13 Run the dbcheck command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/home/gaussdba/up_out

Step 14 Run the flush command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t flush --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

----End

2.9 Downgrading a Database


Scenario
GaussDB 100 supports minor version downgrades, that is, the versions before and after a
downgrade must be adjacent C versions. If the new version is abnormal after an upgrade, you
need to downgrade the database to roll back the version. Before a downgrade, contact Huawei
technical support to check whether the target database supports downgrades. For details about
downgrade procedures, see Procedure (Standalone Automatic Downgrade), Procedure
(HA Automatic Downgrade), Procedure (Standalone Manual Downgrade), and
Procedure (HA Manual Downgrade). This function must be used with caution.

Prerequisites
l Downgrades are supported only between adjacent C versions. Ensure that the target and
source versions are adjacent C versions. If a downgrade across multiple versions is
needed, perform a downgrade for each version in sequence. If the database versions
before and after a downgrade are the same, the downgrade is not supported.
l Reserve 10 to 60 minutes for a downgrade. Downgrade time depends on hardware
performance in the product environment, service load before service stop, and network
performance between primary and standby databases.
l Back up important data before a downgrade. A full backup is recommended.
l The reserved space of a disk where the target database is deployed is no less than the
space occupied by system catalog files. (The reserved space is for backup operations.)
Otherwise, the downgrade will fail.
l The lsof tool has been installed in the system.
l The Python version is 2.7.*.
l Before a downgrade, prepare the installation package for the downgrade and verify the
integrity of the installation package. For details about how to verify an installation
package, see Obtaining and Verifying an Installation Package.
l Ensure that the database user (for example, gaussdba) has certain permissions for the
downgrade installation package (≤ 0750). Otherwise, the downgrade will fail and
rollback will be needed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 56


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

l Before a downgrade, ensure that the database instance is running properly, can be started
and stopped, and can perform services. Otherwise, the downgrade will fail and rollback
will be needed.
l Services must be stopped before a downgrade.
l No other control software (such as CloudSOP or DBM) is used to stop or start database
instances; perform primary/standby switchovers, disaster recovery, and backup; or
trigger scheduled jobs. If there is such software, the downgrade may fail and rollback
cannot be performed.
l Ensure that the network between primary and standby databases is normal before an HA
downgrade. Otherwise, the downgrade will fail and rollback will be needed.
l For an HA manual downgrade, ensure a consistent password for user SYS of different
database instances started from the same program directory. Otherwise, the downgrade
will fail.
l For an HA automatic downgrade, ensure a consistent password for user SYS of different
database instances that need to be downgraded on all nodes. Otherwise, the downgrade
will fail.
l For an HA automatic downgrade, the mutual trust relationships must be consistently
configured between nodes. That is, each node must either have or not have a mutual trust
relationship. If there is an inconsistency, the downgrade will fail.
l For an HA automatic downgrade, the value of ChallengeResponseAuthentication
in /etc/ssh/sshd_config must be no. Otherwise, the execution of pre-check will fail.
l If a downgrade package supports the compatible package, the degraded database will be
in compatible mode.
l Before downgrading a database, ensure that the database is running properly.

Precautions
l If password-free login is disabled on zsql, you need to use the formal parameter -P to
enter the password for a downgrade.
l For a downgraded database, the next upgrade must use a version of the installation
package later than that before the downgrade.

Procedure (Standalone Automatic Downgrade)


Automatic downgrade is supported in standalone scenarios. During an automatic downgrade,
you need to run the downgrade command for only once on the node.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the downgrade installation package.
You must have the read, write, and execute permissions for the directory where the
downgrade installation package is stored. If the downgraded version supports the compatible
package, you need to upload the installation package of the downgraded version and the
compatible package DIALECT-SCRIPT-3.1.0.0.0.tar.gz to the same directory.
Step 3 Create the upgradetool folder in the installation directory of the current database to store the
tool scripts used for the downgrade.
cd $GSDB_HOME
mkdir upgradetool
chmod 700 upgradetool

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 57


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 4 Copy upgrade.py, sshexkey.py, and funclib.py in the installation package of the current
database to the created upgradetool folder.

Assume that the installation package path of the current database is /opt/gaussdb/
GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.
cd /opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
cp upgrade.py sshexkey.py funclib.py $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Step 5 Configure a downgrade file config_file.ini.

The config_file.ini file needs to be created manually. Assume that the IP address of the node
where the standalone database resides is 192.168.0.1. The format of the node configuration is
as follows:
192.168.0.1=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data

l 192.168.0.1 is the IP address of the database server.


l /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz is the absolute path of the downgrade package.
l /opt/gaussdb/app is the installation path of the database.
l /opt/gaussdb/backup is the directory for storing backup files during the downgrade. It
needs to be manually created in advance.
l /opt/gaussdb/data is the data file directory of the database instance. When multiple
instances are installed, the database instances that are started from the same installation
directory must be downgraded at a time. In this case, you need to specify the data
directories of multiple database instances. Use commas (,) to separate the directories.

Step 6 Go to the directory where upgrade.py is stored.


cd $GSDB_HOME/upgradetool

Step 7 (Optional) Obtain the downgrade type before the downgrade.

When multiple instances are installed, the database instances that are started from the same
installation directory must be downgraded at a time. In this case, --GSDB_DATA specifies
the data directories of multiple database instances, separated by commas (,). The /home/
gaussdba/up_out directory specified by --backupdir needs to be manually created.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Check the downgrade environment.


python upgrade.py -s pre-check --config-file=/opt/gaussdb/config_file.ini
--upgrade-mode=single

Step 9 Perform a one-click downgrade.


python upgrade.py -s run --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=single

If the downgrade fails, you need to perform rollback and then run the downgrade command
again. For details about the rollback procedure, see Procedure (Standalone Automatic
Rollback).

Step 10 Delete the configurations.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 58


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

python upgrade.py -s cleanup --config-file=/opt/gaussdb/config_file.ini --upgrade-


mode=single

----End

Procedure (HA Automatic Downgrade)


Automatic downgrade is supported in HA scenarios. During an automatic downgrade, you
need to run the downgrade command for only once on the primary node. During an automatic
downgrade, the downgrade tool automatically checks whether mutual trust relationships have
been established between nodes in the HA environment. If no relationship has been
established, the downgrade tool will automatically establish the relationships for the nodes.

The following steps must be performed on the same node.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the downgrade installation package.
You must have the read, write, and execute permissions for the directory where the
downgrade installation package is stored. If the downgraded version supports the compatible
package, you need to upload the installation package of the downgraded version and the
compatible package DIALECT-SCRIPT-3.1.0.0.0.tar.gz to the same directory.
Step 3 Create the upgradetool folder in the installation directory of the current database to store the
tool scripts used for the downgrade.
cd $GSDB_HOME
mkdir upgradetool
chmod 700 upgradetool

Step 4 Copy upgrade.py, sshexkey.py, and funclib.py in the installation package of the current
database to the created upgradetool folder.
Assume that the installation package path of the current database is /opt/gaussdb/
GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.
cd /opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
cp upgrade.py sshexkey.py funclib.py $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Step 5 Configure a downgrade file config_file.ini.


The config_file.ini file needs to be created manually. For an HA automatic downgrade, you
need to add information about each node. The configuration information of each node is in a
separate line, and the configuration information in the first line must be about the node for
running the downgrade command. Information behind the equal sign (=) must be arranged in
the following sequence: Downgrade package path, Database installation path, Backup path,
Database instance data path.
Assume that the HA deployment involves nodes 192.168.0.1, 192.168.0.2, and 192.168.0.3
and that the downgrade command will be executed on node 192.168.0.1. The format of the
node configuration is as follows:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 59


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

192.168.0.1=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data
192.168.0.2=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data
192.168.0.3=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz,/opt/gaussdb/app,/opt/gaussdb/backup,/opt/gaussdb/data

l 192.168.0.1, 192.168.0.2, and 192.168.0.3 are the IP addresses of database servers.


l /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz is the absolute path of the downgrade package.
l /opt/gaussdb/app is the installation path of the database.
l /opt/gaussdb/backup is the directory for storing backup files during the downgrade.
l /opt/gaussdb/data is the data file directory of the database instance. When multiple
instances are installed, the database instances that are started from the same installation
directory must be downgraded at a time. In this case, you need to specify the data
directories of multiple database instances. Use commas (,) to separate the directories.

Step 6 Go to the directory where upgrade.py is stored.


cd $GSDB_HOME/upgradetool

Step 7 (Optional) Obtain the downgrade type before the downgrade.

When multiple instances are installed, the database instances that are started from the same
installation directory must be downgraded at a time. In this case, --GSDB_DATA specifies
the data directories of multiple database instances, separated by commas (,). The /home/
gaussdba/up_out directory specified by --backupdir needs to be manually created.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Perform the downgrade check and prepare the downgrade package and environment for
remote nodes.
python upgrade.py -s pre-check --config-file=/opt/gaussdb/config_file.ini --
upgrade-mode=ha

Step 9 Perform a one-click downgrade.


python upgrade.py -s run --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=ha

If the downgrade fails, you need to perform rollback and then run the downgrade command
again. For details about the rollback procedure, see Procedure (HA Automatic Rollback).

Step 10 Delete the configurations.


python upgrade.py -s cleanup --config-file=/opt/gaussdb/config_file.ini --upgrade-
mode=ha

----End

Procedure (Standalone Manual Downgrade)


Manual downgrade is supported in standalone scenarios. During a manual downgrade, you
need to separately perform several downgrade steps.

A standalone manual downgrade consists of 12 steps: pretest, precheck, prepare, replace,


start, upgrade, sync, restart, upgrade-view, checkpoint, dbcheck, and flush. The specific
procedure is as follows:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 60


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Upload the downgrade installation package.
You must have the read, write, and execute permissions for the directory where the
downgrade installation package is stored. If the downgraded version supports the compatible
package, you need to upload the installation package of the downgraded version and the
compatible package DIALECT-SCRIPT-3.1.0.0.0.tar.gz to the same directory.

Step 3 Create the upgradetool folder in the installation directory of the current database to store the
tool scripts used for the downgrade.
cd $GSDB_HOME
mkdir upgradetool
chmod 700 upgradetool

Step 4 Copy upgrade.py, sshexkey.py, and funclib.py in the installation package of the current
database to the created upgradetool folder.
Assume that the installation package path of the current database is /opt/gaussdb/
GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.
cd /opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
cp upgrade.py sshexkey.py funclib.py $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be downgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In 6 through 18, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The two
parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment variables.
If the first two parameters are not specified, the default configuration in the environment variables
will be used.
l The generated log file is upgrade.log, which is stored in the backup directory specified by --
backupdir=/opt/gaussdb/backup. Rollback is needed if any step from 8 to 18 in a standalone
manual downgrade fails. It is not needed if 7 (pretest) fails. For details about the rollback procedure,
see Procedure (Standalone Manual Rollback).

Step 5 Go to the directory where upgrade.py is stored, that is, the manually created upgradetool
folder.
cd $GSDB_HOME/upgradetool

Step 6 (Optional) Run the upgrade-type command to obtain the downgrade type.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 (Optional) Run the pretest command to examine whether the current database environment is
suitable for the downgrade.
python upgrade.py -t pretest --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Run the precheck command.


python upgrade.py -t precheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 61


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 9 Run the prepare command.


python upgrade.py -t prepare --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/home/gaussdba/up_out

Step 10 Run the replace command.


python upgrade.py -t replace --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 11 Run the start command.


python upgrade.py -t start --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 12 Run the upgrade command.


python upgrade.py -t upgrade --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 13 Run the sync command.


python upgrade.py -t sync --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 14 Run the start command.


python upgrade.py -t start --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 15 Run the upgrade-view command.


python upgrade.py -t upgrade-view --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 16 Perform the checkpoint operation.


python upgrade.py -t checkpoint --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 17 Run the dbcheck command.


python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 18 Run the flush command.


python upgrade.py -t flush --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

----End

Procedure (HA Manual Downgrade)


Manual downgrade is supported in HA scenarios. During a manual downgrade, you need to
perform several downgrade steps on each node involved in the HA deployment.
An HA manual downgrade consists of 12 steps: pretest, precheck, prepare, replace, start,
upgrade, sync, restart, upgrade-view, checkpoint, dbcheck, and flush. The specific
procedure is as follows:

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 62


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 2 Upload the downgrade installation package on all physical machines where primary and
standby databases are installed.
You must have the read, write, and execute permissions for the directory where the
downgrade installation package is stored. If the downgraded version supports the compatible
package, you need to upload the installation package of the downgraded version and the
compatible package DIALECT-SCRIPT-3.1.0.0.0.tar.gz to the same directory.

Step 3 Create the upgradetool folder in the installation directory of the current database on all
physical machines where primary and standby databases are installed to store the tool scripts
used for the downgrade.
cd $GSDB_HOME
mkdir upgradetool
chmod 700 upgradetool

Step 4 Copy upgrade.py, sshexkey.py, and funclib.py in the installation package of the current
database to the created upgradetool folder on all physical machines where primary and
standby databases are installed.
Assume that the installation package path of the current database is /opt/gaussdb/
GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit.
cd /opt/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit
cp upgrade.py sshexkey.py funclib.py $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be downgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In Step 6 through 18, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The
two parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment
variables. If the first two parameters are not specified, the default configuration in the environment
variables will be used.
l The generated log file is upgrade.log, which is stored in the backup directory specified by --
backupdir=/opt/gaussdb/backup. Rollback is needed if any step from 8 to 18 in an HA manual
downgrade fails. It is not needed if 7 (pretest) fails. For details about the rollback procedure, see
Procedure (HA Manual Rollback).

Step 5 Go to the directory where upgrade.py is stored on all physical machines where primary and
standby databases are installed, that is, the manually created upgradetool folder.
cd $GSDB_HOME/upgradetool

Step 6 (Optional) Run the upgrade-type command on the current physical machine to obtain the
downgrade type.
python upgrade.py -t upgrade-type --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 7 (Optional) Run the pretest command on all physical machines where primary and standby
databases are installed to check whether the current database environment is suitable for the
downgrade.
python upgrade.py -t pretest --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 8 Run the precheck command on all physical machines where primary and standby databases
are installed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 63


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

python upgrade.py -t precheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/


gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 9 Run the prepare command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t prepare --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 10 Run the replace command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t replace --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 11 Run the start command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t start --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 12 Run the upgrade command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t upgrade --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 13 Run the sync command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t sync --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/
data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 14 Run the restart command on all physical machines where primary and standby databases are
installed.
python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 15 Run the upgrade-view command on all physical machines where primary and standby
databases are installed.
python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 16 Run the checkpoint command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 17 Run the dbcheck command on all physical machines where primary and standby databases
are installed.
python upgrade.py -t dbcheck --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

Step 18 Run the flush command on all physical machines where primary and standby databases are
installed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 64


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

python upgrade.py -t flush --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/gaussdb/


data --package=/opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-
EULER20SP8-64bit.tar.gz --backupdir=/opt/gaussdb/backup

----End

2.10 Rolling Back a Database


Scenario
If upgrading or downgrading a database fails, you need to roll back it. The database can be
rolled back either automatically or manually. In an automatic rollback, you can specify the
upgrade file. In a manual rollback, you need to manually execute several rollback steps on
each node. For details about rollback procedures, see Procedure (Standalone Automatic
Rollback), Procedure (HA Automatic Rollback), Procedure (Standalone Manual
Rollback), and Procedure (HA Manual Rollback)

Procedure (Standalone Automatic Rollback)


If a standalone automatic database upgrade or downgrade fails, you need to roll back the
database automatically.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Go to the directory where upgrade.py is stored.


l To roll back a database when its upgrade fails, go to the directory where upgrade.py is
stored.
cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

l To roll back a database when its downgrade fails, go to the directory where upgrade.py
is stored.
cd $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Step 3 Perform a rollback check.


python upgrade.py -s rollback-check --config-file=/opt/gaussdb/config_file.ini
--upgrade-mode=single

Step 4 Perform a rollback.


python upgrade.py -s rollback --config-file=/opt/gaussdb/config_file.ini --
upgrade-mode=single

----End

Procedure (HA Automatic Rollback)


If an HA automatic database upgrade or downgrade fails, you need to roll back the database
automatically.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 65


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

The following steps must be performed on the node where the python upgrade.py -s run --
config-file=/opt/gaussdb/config_file.ini --upgrade-mode=ha command has been executed.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Go to the directory where upgrade.py is stored.
l To roll back a database when its upgrade fails, go to the directory where upgrade.py is
stored.
cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

l To roll back a database when its downgrade fails, go to the directory where upgrade.py
is stored.
cd $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

Step 3 Perform a rollback check.


python upgrade.py -s rollback-check --config-file=/opt/gaussdb/config_file.ini --
upgrade-mode=ha

Step 4 Perform a rollback.


python upgrade.py -s rollback --config-file=/opt/gaussdb/config_file.ini --
upgrade-mode=ha

----End

Procedure (Standalone Manual Rollback)


If a standalone manual database upgrade or downgrade fails, you need to roll back the
database manually.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Go to the directory where upgrade.py is stored.
l To roll back a database when its upgrade fails, go to the directory where upgrade.py is
stored.
cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

l To roll back a database when its downgrade fails, go to the directory where upgrade.py
is stored.
cd $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In 3 through 5, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The two
parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment variables.
If the first two parameters are not specified, the default configuration in the environment variables
will be used.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 66


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

Step 3 Perform a rollback check.


python upgrade.py -t rollback-check --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --backupdir=/opt/gaussdb/backup

Step 4 Perform a rollback.


python upgrade.py -t rollback --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --backupdir=/opt/gaussdb/backup

Step 5 Delete the rollback configurations.


python upgrade.py -t rollback-clean --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --backupdir=/opt/gaussdb/backup

----End

Procedure (HA Manual Rollback)


If an HA manual database upgrade or downgrade fails, you need to roll back the database
manually.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Go to the directory where upgrade.py is stored on all physical machines where HA primary
and standby databases are installed.
l To roll back a database when its upgrade fails, go to the directory where upgrade.py is
stored.
cd /opt/software/gaussdb/GAUSSDB100-V300R001C00-DATABASE-EULER20SP8-64bit

l To roll back a database when its downgrade fails, go to the directory where upgrade.py
is stored.
cd $GSDB_HOME/upgradetool

For details about upgrade.py, see Database Management Tools > upgrade.py in GaussDB
100 V300R001C00 Operation Guide to Tools (Standalone).

NOTE

l When multiple instances are installed, the database instances that are started from the same
installation directory must be upgraded at a time. In this case, --GSDB_DATA specifies the data
directories of multiple database instances, separated by commas (,).
l In 3 through 5, use --GSDB_HOME and --GSDB_DATA to explicitly specify a path. The two
parameters have a higher priority than GSDB_HOME and GSDB_DATA in environment variables.
If the first two parameters are not specified, the default configuration in the environment variables
will be used.

Step 3 Perform the rollback check on all physical machines where HA primary and standby
databases are installed.
python upgrade.py -t rollback-check --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --backupdir=/opt/gaussdb/backup

Step 4 Perform the rollback on all physical machines where HA primary and standby databases are
installed.
python upgrade.py -t rollback --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/
gaussdb/data --backupdir=/opt/gaussdb/backup

Step 5 Delete the rollback configurations on all physical machines where HA primary and standby
databases are installed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 67


GaussDB 100
User Guide (Standalone) 2 Installation and Deployment

python upgrade.py -t rollback-clean --GSDB_HOME=/opt/gaussdb/app --GSDB_DATA=/opt/


gaussdb/data --backupdir=/opt/gaussdb/backup

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 68


GaussDB 100
User Guide (Standalone) 3 Database System Management

3 Database System Management

3.1 Risky Operations


Table 3-1 Forbidden operations
Operation Risk Risk Level

Modify or delete files Serious errors occur on ★★★★★


in the database instances and cannot
$GSDB_HOME be fixed.
directory and its
subdirectories (except
the log directory),
covering file names,
file permissions, and
file content.

Modify or delete Service operations cannot be ★★★★★


database system performed.
catalogs, views, or
system catalog data.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 69


GaussDB 100
User Guide (Standalone) 3 Database System Management

Table 3-2 Risky operations


Operation Risk Risk level Workaround Check Item

Change the Services are ★★★ After you Check


internal interrupted change the whether the
database when the internal account RDS traffic
password. password is password, make statistics
being changed. the same change service is
to the password normal.
on the
RDSService,
HAMonitor,
Servicebilling,
and RDSInsight
components.

Manually The database ★★★★ Strictly follow -


modify the cannot be the instructions
configuration started or the provided in
file zengine.ini client cannot product
at will. be connected. documentation
while you
modify this file.

Manually Database ★★★★★ Use the SQL -


modify the startup fails commands of
content of files and data the system to
in the data becomes modify the
subdirectory inconsistent. content.
under
$GSDB_HOM
E.

3.2 Managing Sessions and Threads


GaussDB 100 adopts a single-process, multithreading structure. The thread here means an
operating system thread. When a server is running, it consists of various memory data
structures and a series of threads. Different types of threads complete different jobs. Users
access and process a database through threads to complete various jobs.
GaussDB 100 allows multiple users to connect to the same server, and the server process
becomes a shared process. You can modify the SESSIONS parameter based on the site
requirements to determine the maximum number of concurrent sessions.

User SYS Threads


To ensure the operations of user SYS on a database in emergency, GaussDB 100 reserves five
independent sessions and one work thread for the user.
In daily running, there are 16 default sessions for autonomous transactions (specified by the
AUTONOMOUS_SESSIONS and KNL_AUTONOMOUS_SESSIONS parameters); 32
reserved sessions for internal use, such as for reclaiming resources and executing checkpoints;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 70


GaussDB 100
User Guide (Standalone) 3 Database System Management

and 16 framework sessions for concurrent SQL execution. The following table describes the
reserved sessions for internal use.

Table 3-3 Reserved sessions

SID Session Function

0 Instance status switchover, for example, kernel start and stop, demotion from
primary to standby, and promotion from standby to primary

1 lgwr thread

2 ckpt thread

3 smon thread

4 Reserved, not in use now

5 undo preload thread

6 arch thread

7 rst thread

8 lsnr thread

9 mrp thread

10 Reserved, not in use now

11 fal thread

12 timer thread

13 rollback thread

14 Reserved, not in use now

15 log async thread

16 gts synchronizer thread

17 rcy thread

18 Reserved, not in use now

19 Reserved, not in use now

20 Reserved, not in use now

21 Reserved, not in use now

22 Reserved, not in use now

23 Reserved, not in use now

24 Reserved, not in use now

25 shd trans clean thread

26 stats thread

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 71


GaussDB 100
User Guide (Standalone) 3 Database System Management

SID Session Function

27 Statistics insertion to a temporary table and loading from a temporary table to


a DC

28 Distributed node loading

29 Job thread

30 index page recycle thread

31 Reserved, not in use now

3.3 Configuring a Database System


Scenario
After GaussDB 100 installation, parameters except those configured in the zengine.ini file
during installation all use default values. For details, see section "Parameters" in GaussDB
100 V300R001C00 Database Reference (Standalone). You need to adjust database parameters
to ensure that GaussDB 100 provides better service performance.

Precautions
l Parameter names are case-insensitive.
l Modifications on some parameters need a database restart before taking effect.
l You must have the corresponding system permissions for configuring parameters.
l Adjusting parameters may affect database system behavior. After installation is
complete, do not modify parameters. If the parameters require modification, fully
understand the impacts on GaussDB 100 before modifying them. Otherwise, unexpected
results may be generated.
l When optimizing a database, use the parameters provided in Parameters > Advanced
Optimization in GaussDB 100 V300R001C00 Database Reference (Standalone).

Viewing Database Parameters


You can query the system view DV_PARAMETERS for the configuration items of the
current database. Table 3-4 describes columns in this view.
SELECT * FROM DV_PARAMETERS;

Table 3-4 DV_PARAMETERS columns

No. Column Name Data Type Description

0 NAME VARCHAR(64) Parameter name

1 VALUE VARCHAR(2048) Parameter value

2 DEFAULT_VALUE VARCHAR(2048) Default parameter value

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 72


GaussDB 100
User Guide (Standalone) 3 Database System Management

No. Column Name Data Type Description

3 ISDEFAULT VARCHAR(20) Whether a parameter uses its


default value

4 MODIFIABLE VARCHAR(20) Whether a parameter can be


modified

5 DESCRIPTION VARCHAR(2048) Parameter description

6 RANGE VARCHAR(2048) Parameter value range

7 DATATYPE VARCHAR(20) Parameter type

8 EFFECTIVE VARCHAR(20) Parameter validation level. Values


are reboot, re-connect, and
immediately.

Configuring Installation Parameters


During installation, you need to configure the zengine.ini file for the database. Table 3-5 lists
mandatory parameters for installation. The parameters REPL_PORT and
ARCHIVE_DEST_2 are mandatory for HA installation, and are not needed for standalone
installation. Set other parameters based on actual service requirements. For details about how
to configure these parameters, see section "Parameters" in GaussDB 100 V300R001C00
Database Reference (Standalone). After installation, do not modify parameters randomly.
Otherwise, unexpected results may be generated.

Table 3-5 zengine.ini parameters


Parameter Description Value Range

TEMP_BUFFER_ Size of a temporary buffer Integer (unit: MB)


SIZE

DATA_BUFFER_ Size of a data buffer, which is used for Integer (unit: MB)
SIZE recently accessed data

SHARED_POOL_ Size of a shared pool Integer (unit: MB)


SIZE

LOG_BUFFER_S Size of a log buffer, which is used for redo Integer (unit: MB)
IZE logs

DBWR_PROCES Number of background threads for writing Integer


SES dirty pages. Increasing the value improves
concurrency efficiency but consumes more
resources.

LSNR_ADDR IPv4 address of the listening server IP address

LSNR_PORT Number of the listening port Integer, in the range


[1024, 65535]

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 73


GaussDB 100
User Guide (Standalone) 3 Database System Management

Parameter Description Value Range

SESSIONS Maximum number of concurrent sessions Integer, in the range


[64, 8192]

REPL_PORT Port on a standby database for primary- Available port


standby communication

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 74


GaussDB 100
User Guide (Standalone) 3 Database System Management

Parameter Description Value Range

ARCHIVE_DEST Log archiving path. This parameter allows String


_2 for two attributes, LOCATION and
SERVICE. SERVICE is applicable only to
HA clusters. It specifies the IP address and
port number of a peer end as well as the log
synchronization mode. In an HA cluster,
ARCHIVE_DEST_1 uses LOCATION
by default to set a local destination for log
archiving; and ARCHIVE_DEST_2 to
ARCHIVE_DEST_10 can use SERVICE.
l SYNC: synchronous mode
l ASYNC: asynchronous mode
l PRIMARY_ROLE:
ARCHIVE_DEST_n takes effect only
when an instance is primary.
l STANDBY_ROLE:
ARCHIVE_DEST_n takes effect only
when an instance is standby.
l ALL_ROLES: ARCHIVE_DEST_n
takes effect no matter whether an
instance is primary or standby.
l ZSTD: zstd compression is enabled.
(Logs are compressed by using the zstd
compression algorithm before being
sent.)
l LZ4: lz4 compression is enabled. (Logs
are compressed by using the lz4
compression algorithm before being
sent.)
Set this parameter for both the primary and
standby databases. The IP address is the IP
address of the peer end.
If the machine where a primary database
resides has multiple NICs or one NIC has
multiple IP addresses, you need to
configure the LOCAL_HOST attribute to
specify the IP address bound to the primary
database when it connects to a standby
database.
The format is as follows:
ARCHIVE_DEST_2={ SERVICE=ip:port
[SYNC | ASYNC] [PRIMARY_ROLE |
STANDBY_ROLE | ALL_ROLES] [ZSTD
| LZ4] [LOCAL_HOST=ip] }

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 75


GaussDB 100
User Guide (Standalone) 3 Database System Management

Parameter Description Value Range

CHECKPOINT_P Checkpoint execution interval Integer (unit: second).


ERIOD The default value is
300, and the minimum
value is 1.

REPL_WAIT_TI If no message is exchanged between Integer (unit: second).


MEOUT primary and standby databases within the The default value is
period specified by 10, and the minimum
REPL_WAIT_TIMEOUT, the primary- value is 3.
standby link will be considered abnormal,
and the primary or standby database will
proactively disconnect from each other.

Configuring Instance Parameters


Set system parameters. SCOPE is optional and specifies where the settings of system
parameters are written. Value PFILE or BOTH indicates that parameter settings are written
into the Zenith.ini configuration file. If SCOPE is not set, the default value BOTH will be
used.
ALTER SYSTEM SET parameter_name = parameter_value [ SCOPE = { MEMORY | PFILE |
BOTH } ]

l MEMORY: Parameter settings are written into only memory and take effect
immediately but become invalid after a restart. MEMORY is suitable for only dynamic
system parameters.
l PFILE: Parameter settings are written into initial parameter files and take effect after a
restart. PFILE is suitable for both dynamic and static system parameters. The settings of
static system parameters can be written into only initial parameter files.
l BOTH: Parameter settings are written into both initial parameter files and memory, and
take effect immediately. BOTH is suitable for only dynamic system parameters.

Examples
l Change the value of _ENABLE_QOS, an instance parameter, to TRUE.
ALTER SYSTEM SET _ENABLE_QOS = TRUE SCOPE = PFILE;

Succeed.

Configuring Session Parameters


GaussDB 100 supports session-based transaction committing and log committing.
l Set whether to wait for log writing when a transaction is committed.
ALTER SESSION SET COMMIT_WAIT_LOGGING = { WAIT | NOWAIT }

Default value: WAIT

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 76


GaussDB 100
User Guide (Standalone) 3 Database System Management

Assume that the value NOWAIT is used and there is a fault after the database receives a
commit request and before the redo log records are written. This can falsely indicate to a
transaction that its changes are persistent. Also, it can violate the durability of ACID
transactions if the database shuts down unexpectedly. ACID is short for Atomicity,
Consistency, Isolation, Durability.

l Set the redo log commit mode.


ALTER SESSION SET COMMIT_MODE = { IMMEDIATE | BATCH }

Default value: IMMEDIATE


l Change the redo log commit mode to batch commit.
ALTER SESSION SET COMMIT_MODE = BATCH ;

Succeed.

3.4 Managing Database Status


Scenario
A database administrator needs to maintain and rebuild database instances when GaussDB
100 is started in different modes.

Precautions
l The database status can only be changed only from NOMOUNT to MOUNT or OPEN,
and from MOUNT to OPEN. It cannot be rolled back from OPEN. If you need to
switch to another status from OPEN, restart the database instance in NOMOUNT or
MOUNT mode.
l When a database is switched from OPEN to its child status, READ WRITE and READ
ONLY can be switched online, and RESETLOGS and RESTRICT can be switched
only when the database is in the NOMOUNT or MOUNT status.

Related Concepts
The GaussDB 100 start process covers four phases: CLOSED, NOMOUNT, MOUNT, and
OPEN. A database administrator can start the database to any phase as needed.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 77


GaussDB 100
User Guide (Standalone) 3 Database System Management

Figure 3-1 Instance start process

Viewing Database Status


l If GaussDB 100 has been connected, you can view the database status in the
DV_DATABASE view.
SELECT STATUS FROM DV_DATABASE;
STATUS
--------------------
OPEN
1 rows fetched.

l Query the DV_DATABASE view for the OPEN status.


SELECT OPEN_STATUS FROM DV_DATABASE;
OPEN_STATUS
--------------------
OPEN READONLY
1 rows fetched.

Changing Database Instance Status


Step 1 Log in to a server where GaussDB 100 is deployed as user gaussdba.

Step 2 Start the database in NOMOUNT or MOUNT mode and connect it.

The following uses NOMOUNT as an example.


python zctl.py -t start -m NOMOUNT

Step 3 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 4 Change the database status to MOUNT.


ALTER DATABASE MOUNT;

----End

Changing OPEN Child Statuses


l Change database status to RESETLOGS or RESTRICT.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 78


GaussDB 100
User Guide (Standalone) 3 Database System Management

Step 1 Stop the database.


cd ${GSDB_HOME}/bin
python zctl.py -t stop

Step 2 Start the database in NOMOUNT or MOUNT mode.


python zctl.py -t start -m { NOMOUNT | MOUNT }

Step 3 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 4 Switch the database status to a child status of OPEN.

For example, switch to RESTRICT.


ALTER DATABASE OPEN RESTRICT;

----End

l Change database status to READ WRITE or READ ONLY.


READ WRITE and READ ONLY can be switched online. In HA primary/standby
deployment, such a switchover can be performed only on the primary database.
– To switch from READ ONLY to READ WRITE, run the following command:
ALTER DATABASE CONVERT TO READWRITE;

– To switch from READ WRITE to READ ONLY, run the following command:
ALTER DATABASE CONVERT TO READONLY;

Status Description

Table 3-6 Database status


Status Description Scenario

CLOSED System status before startup -

NOMOUN The process or thread has been l Create database instances.


T started but the database is not l Rebuild control files.
mounted. Users can
communicate with the database
but cannot use any files in the
database.

CREATING A database is being created. -

MOUNT The database is mounted but l Rename, add, or delete data files.
not started. In this mode, only l Perform full restoration on a database.
database administrators can
modify the database and users l Change the archiving mode of a
cannot establish connections or database.
sessions with the database.

RECOVER The database is being restored. -


Y

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 79


GaussDB 100
User Guide (Standalone) 3 Database System Management

Status Description Scenario

OPEN The database is loaded and the Normal use


instance is started.

Table 3-7 Child statuses of OPEN


Status Description Scenario

READ Supports read and write. It is This status is used when services are
WRITE the default status after the executed normally.
database enters OPEN.

READ Supports only read. In this l Before a primary/standby switchover,


ONLY case, the database supports the primary database is set to this
only query. status.
l Data is only queried.

RESTRICT Loads only core system l This status can be used with
catalogs, allowing for user upgrade.py. For details, see
SYS only. Upgrading a Database. Other
unconventional operations will cause
database processes to exit abnormally,
resulting in database unavailability.
l In this status, you can run the
COMMIT FORCE command to
forcibly commit residual transactions.
However, new transactions generated
in this status cannot be forcibly
committed.

RESETLO Resets the time line of a A physical backup is restored.


GS database to prevent obsolete NOTE
data from entering the The reset can be performed only after the
database. RECOVER DATABASE statement is
executed.

Examples
Change the database status.
-- Change the database status to MOUNT:
ALTER DATABASE MOUNT;
-- Change the database status to OPEN:
ALTER DATABASE OPEN;

3.5 Managing a Database


Scenario
You can run the ALTER DATABASE statement to modify database attributes.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 80


GaussDB 100
User Guide (Standalone) 3 Database System Management

Procedure
l Add redo log files to a database.
ALTER DATABASE ADD LOGFILE ('/gaussdb/data/log1' size 256M, '/gaussdb/data/
log2' size 256M, '/gaussdb/data/log3' size 256M);

l Delete redo log files from the database.


ALTER DATABASE DROP LOGFILE ('/gaussdb/data/log1' );

l Set the redo log storage mode.


The mode can be set to ARCHIVELOG or NOARCHIVELOG.
ALTER DATABASE ARCHIVELOG;

– Archiving mode (ARCHIVELOG)


When the size of a redo log file reaches the maximum, the system copies the log
content to the archive log file for unified storage, preventing the content from being
overwritten by next write.
– Online mode (NOARCHIVELOG)
When a redo log file is full, the system directly switches the log file without
backing up it. The log content will be overwritten by next write to the file.
NOTE

l In primary/standby database deployment, you can set the redo log mode only to
ARCHIVELOG.
l By default, GaussDB 100 uses the archiving mode.
l Change the system protection mode.
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PROTECTION;

The default data protection mode in GaussDB 100 is PERFORMANCE. If SERVICE


in the ARCHIVE_DEST_n parameter of a database instance is set to SYNC
(synchronous standby), the data protection mode can be switched. A database instance
whose SERVICE is ASYNC (asynchronous standby) does not participate in data
protection mode determination.
When the mode is switched to PROTECTION, the database must be in MOUNT status.
When it is switched to AVAILABILITY or PERFORMANCE, the database must be in
OPEN or MOUNT status.
GaussDB 100 supports the following data protection modes:
– PROTECTION
Highest-level data protection. Transactions on the primary database can be
committed only after its standby database receives the redo logs. This mode ensures
that no data is lost, but has high requirements on network conditions and greatly
compromises database performance.
– AVAILABILITY
Highest-level data availability. Data protection in this mode is only second to
PROTECTION. In principle, transactions on the primary database can be
committed only after its standby database receives the redo logs. If the redo logs
cannot be written to the standby database, the data protection mode is temporarily
switched to PERFORMANCE until the standby database receives the redo logs.
This mode ensures that data on a standby database running properly is not lost, but
compromises database performance to some extent.
– PERFORMANCE
Highest-level data performance. Transactions on the primary database are
committed no matter whether its standby database receives the redo logs. However,

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 81


GaussDB 100
User Guide (Standalone) 3 Database System Management

if the standby database fails to receive the redo logs related to the transactions
committed by the primary database, the transaction data may be lost.
l Change the size of the data file USER.
ALTER DATABASE DATAFILE 'USER' RESIZE 128M;

– When reducing the file size, ensure it is not smaller than the minimum size required
by the database system. The minimum size required by the SYSTEM tablespace
and UNDO tablespace is 128 MB, and that of other data files is 1 MB.
– When reducing the file size, ensure that the storage area of valid data is not
damaged. Otherwise, the command execution will fail.
– The number of pages occupied by valid data can be obtained from the
HIGH_WATER_MARK column in the view Data Dictionary and Views >
Dynamic Performance Views > DV_DATA_FILESDV_DATA_FILES in
GaussDB 100 V300R001C00 Database Reference (Standalone). Note that this
column specifies the number of pages occupied by a data file. To calculate the file
size, multiply the column value by the size of each page.

3.6 Managing Logs

3.6.1 Log Overview


During database running, a large number of logs are generated, including run, audit, debug,
and alarm logs. If a database is faulty, you can use these logs to locate the fault and restore the
database.

GaussDB 100 supports the following types of logs:

l Installation and Uninstallation Logs


An installation log prints GaussDB 100 installation information. When installation fails,
examine the zengineinstall.log file.
For installation by user root, the log directory is ~/zengineinstall.log by default.
For installation by a common user, the log directory is ~/zengineinstall.log in HOME
by default.
l Installation and Uninstallation Logs
An uninstallation log prints GaussDB 100 uninstallation information. When
uninstallation fails, examine the zengineuninstall.log file.
For uninstallation by user root, the log directory is ~/zengineinstall.log.
For uninstallation by a common user, the log directory is ~/zengineuninstall.log in
HOME.
l Run Logs
A run log prints GaussDB 100 running information. When a database is faulty, examine
the zengine.rlog file.
The log directory is $GSDB_DATA/log/run/zengine.rlog by default.
l Debug Logs
A debug log prints debug information during GaussDB 100 running. When a database is
faulty and debug logging has been enabled, examine the zengine.dlog file.
The log directory is $GSDB_DATA/log/debug/zengine.dlog by default.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 82


GaussDB 100
User Guide (Standalone) 3 Database System Management

l Slow Query Logs


A slow query log prints information about SQL statements executed in GaussDB 100
with execution time exceeding the thresholds specified by the LONGSQL_TIMEOUT
parameter. Examine the zengine.lsql file if necessary.
The log directory is $GSDB_DATA/log/longsql/zengine.lsql by default.
l Audit Logs
An audit log prints GaussDB 100 audit information. For details about the audit
information, see zengine.aud. 2
The log directory is $GSDB_DATA/log/audit/zengine.aud by default.
l zctl Logs
A zctl log prints information about O&M operations performed by zctl.py. To obtain
complete O&M information of GaussDB 100, examine the zctl-yyyy-mm-dd_xxx.log file
and the zenithstatus.log file, which contains output information upon database startup.
The log directory is $GSDB_DATA/log/zctl-yyyy-mm-dd_xxx.log.
l Alarm Logs
An alarm log prints alarm information during GaussDB 100 running. For details about
the alarm information, see zenith_alarm.log.
The log directory is $GSDB_DATA/log/zenith_alarm.log.
l Operation Logs
An operation log records information about the operations performed by users on
GaussDB 100 through ZSQL. For details about the operation records, see zsql.olog.
The log directory is $GSDB_DATA/log/oper/zsql.olog.
l Startup Logs
A startup log records output information upon database startup. For details, see
zenithstatus.log. To obtain complete O&M information of GaussDB 100, examine the
zctl-yyyy-mm-dd_xxx.log file and the zenithstatus.log file, which contains output
information upon database startup.
The log directory is $GSDB_DATA/log/zenithstatus.log.
l Trace Logs
A trace log records the information about database session deadlocks. For details about
session deadlocks, see zengine_00003_xxxxxx.trc.
The log directory is $GSDB_DATA/trc/zengine_00003_xxxxxx.trc.

3.6.2 Configuring Logs


GaussDB 100 allows you to configure the size, number of backup log files, permissions, and
levels for some logs. It also supports log deletion and automatic restoration. For details about
how to modify log attributes, see Parameters > Logs in GaussDB 100 V300R001C00
Database Reference Information (Standalone). Modification of log parameters takes effect
only after the database is restarted. Therefore, exercise caution when doing so.

Setting Log Parameters


Parameter Introduction
You can set log control parameters to specify the types of logs to be recorded by the database
system.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 83


GaussDB 100
User Guide (Standalone) 3 Database System Management

l The _LOG_LEVEL parameter specifies the run and debug logs to be recorded. If
multiple types of logs need to be recorded, set the parameter to the sum of parameter
values for required log types. Table 3-8 lists parameter values for different log types.

Table 3-8 Settings of _LOG_LEVEL (for run logs and debug logs)
Log Type Decimal Value Binary Value

RUN ERROR 1 000000000001

RUN WARNING 2 000000000010

RUN INFORMATION 4 000000000100

DEBUG ERROR 16 000000010000

DEBUG WARNING 32 000000100000

DEBUG INFORMATION 64 000001000000

LONGSQL LOG 256 000100000000

NOTE

l After _LOG_LEVEL is set to a number, the number will be converted into a binary value,
with the last nine bits in use. If the most significant bits are insufficient, the value will be left
padded with 0. From the most significant bit to the least significant bit, each bit represents
LONGSQL LOG, reserved bit, DEBUG INFORMATION, DEBUG WARNING, DEBUG
ERROR, reserved bit, RUN INFORMATION, RUN WARNING, and RUN ERROR,
respectively. Bit 1 indicates on, and bit 0 indicates off.
For example, if the parameter is set to 16, its binary value will be 10000. After left-padding
with 0, the value becomes 000010000, indicating that DEBUG ERROR logs will be recorded.
l For details about the _LOG_LEVEL parameter, see section "Parameters" in GaussDB 100
V300R001C00 Database Reference (Standalone).
l The AUDIT_LEVEL parameter specifies the types of audit logs to be recorded. Table
3-9 lists parameter values for different audit log types.

Table 3-9 Settings of AUDIT_LEVEL for audit logs


Log Type Decimal Value Binary Value

DDL 1 00000001

DCL 2 00000010

DML 4 00000100

PL 8 00001000

ALL 255 11111111

For functional syntax, set AUDIT_LEVEL based on its types to record required audit
logs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 84


GaussDB 100
User Guide (Standalone) 3 Database System Management

– For EXP, IMP, LOAD, and DUMP syntax that consists of multiple types of SQL
statements, the value of AUDIT_LEVEL must cover the corresponding SQL types.
– For other syntax, the value of AUDIT_LEVEL must cover the DCL type.
NOTE

l When the value of AUDIT_LEVEL is 0, audit logging is disabled.


l When the value of AUDIT_LEVEL is greater than 0, it needs to be converted into a binary
value, with the last four bits in use. If the most significant bits are insufficient, the value will
be left padded with 0. From the most significant bit to the least significant bit, each bit
represents PL, DML, DCL, and DDL, respectively. Bit 1 indicates on, and bit 0 indicates off.
For example, if the parameter is set to 16, its binary value will be 10000. The last four bits are
0000, indicating that PL, DML, DCL, and DDL audit logs are all disabled. In this case, the PL,
DML, DCL, and DDL audit logs are not recorded, but login requests, logout requests,
cancellation requests, and FREE statements are recorded.
l For details about the AUDIT_LEVEL parameter, see section "Parameters" in GaussDB 100
V300R001C00 Database Reference (Standalone).

Modifying Log Parameters

Connect to a database, and run the ALTER SYSTEM SET statement to change the parameter
values. The changes take effect immediately.

For example, to record RUN ERROR and DEBUG ERROR logs, change the value of
_LOG_LEVEL to 17 (00010001).
ALTER SYSTEM SET _LOG_LEVEL = 17;

Modifying Redo Log Files


l Add redo log files.
Add one or more redo log files to a primary or standby node. If no directory is specified,
files will be added to the $GSDB_HOME/data directory.
Syntax:
Specify one or more redo log files. The parameter value must contain the file size, and
the file name or absolute path. The file size is unlimited.
ALTER DATABASE ADD LOGFILE
( { 'file_name' SIZE integer [ K | M | G | T | P | E ]
} [ , ... ]
);

– SIZE integer [ K | M | G | T | P | E ]
Specifies the file size. The default unit is byte. K indicates KB, M indicates MB, G
indicates GB, T indicates TB, and E indicates EB.
Note that the total number of log files cannot exceed 256.
l Execute redo log files.
Delete one redo log file from a primary or standby node.
Syntax:
ALTER DATABASE DROP LOGFILE ( 'file_name' );

3.6.3 Viewing Logs


A database can still run when errors occur during the execution of some operations. However,
data may be inconsistent before and after the error occurrences. Therefore, you are advised to
monthly check database run logs to detect potential problems in a timely manner.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 85


GaussDB 100
User Guide (Standalone) 3 Database System Management

Run Logs
Run logs record various information during database running. If there is a fault during the
running, you can view the run log file zengine.rlog to locate the fault.
l Log directory
$GSDB_DATA/log/run/zengine.rlog by default
l Log format
For example:
UTC+8 2018-06-09 12:09:40.053|ZENGINE|00048|140045052368640|INFO>[SPACE]
succeed to create tablespace TABLESPACE1

– Time zone
– Event occurrence time
– Module
– Session ID
– Current thread ID
– Log level
– Log content

Debug Logs
l Log directory
$GSDB_DATA/log/debug/zengine.dlog by default
l Log format
For example:
UTC+8 2018-06-09 12:09:40.053|ZENGINE|00048|140045052368640|INFO>[SPACE]
succeed to create tablespace TABLESPACE1

– Time zone
– Event occurrence time
– Module
– Session ID
– Current thread ID
– Log level
– Log content

Slow Query Logs


l Log directory
$GSDB_DATA/log/longsql/zengine.lsql by default
l Log format
The format of slow query logs is special and needs to be checked in the view Data
Dictionary and Views > Dynamic Performance Views > DV_LONG_SQL in
GaussDB 100 V300R001C00 Database Reference (Standalone).
For example:
SQL> select stage,sql_text from dv_long_sql;

STAGE SQL_TEXT
------------ ----------------------------------------------------------------

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 86


GaussDB 100
User Guide (Standalone) 3 Database System Management

PREPARE "INSERT INTO T_LONGSQL(ID) VALUES(1)"


EXECUTE "INSERT INTO T_LONGSQL(ID) VALUES(1)"
PREPARE "SELECT ID FROM T_LONGSQL"
EXECUTE "SELECT ID FROM T_LONGSQL"

Audit Logs
Audit logs record different information based on the audit level set by users.

Sensitive information (such as a password) is not allowed in SQL constant strings or dynamic
SQL statements of stored procedures because it cannot be identified by GaussDB 100 and
may be printed with audit logs.

l Log directory
$GSDB_DATA/log/audit/zengine.aud by default
l Log format
For example:
UTC+8 2019-01-30 10:09:23.488
LENGTH: "117"
SESSIONID:[2] "48" STMTID:[0] "" USER:[6] "SYSDBA" HOST:[0] "" ACTION:[7]
"CONNECT" RETURNCODE:[1] "0" SQLTEXT:[0] ""

– Event occurrence time


– Audit content length
– Audit content
Content keyword:[Keyword length]"Audit content"

Operation Logs
Operation logs are generated when a database administrator uses zsql.py to perform
operations on the database. If GaussDB 100 is faulty, you can backtrack user operations on
the database and reproduce the fault based on the operation logs.

l Log directory
$GSDB_DATA/log/oper/zsql.olog by default
l Log format
For example:
2019-01-30 10:21:10.894|zsql|SELECT VALUE FROM DV_PARAMETERS WHERE NAME =
'TCP_INVITED_NODES';

– Event occurrence time


– zsql tool
– Statement executed

Installation and Uninstallation Logs


Installation logs (zengineinstall.log) and uninstallation logs (zengineuninstall.log) record
information about GaussDB 100 installation and uninstallation, respectively. When
installation or uninstallation fails, view the corresponding logs to locate the failure.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 87


GaussDB 100
User Guide (Standalone) 3 Database System Management

l Log directory
for installation by user root
~/zengineinstall.log for installation by a common user
for uninstallation by user root
~/zengineuninstall.log for uninstallation by a common user
l Log format
For example:
[2019-01-31 11:17:50] Begin check parameters...

– Event occurrence time


– Operation performed

Alarm Logs
Alarm logs record database exceptions. If there is a deadlock in a database, a deadlock log
will be recorded, including deadlocks on tables and transactions. If the number of database
handles is insufficient, a corresponding log will be recorded. If running a customized job for
the first time fails, a failure log will be recorded.

l Log directory
$GSDB_DATA/log/zenith_alarm.log by default
l Log format
For example:
2019-02-02 09:24:55|1078919231|DeadLock|DN|zenith|zenith

– Event occurrence time


– Alarm ID
– Alarm content
– Component name
– Database name
– Alarm description

zctl Logs
zctl logs record information about O&M operations performed by zctl.py.

l Log directory
$GSDB_DATA/log/zctl-yyyy-mm-dd_xxx.log by default
l Log format
For example:
[2019-02-28 09:35:14.414081][USER:root][HOST:10.190.92.132][zctl][LOG]:Zctl
start instance successful.

– Event occurrence time


– Operation user
– Host IP address
– zctl tool
– Log details

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 88


GaussDB 100
User Guide (Standalone) 3 Database System Management

Startup Logs
Startup logs record output information upon database startup. To obtain complete O&M
information of GaussDB 100, examine both the zctl logs and startup logs.
l Log directory
$GSDB_DATA/log/zenithstatus.log by default
l Log format
For example:
starting instance(normal)
instance started

Trace Logs
Trace logs are used to record tracing information about related sessions when a fault occurs in
the database. Currently, they record only the session deadlock information.
l Log directory
$GSDB_DATA/trc/zengine_00003_xxxx.trc by default
In this directory, 00003 is the ID of a session, and the deadlock log is recorded in the
session whose SESSION_ID is 3. In addition, xxxx is the process ID. After the database
is restarted, a new trace log will be generated.
l Log format
For example:
**2019-03-17 11:37:32 DEADLOCK DETECTED*
The following deadlock is not a ZENITH error.It is due to user error in the
design of SQL.The following information may aid in determining the deadlock :
----------------------WAIT INFORMATION---------------------
[Transaction Deadlock]
session id: 54, wait session: 53, wait rowid: 0-0-9624
wait sql: update d1 set c2 = 'w' where c1 = 1

session id: 53, wait session: 54, wait rowid: 0-0-9632


wait sql: update d2 set c2 = 'w' where c1 = 1

-----------------END OF WAIT INFORMATION-----------------

If wait_sql is empty, there are DDL statements being executed in the current session.
Currently, no DDL deadlocks can be recorded.
A trace log contains the following information:
– Time when the deadlock occurred
– Deadlock type
– Session IDs in the deadlock ring
– Wait session IDs in the deadlock ring
– SQL statements that cause the deadlock in the deadlock ring
– Cause of each deadlock
n Transaction deadlock: You can check the row that causes the deadlock based
on row_id.
n Table deadlock: You can check the table that causes the deadlock based on
table_id.
n ITL deadlock: You can check the page that causes the deadlock based on
page_id.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 89


GaussDB 100
User Guide (Standalone) 3 Database System Management

3.6.4 Deleting Logs


A large number of run logs will be generated during database running and occupy huge disk
space. You are advised to delete old run logs and retain those generated within one month.

The maximum size of a zctl log file is 10 MB. If a zctl log exceeds 10 MB, it will be
automatically dumped to a historical log file. A maximum of nine historical log files can be
retained. When the number of historical log files reaches the upper limit, delete earlier files
first.

3.7 Managing Transactions


A transaction is a user-defined sequence of database operations, which form an integral unit
of work. In GaussDB 100, you can start, set, commit, and roll back transactions. GaussDB
100 supports the following transaction isolation levels: READ COMMITTED, READ
CURRENT COMMITTED, and SERIALIZABLE.

Controlling Transactions
The following describes transaction operations supported by GaussDB 100:

l Starting a transaction
GaussDB 100 provides no explicit statement to start a transaction. The first executable
SQL statement (except the login statement) indicates the start of a transaction.
You cannot run the BEGIN or START statement to start a transaction.
l Setting a transaction
GaussDB 100 provides the SET TRANSACTION statement to set a transaction.
l Committing a transaction
GaussDB 100 provides COMMIT to commit all operations of a transaction. In
GaussDB 100, transactions are not automatically committed by default. They will be
committed only after COMMIT is displayed. Otherwise, records will be lost during
sessions.
After zsql is used to create a connection, you can run the SET command with
AUTOCOMMIT set to ON to enable automatic transaction committing. For details
about how to set this parameter, see Client Tools > zsql > Setting Parameters in
GaussDB 100 V300R001C00 Operation Guide to Tools (Standalone).
l Rolling back a transaction
GaussDB 100 provides ROLLBACK to roll back work done in the current transaction
and terminate the transaction. You can use SAVEPOINT to set a savepoint, which can
be selected for rollback. If you do not explicitly commit a transaction and the program
terminates abnormally, the database rolls back the last uncommitted work unit, rather
than the entire transaction. In addition, you can use RELEASE SAVEPOINT to destroy
unnecessary savepoints. The syntax is as follows:
RELEASE SAVEPOINT savepoint_name;

Transaction Isolation Levels


A transaction isolation level determines the data accessible to users when there are concurrent
transactions.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 90


GaussDB 100
User Guide (Standalone) 3 Database System Management

The isolation level cannot be changed after the first SQL statement SELECT, INSERT,
DELETE, UPDATE, FETCH, or COPY in the transaction is executed.
l READ COMMITTED: At this level, a transaction can access only committed data. This
is the default level.
Generally, the SELECT statement accesses a database snapshot taken when the query
begins. It can also access the data updates in its session, regardless of whether they have
been committed. In this case, different database snapshots may be available to two
consecutive SELECT statements in the same transaction because other transactions may
be committed while the first SELECT statement is executed.
At the READ COMMITTED level, the execution of each statement begins with a new
snapshot, which contains all the transactions that have been committed by the execution
time. Therefore, during a transaction, a statement can access the results of other
committed transactions. Pay attention to whether a single statement always accesses
absolutely consistent snapshots in a database.
Transaction isolation at this level meets the requirements of many applications, and is
fast and easy to use. However, applications performing complicated queries and updates
may require data that is more consistent than this level can provide.
l READ CURRENT COMMITTED: At this level, when the execution of a statement
starts, the SCN of the current system is obtained as the query SCN for the statement.
During the execution of the statement, the last committed result of the current access
record is visible. In GaussDB 100, READ CURRENT COMMITTED is a sub-type of
READ COMMITTED. However, it does not indicate a consistent read, and therefore
can be used when requirements for consistency are low.
l SERIALIZABLE: At this level, transactions are serialized sequentially for execution,
similar to the serializable level in snapshot isolation. This is the highest transaction
isolation level. When all statements in transactions are executed, the start SCN of the
current serializable transaction is obtained as the query SCN for the statements. The
visible result of a statement is determined at the beginning of the transaction and is not
affected by other transactions or changes.

3.8 Backup and Restoration


Even the most stable system may have accidents, such as power breakdown and hardware
faults. Data backup is the basis for DR. GaussDB 100 provides the backup and restoration
functions. By properly planning the backup mode and frequency, you can effectively avoid
data loss in unexpected situations.

3.8.1 Backup and Restoration Overview


Database administrators need to design, implement, and manage backup and restoration
policies. Generally, the policies are used to protect a database from data loss and rebuild the
database after data loss. When there is a media fault, database administrators need to start the
restoration operation. There are two methods to restore a backup: use redo logs to roll forward
the backup to a relatively close time point; or roll back all updates in an uncommitted
transaction. Generally, restoration refers to the operations involved in restoration, rollforward,
and rollback. Backup and restoration refer to the policies and operations involved in
preventing data loss in a database and rebuilding the database when data is lost.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 91


GaussDB 100
User Guide (Standalone) 3 Database System Management

Data Protection
The primary job of a backup administrator is preparing and monitoring data backups. Backup
is a copy that can be used to rebuild a database. Each physical backup is a file that stores
database information in another location (such as a disk, tape, or other offline storage media).
It contains data files, control files, and archive redo logs. GaussDB 100 supports physical
backup. Users can store backup data on disks or using NetBackup (NBU), an enterprise-level
backup and restoration suite. In addition, GaussDB 100 supports hot backup. Data can be
backed up without stopping the database service, ensuring that the system is not interrupted in
7x24 hours.

Data Archiving
Although data archiving is related to data protection, it has different purposes. Archive
backups are different from common backups and use different restoration policies. These
backups are usually archived on separate storage media and retained for a long time. For
example, a database administrator may need to retain the backup of a database until the
service season ends, but this backup is not part of the DR policy. After a backup is complete,
the media to which the backup is written is usually unavailable. This type of backup is called
archive backup.

Data Migration
In some cases, you need to back up the data in a database and move the data to another
location. Strictly, these jobs are not part of backup and restoration policies, but they need
database backups. For example, move an entire database from one platform to another.

3.8.2 Backup and Restoration Solutions


GaussDB 100 provides multiple solutions for backup and restoration. You can select a proper
one based on system configurations and service requirements.

Backup Modes
Data can be backed up in either of the following modes. Currently, GaussDB 100 supports
only physical backup.

l Physical backup
A database is backed up by copying physical files. Data is replicated from a primary
database to a standby database in the unit of disk block. Each backup covers the data of a
sector (512 bytes). A database can be restored using backup files, such as data files and
archive log files. Physical backup is usually used for full backup, quickly backing up and
restoring data with low costs if properly planned.
l Logical backup
Data of a primary database can be backed up to its standby database as follows: the
online and archive log files of the primary database are parsed to generate logical logs;
and then these are used to construct DML statements to be replayed on the standby
database.
Logical backup provides more flexibility than physical backup. Specifically, it allows for
either a heterogeneous database or a homogeneous database of a different version as a
standby database; and it can also back up database subsets by using a table-level, logical
replication switch.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 92


GaussDB 100
User Guide (Standalone) 3 Database System Management

Backup Levels
GaussDB 100 supports full backup and multi-level incremental backup.
l Full backup
Data at a specific time point is fully replicated regardless of the archive attribute of all
files. The archive attribute will be deleted during the backup. A full backup allows tapes
alone to be used for restoring lost data, greatly accelerating system or data restoration.
However, there is a large amount of duplicate information across the tapes with the same
full backup data. In addition, a large amount of data needs to be backed up each time,
consuming huge time.
l Incremental backup
Incremental backup is a backup of changes since the previous backup.
If you use the BACKUP command to perform an incremental backup, the system will
cover all files that have been changed after the previous backup (full backup, differential
incremental backup, or cumulative incremental backup). Such a backup has no duplicate
data. The amount of data to be backed up is small and the backup takes a short time.
However, it is complicated to restore an incremental backup. You must have the tapes for
the previous full backup and all the incremental backups (once the tapes are lost or
damaged, the restoration will fail). In addition, you must restore data one by one from
the full backup to the incremental backups in sequence. This greatly prolongs the
restoration. Incremental backup can be performed only by running the BACKUP
statement.
GaussDB 100 supports two levels for incremental backup: level 0 and level 1. Level-0
backup is a baseline incremental backup, that is, a full backup. Level-1 backup is an
incremental backup for the previous level 0 backup or level 1 backup.
With differential incremental backup, all changed data blocks since the previous level 1
or level 0 backup are backed up. Differential incremental backup is the default
incremental backup mode.
With cumulative incremental backup, all data blocks changed since the previous level 0
backup are backed up.
If you perform an incremental backup, the system will back up archive log files in a
specified time range to a specified directory. Before this incremental backup, you must
perform a full backup. If there is small gap or little data update between the current
backup time and the last full backup time, you can back up only the archive log files in
this gap period.

Backup Media
GaussDB 100 supports backup to disk.
l Backup to disk
When data is backed up to a disk, multiple concurrent read and write threads are started
in the database to implement parallel backup and restoration, accelerating the operations.
The parallel backup and restoration supports a maximum of 8 pairs of concurrent read
and write threads. The default value is 4. A data file is usually backed up by a pair of
read and write threads. If the size of a data file exceeds the splitting threshold, the file
will be split into multiple pieces, which are then allocated to different read and write
threads. This accelerates the data file backup. During backup, the database automatically
determines the optimal data file splitting threshold and policy. You can manually specify
the threshold and policy as well. Data files that exceed the specified threshold are split,

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 93


GaussDB 100
User Guide (Standalone) 3 Database System Management

but the number of data file pieces cannot exceed that of concurrent threads. If the
splitting threshold is manually specified, a larger value will result in a decrease in
parallel efficiency, and a smaller value will generate too many backup files. Therefore,
you are not advised to specify the splitting threshold manually.

Backup Compression
GaussDB 100 supports backup set compression.
If the backup storage space or the network backup bandwidth is limited, the backup set size
needs to be reduced. In this case, backup set compression is applied. GaussDB 100 supports
the zstd, lz4, and zlib compression algorithm for compressing backup sets. A compression
level can be specified for compressed backup. The value range is [1, 9]. A higher level leads
to a higher compression ratio but a lower speed. The default compression level is 1.

PITR
With Point-In-Time Recovery (PITR), a database can be restored to a specified time point
based on physical backup files and redo log files.
Backup sets can be used to restore data to the backup time point. If there are archive logs
generated after the backup, the logs can be replayed to restore data to a time point after the
backup.

Schema-specific Restoration
To facilitate data maintenance, you can store data of different services in a database by using
different schemas. Ensure that each schema uses a separate tablespace. If the data of only one
schema is damaged and needs to be repaired, you can use the ztrst tool to restore only the
data of the specific schema based on the full backup file, which accelerates the restoration.

Table Flashback
Table flashback is a fast data restoration solution. You can selectively query or cancel
misoperations. FLASHBACK TABLE restores a table to an earlier state in the event of
human or application errors. A table can be flashed back to a previous time point.

3.8.3 Data Backup


Prerequisites
l The database runs in ARCHIVELOG mode and archives redo logs to multiple
locations.
You can query the system view DV_DATABASE for the current log archive mode. For
details about how to change the log archive mode, see #li16795218173815
l There are multiple concurrent backups of the control file (CONTROL_FILES)
maintained.
You can specify the path of control files when creating a database. If it is not specified,
GaussDB 100 will automatically create three control files and use the default file names.
l Physical data files are periodically backed up, and the backups are stored on secure
media.
l When the backup operation is performed on the primary and standby databases, the
database status must be OPEN.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 94


GaussDB 100
User Guide (Standalone) 3 Database System Management

l When backing up data files on a standby database is complete, the connection between
the primary and standby databases must be normal. If the connection is abnormal, the
backup information cannot be recorded in the system catalog of the primary database,
and an error will be returned.
-- The standby database fails to send backup set information to the primary
database.
GS-00878: Send backup record to primary failed
-- The standby database fails while waiting for the primary database to
record the backup information.
GS-00879: wait primary record backup set failed

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Run the backup command.


l Full backup:
BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup01.bak';

l Differential incremental backup:


BACKUP DATABASE INCREMENTAL LEVEL 0 FORMAT '/home/gaussdba/data/
backup0_incr.bak';
BACKUP DATABASE INCREMENTAL LEVEL 1 FORMAT '/home/gaussdba/data/
backup1_incr.bak';

l Cumulative incremental backup:


BACKUP DATABASE INCREMENTAL LEVEL 1 CUMULATIVE FORMAT '/home/gaussdba/data/
backup1_incr_cum.bak';

NOTE

Level 0 indicates the baseline backup. Level 0 backup must be performed before level 1 backup is
performed for the first time. Level 1 backup is based on the previous level 1 or level 0 backup.
– Differential incremental backup: a backup based on the previous level 0 or level 1 backup
– Cumulative incremental backup: a backup based on the previous level 0 backup
l Compressed backup:
– Full compressed backup
BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup_c_bak' AS
COMPRESSED BACKUPSET;

– Incremental compressed backup


BACKUP DATABASE INCREMENTAL LEVEL 1 FORMAT '/home/gaussdba/data/
backup1_incr.bak' AS COMPRESSED BACKUPSET;

– Compressed backup with a compression algorithm specified [zlib|zstd|lz4] (default:


zlib)
BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup_zstd_bak' AS
ZSTD COMPRESSED BACKUPSET LEVEL 3;

– Compressed backup with a compression level specified


BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup_compress_bak' AS
COMPRESSED BACKUPSET LEVEL 3;

l Parallel backup:
– Database-determined splitting threshold
BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup_paral_bak'
PARALLELISM 6;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 95


GaussDB 100
User Guide (Standalone) 3 Database System Management

– Manually specified splitting threshold


BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/backup_paral_bak'
PARALLELISM 8 SECTION THRESHOLD 2G;

NOTE

n PARALLELISM 8 indicates that eight concurrent threads are enabled for backup. The
value range is [1, 8], and the default value is 4.
n SECTION THRESHOLD 2G indicates that the splitting threshold is 2 GB. If the size
of a data file exceeds 2 GB, the data file will be split to improve the parallel backup
efficiency. The value range is [128 MB, 32 TB]. If the splitting threshold is manually
specified, a larger value will result in a decrease in parallel efficiency, and a smaller
value will generate too many backup files. Therefore, you are not advised to specify the
splitting threshold. If you do not specify the threshold, the database will automatically
calculate the optimal threshold.
l Backup excluding specified tablespaces:
– Tablespace spc1 excluded
BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/exclude_bak1' EXCLUDE
FOR TABLESPACE spc1;

– Tablespaces spc1 and spc2 excluded


BACKUP DATABASE FULL FORMAT '/home/gaussdba/data/exclude_bak2' EXCLUDE
FOR TABLESPACE spc1,spc2;

NOTE

n For incremental backup with specified tablespaces excluded, ensure that the current
incremental backup and its baseline incremental backup have the same tablespaces
excluded. Otherwise, the incremental restoration will lead to data exceptions.
n For backup, you cannot specify tablespaces used by the system. Otherwise, errors will be
reported.
n After restoration for backup with a specified tablespace excluded, you need to manually
delete the objects that use the tablespace and manually delete the tablespace. Otherwise,
the tablespace and related objects will become unavailable.

For details about the BACKUP statement, see GaussDB 100 V300R001C00 R&D
Documentation (Standalone).

----End

3.8.4 Data Restoration


Prerequisites
l There are database backup files.
l The server has sufficient disk space.
l A database can be restored only when it is in NOMOUNT status, and data files in the
data directory must be deleted.
l The path specified during restoration must be the same as that specified during backup.
l By default, the database will be restored to primary (role: PRIMARY).

Related Concepts
GaussDB 100 backups can be restored in either synchronous or asynchronous mode. In
synchronous mode, the system returns execution results to a client only after restoration is
complete. In asynchronous mode, a database instance returns execution results to the client
after receiving the RESTORE DATABASE statement. To check whether the restoration is
successful, check the STATUS column in the DV_BACKUP_PROCESSES view.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 96


GaussDB 100
User Guide (Standalone) 3 Database System Management

Procedure
Step 1 Log in to the GaussDB 100 server as an administrator.

Step 2 Delete data files in the data directory.


rm -rf $GSDB_DATA/data/*

Step 3 Start the database in NOMOUNT mode.


python zctl.py -t start -m NOMOUNT

Step 4 Log in to the GaussDB 100 database.


zsql sys/Changeme_123@192.168.0.1:1888

sys/Changeme_123 indicates the username and password of user sys used for logging in to
the database. 192.168.0.1 indicates the IP address of the database server. 1888 indicates the
connected port.

Step 5 Restore the data files of the database.


l Synchronous restoration:
RESTORE DATABASE FROM '/home/gaussdba/data/backup01.bak';

l Asynchronous restoration:
RESTORE DATABASE FROM '/home/gaussdba/data/backup01.bak' DISCONNECT FROM
SESSION;

l Parallel restoration:
RESTORE DATABASE FROM '/home/gaussdba/data/backup01.bak' PARALLELISM 8;

NOTE

l If the backup media is a disk, concurrent-thread restoration will be supported. By default, the
number of concurrent threads is 4. You can also specify the PARALLELISM parameter in the
restoration command to customize the number. The parameter value range is [1, 8].
l If the backup media is not a disk, only single-thread restoration will be supported.

Step 6 Restore the database.


l Full restoration:
RECOVER DATABASE;

l Restoration to a specified time point:


RECOVER DATABASE UNTIL TIME '2018-06-29 15:28:54';

Step 7 If you need to demote the primary database after restoration to standby or cascaded standby,
run the following statements to change the database role and rebuild the database by referring
to HA Rebuilding:
l Demotion to standby:
ALTER DATABASE CONVERT TO PHYSICAL STANDBY MOUNT;

l Demotion to cascaded standby:


ALTER DATABASE CONVERT TO CASCADED PHYSICAL STANDBY MOUNT;

Step 8 Change the database status.


l After full restoration:
ALTER DATABASE OPEN;

l After restoration to a specified time point:


ALTER DATABASE OPEN RESETLOGS;

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 97


GaussDB 100
User Guide (Standalone) 3 Database System Management

3.8.5 Data Restoration Using ztrst


In GaussDB 100, the ztrst tool can be used to automatically restore data of a user tablespace.
Such restoration is based on full backup.

Prerequisites
l The ztrst tool package GAUSSDB100-V300R001C00-RESTORE.tar.gz has been
obtained from the GAUSSDB100-V300R001C00-TOOLS.tar.gz package.
l Schemas and tablespaces are in one-to-one mapping and are unique. One tablespace
cannot be shared by multiple schemas, and one schema cannot use multiple tablespaces.
l The disk where data restoration will be performed has sufficient space.
l There are no tmp_data and export_data directories in the temporary data directory
specified by parameter -D.
l All parameters must be set correctly.
l The backup set specified by parameter -B must be a full backup and be valid.
l Before using ztrst to restore data, you need to recreate a schema and the corresponding
tablespace in the database instance.
l The database version used in file backup must be the same as the tool version.

Precautions
l If the ztrst tool and database are deployed on different servers and the error message
"GS-00331, Whitelist rejects connection for user "jack", ip "192.168.0.1", current date
"2019-05-20 10:26:34.583", please check zhba.conf or tcp valid node configuration" is
returned, client access authentication has been configured for the database whose data
will be restored. In this case, add the IP address of the server where the ztrst tool is
running to the user whitelist or IP address whitelist of the database. For details, see
Configuring Client Access Authentication. In addition, do not add that address to the
IP blacklist to ensure that the ztrst tool has permission to access the database.
l If the ztrst tool and database are deployed on different servers and the error message
"GS-00341, Failed to verify SSL certificate, reason self signed certificate in certificate
chain" is returned, SSL authentication has been configured for the server of the database
whose data will be restored. The corresponding private key, certificate, CA root
certificate, and client parameters for the SSL connection must be configured on the ztrst
client. For details, see Database Configuration > Configuring the Database
Connection > Establishing TCP/IP Connections in SSL Mode in GaussDB 100
V300R001C00 Security Hardening Guide (Standalone). After the configuration, you do
not need to restart the database. When configuring client parameters, you only need to
configure ZSQL_SSL_CERT, ZSQL_SSL_KEY, ZSQL_SSL_CA,
ZSQL_SSL_CRL (optional), and ZSQL_SSL_MODE. Do not configure
ZSQL_SSL_KEY_PASSWD. If ZSQL_SSL_KEY is configured as an encrypted
private key, you need to enter the encrypted password for the key in interactive mode
when using the ztrst tool to restore data. In addition, you need to specify -C
PARALLEL=1,DDL_PARALLEL=1 in the command line of the tool.

Procedure
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 98


GaussDB 100
User Guide (Standalone) 3 Database System Management

Step 2 Log in to the database, and recreate a schema and the corresponding tablespace.
1. Log in to the GaussDB 100 database as an administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation


and the administrator password. 192.168.0.1 indicates the IP address of the database
server. 1888 indicates the connected port.
2. Recreate a schema and the corresponding tablespace.
Assume that the new schema is jim and its default tablespace is tbs_jim.
CREATE TABLESPACE tbs_jim EXTENTS 128 DATAFILE 'dfile1_jim' SIZE 32G
AUTOEXTEND ON NEXT 10G;
CREATE USER jim IDENTIFIED BY database_123 DEFAULT TABLESPACE tbs_jim;

3. Exit the current connection.


EXIT

Step 3 Log in to the server where the full physical backup file is located as user root.
Step 4 Create a user and its group for running the ztrst tool on the server, and configure their
permissions to be less than or equal to 0750.
groupadd toolgrp
useradd -g toolgrp -d /home/ztrstdba -m -s /bin/bash ztrstdba

Set the password for user ztrstdba.


passwd ztrstdba

Step 5 Switch to user ztrstdba.


su - ztrstdba

Step 6 Upload the ztrst tool package GAUSSDB100-V300R001C00-RESTORE.tar.gz to the /


home/ztrstdba directory.
Step 7 Decompress the ztrst tool package GAUSSDB100-V300R001C00-RESTORE.tar.gz.
tar -zxvf GAUSSDB100-V300R001C00-RESTORE.tar.gz

total 12
drwx------ 2 ztrstdba toolgrp 4096 May 11 16:43 add-ons
drwx------ 2 ztrstdba toolgrp 4096 May 11 16:43 bin
drwx------ 2 ztrstdba toolgrp 4096 May 11 16:43 lib

Step 8 Configure environment variables.


1. Configure the environment variable LD_LIBRARY_PATH.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/ztrstdba/GAUSSDB100-V300R001C00-
RESTORE/lib:/home/ztrstdba/GAUSSDB100-V300R001C00-RESTORE/add-ons

2. (Optional) Add the bin path in the tool package to the environment variable PATH.
If you do not add the bin path in the tool package to the environment variable PATH, the
format for using the ztrst tool in the bin path of the tool will be ./ztrst. If you add the
path, the format will be ztrst or ./ztrst.
export PATH=$PATH:/home/ztrstdba/GAUSSDB100-V300R001C00-RESTORE/bin

Step 9 Go to the directory where the ztrst script is stored.


cd /home/ztrstdba/GAUSSDB100-V300R001C00-RESTORE/bin

Step 10 Run the ztrst tool to restore data.


ztrst -p 1881 -D /temp -B /data/backup/bak1 -U jim -T tbs_jim -S 192.168.0.1:1888

Please enter sys password:


*********

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 99


GaussDB 100
User Guide (Standalone) 3 Database System Management

Please enter jim password:


************

During data restoration, you need to enter the passwords of user SYS and the schema in
interactive mode. For details about ztrst parameters, see Database Management Tools >
ztrst in GaussDB 100 V300R001C00 Operation Guide to Tools (Standalone).

----End

3.8.6 Flashback
GaussDB 100 supports table flashback. FLASHBACK TABLE restores a table to an earlier
state in the event of human or application errors. The time in the past to which the table can
be flashed back is dependent on the amount of undo data in the system. Note that GaussDB
100 cannot restore a table to an earlier state across any DDL operations that change the
structure of the table. Table flashback can be implemented by:

l Restoring table data to a specified time point or SCN point. This mode is suitable when
users have incorrectly adjusted the data.
l Restoring tables that have been deleted by mistake from recycle bins. This mode is
suitable when users have incorrectly executed DROP TABLE.

For details about the FLASHBACK TABLE syntax, see SQL Syntax Reference > SQL
Syntax > FLASHBACK TABLE in GaussDB 100 V300R001C00 R&D Documentation
(Standalone).

Prerequisites
l To run this statement, you must have the FLASHBACK permission. To flash back
tables of other users, the FLASH ANY TABLE permission is required.
l The recycle bin is open, that is, the value of the database parameter RECYCLEBIN is
TRUE.

Precautions
l By default, GaussDB 100 does not forcibly convert the DATE type and this type needs to
be converted by using functions.
l In the table flashback process, a full table scan is performed, which affects the
performance and blocks the modification of the table content.
l When a table is flashed back, the system reorganizes table content based on the SCN
point. In this case, row IDs may move.
l If the time point for table flashback is too early, an error like "snapshot too old" may be
reported upon undo log reuse.
l Flashback cannot be performed during database restart or rollback.

Procedure
Step 1 Log in to the GaussDB 100 database.
zsql
conn jack/database_123@192.168.0.1:1888

jack/database_123 indicates the username and password used for logging in to the database.
192.168.0.1 indicates the IP address of the database server. 1888 indicates the connected port.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 100


GaussDB 100
User Guide (Standalone) 3 Database System Management

Step 2 Run FLASHBACK TABLE.


l Flashback to a specified time point:
FLASHBACK TABLE staffs TO TIMESTAMP TO_TIMESTAMP('2018-12-28 13:14:15', 'YYYY-
MM-DD HH24:MI:SS');

l Flashback to an SCN point:


FLASHBACK TABLE staffs TO SCN 10063180815101953;

The system supports only a query for the current SCN point. If there is a major operation
or operation on a large amount of data, record the current SCN point before the
operation. You can run the SELECT CURRENT_SCN FROM DV_DATABASE
statement to query for and record the current SCN point used by the database.
l Flashback on a table in the recycle bin after the DROP operation is performed:
FLASHBACK TABLE staffs TO BEFORE DROP;

NOTE

You can query the table data of a specified SCN point or at a specified time point.
-- Query data after flashback to a specified time point:
SELECT * FROM staffs AS OF TIMESTAMP TO_TIMESTAMP('2018-12-28 13:14:15',
'YYYY-MM-DD HH24:MI:SS');
-- Query data after flashback to an SCN point:
SELECT * FROM staffs AS OF SCN 10063180815101953;

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 101


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

4 Routine O&M Management

4.1 Starting or Stopping a Database


Scenario
Starting a database is actually creating an instance of the database and determining the start
mode. Different start modes are supported, facilitating database development and
maintenance.

Related Concepts
GaussDB 100 supports the following three start modes:
l NOMOUNT: An instance is started, and no database is mounted.
In this mode, the system only creates an instance but does not mount the database. It
creates various memory structures and service processes for the instance but does not
open any data files. In this mode, you can access only the data dictionary views related to
the SGA memory, including DV_PARAMETERS and DV_SESSIONS. Information in
these views is obtained from the SGA memory and is irrelevant to the database.
l MOUNT: A database is mounted but not opened.
In this mode, the system mounts the database for the instance but keeps the database shut
down. Mounting a database will open database control files, and data files and redo log
files cannot be read or written. Therefore, you cannot perform operations on the database
in this situation. In this mode, you can access only the data dictionary views related to
the control files, which include V$THREAD, DV_DATABASE, DV_DATA_FILES,
and DV_LOG_FILES. Information in these views is obtained from the control files.
l OPEN: A database is opened.
In this mode, you can only use or develop a database, instead of maintaining it.
GaussDB 100 supports the following four stop modes:
l IMMEDIATE: Client requests are terminated, connected sessions are ended, unfinished
transactions are rolled back, checkpoint operations are performed, and primary processes
are exited.
l ABORT: Client requests are terminated, connected sessions are ended, and primary
processes are exited.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 102


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l NORMAL: Client requests are terminated, the system waits for connected sessions to
normally end (which may take a long time), checkpoint operations are performed, and
primary processes are exited.
l KILL: A database instance is urgently stopped. This mode is only as a special handling
measure in abnormal scenarios. It can be used to stop a database instance in ABORT
mode regardless of whether password-free login is enabled. It is not recommended
unless for special requirements.

Precautions
l If no start mode is specified, GaussDB 100 will be started in OPEN mode.
l If no stop mode is specified, GaussDB 100 will be stopped in NORMAL mode.
l At least 918 MB memory space is required for supporting the SGA memory when a
database instance is started.

Starting a Database
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Start a database instance.

The database can be started in OPEN, MOUNT, or NOMOUNT mode. The $


{GSDB_HOME}/bin directory must be opened before the start.
l OPEN: The database is started normally.
python zctl.py -t start

l MOUNT: The database is mounted but not started.


python zctl.py -t start -m MOUNT

l NOMOUNT: The database is not mounted. Users can communicate with the database
but cannot use any files in the database.
python zctl.py -t start -m NOMOUNT

NOTE

If -m is not specified, the OPEN mode will be used.

----End

Stopping a Database
Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Stop the database instance. The ${GSDB_HOME}/bin directory must be opened before the
stop.
l NORMAL: The database is normally stopped.
python zctl.py -t stop

l IMMEDIATE: Transactions are rolled back, and the database instance is stopped.
python zctl.py -t stop -m IMMEDIATE

l ABORT: The instance is immediately stopped.


python zctl.py -t stop -m ABORT

l KILL: The instance is urgently stopped.


python zctl.py -t kill

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 103


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

NOTE

– If -m is not specified, the NORMAL mode will be used.


– If password-free login is disabled, you need to specify the -P parameter when stopping a
database.
– If password-free login is modified online, you need to run KILL to stop a database instance.

----End

4.2 HA Maintenance
GaussDB 100 supports primary and standby databases for HA DR purposes.

NOTE

If databases are deployed in HA DR mode, perform security hardening on both the primary and standby
databases.

4.2.1 Protection Modes


The HA system provides three data protection modes: Maximum Protection, Maximum
Availability, and Maximum Performance. You can query the value of this parameter in the
PROTECTION_MODE column in DV_DATABASE.

NOTE

The protection modes take effect only on primary nodes, instead of standby or cascaded standby nodes.
After a build operation, the protection mode of the primary node will be automatically synchronized to
the standby nodes. Otherwise, if the protection mode of the primary node is changed, the automatic
synchronization will not be performed on the standby nodes. Although a standby node is not used, you
are still advised to synchronize its protection mode since it may be promoted to primary later.

Maximum Protection
This mode ensures zero data loss.

In this mode, transaction logs are not only written into local log files, but also into the log
files of standby databases. Transactions are committed in a primary database only when data
is available in at least one standby database. If all standby databases are unavailable due to
faults (for example, network disconnection), services on the primary database will be blocked
to prevent data loss.

Only LGWR SYNC is supported for replication from a primary database to standby
databases.

This mode needs to be set when the database is in MOUNT mode. The command is as
follows:
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PROTECTION;

In maximum protection mode:

l The ARCHIVE_DEST_n parameter (n is not 1) specifies a standby database for


archiving logs. You must specify the SYNC attribute for this parameter for redo logs in
least one standby database. Otherwise, if the ASYNC attribute is specified for all
standby databases, starting a database will fail.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 104


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l If the SYNC and AFFIRM attributes are specified for ARCHIVE_DEST_n (n is not 1),
transaction logs will be committed on the primary database only after the logs of all
standby databases with AFFIRM configured are written to the transaction logs.
l If the SYNC and NAFFIRM attributes are specified for ARCHIVE_DEST_n (n is not
1), transaction logs are directly written to the primary database without waiting for the
standby database logs to be written.

Maximum Availability
This mode provides the highest data protection policy without affecting the availability of the
primary database.
Its implementation is similar to the maximum protection mode. The transaction log must be
written to the log file of at least one standby node before the local transaction is committed.
There is also a difference between the two. In maximum availability mode, if standby
databases are unavailable due to a fault, services in the primary database will not be blocked.
Although data will not be lost in most cases, data consistency cannot be completely ensured.
Only LGWR SYNC is supported for replication from a primary database to standby
databases.
This mode can be set regardless of the database mode. The command is as follows:
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE AVAILABILITY;

In maximum availability mode:


l If the SYNC and AFFIRM attributes are specified for ARCHIVE_DEST_n (n is not 1)
and the standby databases with AFFIRM configured are normally connected to the
primary one, transaction logs will be committed on the primary database only after the
logs of all standby databases with AFFIRM configured are written to the transaction
logs.
l If the SYNC and NAFFIRM attributes are specified for ARCHIVE_DEST_n (n is not
1), transaction logs are directly written to the primary database without waiting for the
standby database logs to be written.

Maximum Performance
This mode provides the highest data protection policy without affecting the performance of
the primary database. It is the default mode.
This mode allows transactions to be committed at any time. The transaction logs of a primary
database must be written into at least one standby database, and this write can be
asynchronous. In ideal network conditions, this mode provides data protection similar to the
maximum availability mode and has slight impact on primary database performance.
Both LGWR SYNC and ASYNC are supported for replication from a primary database to
standby databases.
This mode can be set regardless of the database mode. The command is as follows:
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PERFORMANCE;

4.2.2 HA Rebuilding
Currently, only full HA rebuilding is supported. In the following scenarios, the standby or
cascaded standby database needs to be rebuilt:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 105


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l When establishing an HA primary/standby environment, a database needs to be created


on the standby node.
l If the value of DATABASE_CONDITION obtained from the DV_DATABASE view is
NEED REPAIR, the database needs to be rebuilt.
l If a database cannot be started due to a fault that is caused by unexpected file deletion or
damage and cannot be fixed, the database needs to be rebuilt.

Procedure
Step 1 Log in to the server of the standby or cascaded standby database to be rebuilt as the OS user
installing the GaussDB 100 database.
Step 2 Go to the directory where the zctl.py script is stored.
cd /home/gaussdba/app/bin

In this command, /home/gaussdba/app is the installation directory of the database.


Step 3 Rebuild the standby or cascaded standby database.
python zctl.py -t build -D /home/gaussdba/data

In this command, /home/gaussdba/data is the data directory of the database.

Step 4 Log in to the GaussDB 100 database as a database administrator.


zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 5 Check whether the database status is normal.


SELECT DATABASE_ROLE, DATABASE_CONDITION FROM DV_DATABASE;

DATABASE_ROLE DATABASE_CONDITION
------------------------------ ------------------
PHYSICAL_STANDBY NORMAL

1 rows fetched.

----End

4.2.3 Status Query


Common views for primary/standby query include DV_DATABASE,
DV_ARCHIVE_DEST_STATUS, DV_STANDBYS, DV_ARCHIVE_GAPS,
DV_LOG_FILES, and DV_HA_SYNC_INFO.

DV_DATABASE
The following table describes HA-related columns in this view, their types, and meanings.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 106


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Table 4-1 DV_DATABASE columns


Column Name Type Description

PROTECTION_MO VARCHAR(20) Database protection mode


DE (MAXIMUM_PROTECTION/
MAXIMUM_AVAILABILITY/
MAXIMUM_PERFORMANCE)

DATABASE_ROLE VARCHAR(30) Database role (PRIMARY/


PHYSICAL_STANDBY/
CASCADED_PHYSICAL_STANDBY)

DATABASE_CON VARCHAR(16) Database status (NORMAL/STARTING/


DITION DEMOTING/PROMOTING/FAILOVER
PROMOTING/BUILDING/NEED
REPAIR/NO PROCESS/
DISCONNECTED)

SWITCHOVER_ST VARCHAR(20) Primary/standby database switchover status


ATUS (TO PRIMARY/WAIT ROLLBACK/
ROLLBACK END/CHECKPOINT END/
WAIT SEND LOGFILE/SEND LOGFILE
END/WAIT PEER PROMOTE/PEER
PROMOTE END/PEER DEMOTE END/
ANOTHER RUNNING/NOT READY/NOT
ALLOWED)

FAILOVER_STATU VARCHAR(20) Whether the FAILOVER command can be


S executed (TO PRIMARY/NOT
ALLOWED)

DV_ARCHIVE_DEST_STATUS
The following table describes columns in this view, their types, and meanings.

Table 4-2 DV_ARCHIVE_DEST_STATUS columns


Column Name Type Description

DEST_ID INTEGER Archive destination ID (0–


9)

DEST_NAME VARCHAR(256) Archive destination name

STATUS VARCHAR(9) Destination status (VALID/


INACTIVE)

TYPE VARCHAR(30) Archive destination database


type (PHYSICAL)

DATABASE_MODE VARCHAR(11) Archive destination database


mode (READ-ONLY/
READ-WRITE)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 107


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Column Name Type Description

PROTECTION_MODE VARCHAR(20) Protection mode

DESTINATION VARCHAR(256) Destination path

DB_UNIQUE_NAME VARCHAR(30) Instance name

SYNCHRONIZATION_S VARCHAR(20) Synchronization status


TATUS l CHECK
CONFIGURATION:
Synchronization with the
destination is not
possible because this
database is not in either
MAXIMUM
PROTECTION or
MAXIMUM
AVAILABILITY mode,
or the
ARCHIVE_DEST_n
parameter has not been
configured with the
SYNC attribute.
l CHECK NETWORK:
The primary database
cannot connect to its
standby database.
l OK: The archive
destination (standby
database) is synchronized
with the primary
database.
l NOT AVAILABLE: The
standby database cannot
obtain the
synchronization status.

SYNCHRONIZED VARCHAR(8) Whether the destination has


been synchronized
(YES/NO/UNKNOWN)

DV_STANDBYS
The following table describes columns in this view, their types, and meanings.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 108


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Table 4-3 DV_STANDBYS columns


Column Name Type Description

PROCESS VARCHAR(20) Thread name. Values are as


follows:
l RFS: log receiving
thread
l MRP: log replay thread
l ARCH: archive thread
l FAL: archive log fetch
thread

STATUS VARCHAR(20) Thread status

RESETLOG_ID INTEGER RESETLOG ID of the


archived redo log

THREAD# VARCHAR(20) Archived redo log thread


number

SEQUENCE# INTEGER Archived redo log sequence


number

FLUSH_POINT VARCHAR(128) Standby database log flush


point

PRIMARY_CURR_POINT VARCHAR(128) Primary database log flush


point

REPLAY_POINT VARCHAR(128) Standby database log replay


point

DV_ARCHIVE_GAPS
The following table describes columns in this view, their types, and meanings.

Table 4-4 DV_ARCHIVE_GAPS columns


Column Name Type Description

THREAD# INTEGER Thread ID. The value is 1.

LOW_SEQUENCE# VARCHAR( Current replay point of the standby


32) database, including the reset ID and ASN.
For example, 1_101.

HIGH_SEQUENCE# VARCHAR( Latest archive file on the standby database,


32) for example, 2_10

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 109


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

DV_LOG_FILES
This view is used to display information such as the log file size and name. The following
table describes columns in this view, their types, and meanings.

Table 4-5 DV_LOG_FILES columns


Column Name Type Description

ID INTEGER Log file ID

STATUS VARCHAR(20) Log file status (ACTIVE/


INACTIVE/CURRENT)

TYPE VARCHAR(20) Log file type (STANDBY/


ONLINE)

FILE_NAME VARCHAR(256) Log file name

BYTES BIGINT Log file size

WRITE_POS BIGINT Log write position

FREE_SIZE BIGINT Free log space size

RESET_ID INTEGER Reset ID of the log

ASN INTEGER Archived serial number


(ASN) of the log

BLOCK_SIZE INTEGER Log block size

CURRENT_POINT VARCHAR(128) Log flush point

DV_HA_SYNC_INFO
This view is used to display information about log synchronization (log sending). The
following table describes the columns, types, and meanings.

Table 4-6 DV_HA_SYNC_INFO columns


Column Name Type Description

THREAD# INTEGER Sequence number of the log


sending thread

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 110


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Column Name Type Description

STATUS VARCHAR(20) Status of the log sending


thread
Values are:
l NOT RUNNING: The
corresponding link has
not been used.
l DISCONNECTED: The
corresponding link has
been used but
disconnected. The
primary database
attempts to reconnect to
the standby database.
l CONNECTED: The
primary database has
connected to the standby
database but is not ready
for sending logs.
l SHIFTING: The
primary database has
been ready and entered
the normal log sending
state.

LOCAL_HOST VARCHAR(64) Local database IP address

ROLE_VALID VARCHAR(13) Condition for the


ARCHIVE_DEST_n
parameter on the local
database to take effect.
Values are:
l PRIMARY_ROLE: The
parameter takes effect
only when the local
database is primary.
l STANDBY_ROLE: The
parameter takes effect
only when the local
database is standby.
l ALL_ROLES: The
parameter takes effect no
matter whether the local
database is primary or
standby.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 111


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Column Name Type Description

NET_MODE VARCHAR(6) Log transmission mode.


Values are:
l SYNC: synchronous
mode
l ASYNC: asynchronous
mode

PEER_HOST VARCHAR(64) IP address of the database


that receives logs

PEER_PORT INTEGER Port number of the database


that receives logs

LOCAL_SEND_POINT VARCHAR(128) Log point where the primary


database sends logs

PEER_FLUSH_POINT VARCHAR(128) Log point where the standby


database receives logs and
flushes them to disk

PEER_BUILDING VARCHAR(6) Whether the standby


database is being built
l TRUE: The standby
database is being built.
l FALSE: The standby
database is not being
built.

LOCAL_LFN BIGINT Local log flush number


(LFN)

LOCAL_LSN BIGINT Local log sequence number


(LSN)

PEER_LFN BIGINT Peer LFN

PEER_LSN BIGINT Peer LSN

FLUSH_LAG BIGINT Delay in receiving logs on


the peer end (unit: ms)
Value -1 indicates that the
primary database has not
sent logs to the standby
database. In this case,
FLUSH_LAG is invalid.

REPLAY_LAG BIGINT Delay in replaying logs on


the peer end (unit: ms)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 112


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

4.2.4 Logical Replication

Scenario
In GaussDB 100, logical replication parses redo logs that contain logical log information to
obtain data changes of database tables, and then replays the changes in a target data source. In
this way, logical replication replicates GaussDB 100 data changes to other homogeneous or
heterogeneous data sources in quasi real time. Logical replication is more flexible than
physical replication, which has strong dependency on the physical formats of logs. Logical
replication can implement GaussDB 100 cross-version replication and GaussDB 100
replication to other heterogeneous databases (such as Oracle databases). It also provides
customization support when the structures of source and target database tables are
inconsistent. Logical replication can be used for incremental data backup between primary
and standby databases, data synchronization between different service systems, and online
data migration during system upgrade.

When service data needs to be synchronized between a GaussDB 100 database and other
commercial databases:

l Synchronization from other commercial databases to GaussDB 100: GaussDB 100


provides standard JDBC interfaces, and other commercial databases use their logical
replication tools to replicate service data to GaussDB 100 over the JDBC interfaces.
l Synchronization from GaussDB 100 to other commercial databases or data sources:
GaussDB 100 provides a logical replication tool to replicate its service data to other
commercial databases or data sources, such as a message queue. For details, see Logical
Replication.

Prerequisites
l Java JDK 1.8 or later has been installed in the operating environment.
l The installation package for the logical replication tool GAUSSDB100-V300R001C00-
LOGICREP.tar.gz has been obtained from GAUSSDB100-V300R001C00-
TOOLS.tar.gz.

Precautions
l Currently, the logical replication service is preconfigured to support the following types
of target data sources: Oracle, GaussDB 100, and Kafka. Other types of data sources can
be supported by developing corresponding plug-ins.
l For primary/standby replication, you need to install, configure, and start the logical
replication service on both the primary and standby databases. In this case, only the
primary database has logical replication in working mode.
l The table data of user SYS does not support logical replication.
l Logical replication needs to read archive and online logs. Therefore, you need to enable
the archive logging function of GaussDB 100 and disable the automatic archive log
deletion function of GaussDB 100 to prevent archive logs from being deleted by mistake.
l In standalone deployment, logical replication does not provide the alarm function. You
do not need to pay attention to the error information "cannot get $DM_AGENT_HOME
env or DM_AGENT_HOME path is invalid." in the run logs of logical replication
because this error is caused by a lack of DM and does not affect the functionality of
logical replication.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 113


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l The logical replication service works only on the data updated after the global logical
replication switch and table-level logical replication switch are enabled. The source table
data before logical replication is enabled cannot be replicated to the target database.
l If a target database is GaussDB 100 and "errMsg=the connecting IP is invalid according
to IP white list" is recorded in the zlogcatcher.rlog file, client access authentication has
been configured for the target database. In this case, add the IP address of the server
where the source database is located to the user whitelist or IP address whitelist of the
target database by referring to Configuring Client Access Authentication. In addition,
the IP address must not be added to the IP address blacklist, ensuring that the logical
replication tool has permission to access the target database.
l You need to create a database user LREP for the logical replication service, create a
logical replication progress table which is required in the replication process as user
LREP, and grant required permissions to user LREP. For details about the minimum
permissions required for user LREP, see Table 4-7. User LREP is only used to query
for the metadata of a table where data replication is needed, and to record the logical
replication progress. Note that user LREP is not associated with the users in the table
(where data replication is needed) specified in the repconf_db.xml file.

Table 4-7 Minimum permissions required for logical replication users


Minimum Permission, Source Minimum Permission, Target
Database Database

CONNECT CREATE SESSION


RESOURCE UPDATE ON user_name.table_name
SELECT ON SYS.SYS_TABLES INSERT ON user_name.table_name
SELECT ON SYS.SYS_COLUMNS DELETE ON user_name.table_name
SELECT ON SYS.SYS_USERS
SELECT ON
SYS.SYS_CONSTRAINT_DEFS
SELECT ON SYS.SYS_LOGIC_REPL
SELECT ON SYS.DV_DATABASE
SELECT ON SYS.DV_LOG_FILES
SELECT ON
SYS.DV_ARCHIVED_LOGS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 114


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Procedure

Figure 4-1 Flowchart for configuring and starting logical replication

Procedure – Configuring and Starting Logical Replication


The following describes database connection information used in the steps below:

l database_123 is the new password of the database administrator gaussdba. When a


database is installed, the default password for the database administrator gaussdba to log
in to the database is Changeme_123. To ensure information security, change the default
password as soon as possible after the database is installed and the first login.
l gaussdba is the database user.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 115


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l 127.0.0.1 indicates a local database login. For remote logins, enter the IP address of the
server where the target database is located.
l 1888 is the number of the database listening port.

Step 1 On the primary and standby nodes, decompress and install the logical replication tool.
The following operations 1 to 8 in this step must be performed on both the primary and
standby nodes.
1. Log in to the primary GaussDB 100 node as user root.
2. Create a directory for storing the logical replication tool as planned.
mkdir -p /opt/software/tools

3. Upload the installation package of the logical replication tool GAUSSDB100-


V300R001C00-LOGICREP.tar.gz to the created directory /opt/software/tools.
4. Go to the directory where the logical replication tool is stored.
cd /opt/software/tools

5. Decompress the installation package to the /opt/software/tools directory.


The GAUSSDB100-V300R001C00-LOGICREP folder will be generated after the
installation package is decompressed.
tar -zxvf GAUSSDB100-V300R001C00-LOGICREP.tar.gz -C /opt/software/tools
[root@plat tools]$ ll

total 7940
drwxr-xr-x. 3 root root 4096 Apr 26 15:13 GAUSSDB100-V300R001C00-LOGICREP
-rw-r--r--. 1 root root 8113682 Apr 29 16:24 GAUSSDB100-V300R001C00-
LOGICREP.tar.gz

6. Go to the GAUSSDB100-V300R001C00-LOGICREP directory.


cd GAUSSDB100-V300R001C00-LOGICREP
[root@plat GAUSSDB100-V300R001C00-LOGICREP]$ ll

total 4
drwx------. 5 root root 4096 Apr 26 15:13 logicrep

7. Change the owner and owner group of the logicrep directory to the database installation
user gaussdba and its group dbgrp, respectively.
chown -R gaussdba:dbgrp /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep

8. (Optional) If the target database is an Oracle database, download the ojdbc driver of the
corresponding version from the Oracle official website and upload the driver to the
logicrep/lib directory.
NOTE

– Ensure that the permission for the ojdbc driver is 500. If the permission is not 500, run the
following command as user root to change the permission:
chmod 500 File name
– Ensure that the owner of the ojdbc driver is the database installation user gaussdba and the
owner group is dbgrp. If the owner and owner group are incorrect, run the following
command as user root to change them:
chown gaussdba:dbgrp /opt/software/tools/GAUSSDB100-V300R001C00-
LOGICREP/logicrep/lib/File name

9. Switch to user gaussdba.


su - gaussdba

10. (Optional) Go to the logicrep directory and view related directories.


cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep
[gaussdba@plat logicrep]$ ll

total 6772
lrwxrwxrwx 1 gaussdba gaussdba 51 May 14 09:24

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 116


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

com.huawei.gauss.logicrep.jar -> com.huawei.gauss.logicrep-


V300R001C00SPC200B128.jar
-r-x------ 1 gaussdba gaussdba 6899687 May 14 09:24 com.huawei.gauss.logicrep-
V300R001C00SPC200B128.jar
drwx------ 5 gaussdba gaussdba 4096 May 14 09:24 conf
drwx------ 2 gaussdba gaussdba 4096 May 14 09:24 ctrl
drwx------ 2 gaussdba gaussdba 4096 May 14 09:24 lib
drwx------ 2 gaussdba gaussdba 4096 May 14 09:24 plugin
-r-x------ 1 gaussdba gaussdba 1415 May 14 09:24 shutdown.sh
-rw------- 1 gaussdba gaussdba 7 May 14 09:24 startup.ini
-r-x------ 1 gaussdba gaussdba 5206 May 14 09:24 startup.sh

Related directories are as follows:


– com.huawei.gauss.logicrep.jar -> com.huawei.gauss.logicrep-
V300R001C00.jar: soft link to the JAR package of the logical replication service
– com.huawei.gauss.logicrep-V300R001C00.jar: JAR package of the logical
replication service
– conf: directory storing configuration files
n repconf: directory storing the definition file of replication relationships
n sec: directory storing key configuration files
– ctrl: directory storing control files for log extraction and replay
– lib: directory of the dependent, third-party library
– plugin: plug-in directory, storing customized plug-in JAR packages
– startup.sh: logical replication startup script
– shutdown.sh: logical replication stop script
– startup.ini: configuration file of startup parameters
Step 2 On the primary node, configure the startup parameters of the logical replication service
process.
1. Go to the conf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf

2. Open the init.properties file and press i to enter the insert mode.
vi init.properties

3. Change the values of the startup parameters.


All modifications take effect only after the logical replication service is restarted. The
conf/init.properties file template is as follows (italic indicates an example value, and an
actual value is needed):
#unit: number of replayer threads
#value range:[1,32]
replayer.thread.number=1

#specify which kind of replayer is used


replayer.class=com.huawei.gauss.logicrep.replayer.jdbc.JdbcReplayer
#replayer.class=com.huawei.gauss.logicrep.replayer.kafka.KafkaReplayer

#unit: number of slots


#value range:[1024,2048]
dispatch.queue.size=1024

#unit: number of transactions


#value range:[100,300]
transaction.buffer.size=100

#unit: MB
#value range:[100,500]
transaction.buffer.memory.size=100

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 117


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

#unit: MB
#value range:[300,800]
logentry.buffer.size=500

#checkpoint interval: millisecond


#value range:[3000,30000]
checkpoint.interval=3000

#where checkpoint is persisted:


# sourcedb - logic_rep_progress table on source db
checkpoint.location=sourcedb

#logic_rep_progress table version.


#it is for compatibility, since some deployments use old table version now.
#for new deployment, don't need to change this.
#if it is not set, v1 used.
# v1 - old version: ID,COMMITTED_SCN,LOGPOINT,UPDATE_TIME
# v2 - new columns used:
ID,COMMITTED_TX_SCN,COMMITTED_TX_TIME,LOGPOINT,UPDATE_TIME
checkpoint.table.version=v2

#byte order of redo logfiles to be extracted


# little - logfiles generated on little endian platform
# big - logfiles generated on big endian platform
logfile.endian.type=little

#path_to_keystore_file(for zenith)
javax.net.ssl.keyStore=

#encrypted keyStorePassword(for zenith)


javax.net.ssl.keyStorePassword=

#path_to_trustStore_file(for oracle)
javax.net.ssl.trustStore=

#encrypted trustStorePassword(for oracle)


javax.net.ssl.trustStorePassword=
The parameters are as follows:
– replayer.thread.number
Specifies the number of replay threads. It is evaluated based on the size of
transactions that can be concurrently executed. When the requirements for
performance are low, use the default configuration, that is, single-thread replay.
– replayer.class
Specifies the replay class in use. When you customize a plug-in based on the
software development kit (SDK) of logical replication, set this parameter to the
name of the replay class that is implemented.
– dispatch.queue.size
Specifies the size of the work queue. It is evaluated based on the size of transactions
that can be concurrently executed. When the requirements for performance are low,
use the default configuration.
– transaction.buffer.size
Specifies the maximum number of transactions that can be stored in the transaction
buffer. When the buffer is full, the system waits for a replay thread to process. Use
the default configuration in the initial phase. Later, you can adjust the value of this
parameter by observing the high-water mark (HWM) for buffering performance
logs.
– transaction.buffer.memory.size
Specifies the maximum memory space occupied by each transaction. When the
space occupied by a transaction exceeds the default value, logical replication fails.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 118


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

In this case, increase the value of this parameter to ensure that transactions
occupying large space perform the replication correctly.
– logentry.buffer.size
Specifies the size of the logentry buffer. Use the default configuration in the initial
phase. Later, you can adjust the value of this parameter by observing the HWM for
buffering performance logs.
– checkpoint.interval
Specifies an interval for storing the replay progress. The default configuration is
recommended. If this parameter is set too small, the progress may be frequently
stored, affecting performance.
– checkpoint.location
Specifies the location for storing the parsing and replay progress of physical logs. It
stores the location of the physical log where the logical replication service stopped
parsing and the latest transaction SCN that is committed to the target database. The
value can only be sourcedb, indicating that the progress information of the logical
replication service is stored in the LOGICREP_PROGRESS table of the logical
replication service user created in the source database.
– checkpoint.table.version
Specifies the version of the logical replication progress table stored in the source
database. In an old version of the table, there are ID, COMMITTED_SCN,
LOGPOINT, and UPDATE_TIME columns. In an upgraded version of the table,
the COMMITTED_TX_TIME column is added. This version is identified by v2.
For a logical replication service that has been launched and running, you do not
need to specify this parameter, or you can set this parameter to v1, indicating the
old version of the logical replication progress table in the source database.
For a logical replication service that is newly launched, this parameter in the
parameter file of the logical replication installation package has been set to v2 by
default. The logical replication progress table in the source database will be created
based on the structure of the new version of the table.
– logfile.endian.type
Specifies whether to use the big endian or little endian mode for storing data in
memory. The big endian or little endian mode refers to the configuration of the
machine that generates the log files required by the logical replication tool. When
the big endian mode is used, the high byte of data is stored in the low address of
memory, and the low byte of data is stored in the high address of memory. When
the little endian mode is used, the high byte of data is stored in the high address of
memory, and the low byte of data is stored in the low address of memory.
– javax.net.ssl.keyStore
Specifies the path of the keystore file, which must contain the file name. This
parameter is used only when useSSL is set to true and the client needs to be
authenticated.
– javax.net.ssl.keyStorePassword
Specifies the ciphertext of the keystore password. This parameter is used only when
useSSL is set to true and the client needs to be authenticated. For details about how
to generate the ciphertext, see Step 4.
– javax.net.ssl.trustStore=
Specifies the path of the truststore file, which must contain the file name. This
parameter is used only when SSL is configured for the Oracle database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 119


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

– javax.net.ssl.trustStorePassword=
Specifies the ciphertext of the truststore password. This parameter is used only
when SSL is configured for the Oracle database. For details about how to generate
the ciphertext, see Step 4.
4. Press Esc and enter :wq to save the settings and exit.

Step 3 Create and configure users for the logical replication service on the source and target
databases.
l Create and configure a user for the logical replication service on the source database
GaussDB 100.
Perform this operation only on the primary GaussDB 100 node. The created user will be
synchronized to the standby node in real time.
a. Log in to the primary GaussDB 100 node as user gaussdba.
b. Log in to the database as a database administrator.
zsql gaussdba/database_123@127.0.0.1:1888

c. Run the following SQL statements to create a logical replication user LREP, a
logical replication progress table LREP.LOGICREP_PROGRESS, and grant the
CONNECT and RESOURCE roles as well as the permission for reading related
system catalogs and views to the user LREP:
CREATE USER LREP IDENTIFIED BY database_234;
GRANT CONNECT, RESOURCE TO LREP;
GRANT SELECT ON SYS.SYS_TABLES TO LREP;
GRANT SELECT ON SYS.SYS_COLUMNS TO LREP;
GRANT SELECT ON SYS.SYS_USERS TO LREP;
GRANT SELECT ON SYS.SYS_CONSTRAINT_DEFS TO LREP;
GRANT SELECT ON SYS.SYS_LOGIC_REPL TO LREP;
GRANT SELECT ON SYS.DV_DATABASE TO LREP;
GRANT SELECT ON SYS.DV_LOG_FILES TO LREP;
GRANT SELECT ON SYS.DV_ARCHIVED_LOGS TO LREP;
CREATE TABLE LREP.LOGICREP_PROGRESS
(
ID VARCHAR(128),
COMMITTED_TX_SCN BIGINT,
COMMITTED_TX_TIME TIMESTAMP,
LOGPOINT VARCHAR(128),
UPDATE_TIME TIMESTAMP
);
CREATE UNIQUE INDEX IX_LREP_PROGRESS ON LREP.LOGICREP_PROGRESS(ID);

l Create a user for the logical replication service on the target database and grant
permissions to the user.
– When the target database is a GaussDB 100 database:
i. Log in to the server where GaussDB 100 is deployed as the OS user who
installs the GaussDB 100 database.
ii. Connect to the database through the port and create a user.
zsql gaussdba/database_123@127.0.0.1:1888 -c "CREATE USER logicuser
IDENTIFIED BY database_123;"

iii. Grant the permissions to add, delete, and modify any target tables of logical
replication to the user.
zsql gaussdba/database_123@127.0.0.1:1888 -c "GRANT UPDATE ON
user_name.table_name TO logicuser;"
zsql gaussdba/database_123@127.0.0.1:1888 -c "GRANT INSERT ON
user_name.table_name TO logicuser;"
zsql gaussdba/database_123@127.0.0.1:1888 -c "GRANT DELETE ON
user_name.table_name TO logicuser;"

– When the target database is an Oracle database:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 120


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

i. Log in to the database.


sqlplus / as sysdba

ii. Create a user.


CREATE USER logicuser IDENTIFIED BY database_123;

iii. Grant the permissions to add, delete, and modify any target tables of logical
replication to the user.
GRANT CREATE SESSION TO logicuser;
GRANT UPDATE ON user_name.table_name TO logicuser;
GRANT INSERT ON user_name.table_name TO logicuser;
GRANT DELETE ON user_name.table_nameE TO logicuser;

Step 4 On the primary node, generate the password ciphertexts for the logical replication users in the
source and target databases.
This operation is performed by using the zencrypt tool on the source database GaussDB 100.
1. Go to the directory storing the key configuration file of logical replication.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/sec
[gaussdba@plat sec]$ ll
total 8
-rw-------. 1 gaussdba dbgrp 38 Apr 26 15:13 key1.properties
-rw-------. 1 gaussdba dbgrp 100 Apr 26 15:13 key2.properties

The key1.properties file is used to store the random key factor, and the key2.properties
file is used to store the working key.
2. Run the vi key1.properties command to view the random key factor stored in the
key1.properties file.
3. Run the vi key2.properties command to view the working key stored in the
key2.properties file.
4. Go to the bin directory under the GaussDB 100 installation directory.
cd $GSDB_HOME/bin

5. Use the zencrypt tool to generate the password ciphertexts for the logical replication
users in the source and target databases.
When the message "Please enter password to encrypt:" is displayed, entering the
password of user LREP created for logical replication in the source database generates
the password ciphertext of this user, which needs to be configured in the ds.passwd
parameter for the source database in Step 5; and entering the password of user logicuser
created for logical replication in the target database generates the password ciphertext of
this user, which needs to be configured in the ds.passwd parameter for the target
database in Step 5.
./zencrypt -e AES256 -f lCHMm1WvDKU97uVQDd8+ew== -k g/FMnXWyHkp+8TKMa8qm5j
+Ojvuy5hHV/p3WloMhNl2DoUT6Dl90Tom5DKP+3J2M6s/jI0mMdUknmUYcOHQN+g==
Please enter password to encrypt:
*********
Please input password again:
*********
Cipher: jFB1xNaKybjU5kAD3gdJeJvdvEdjj0c87L1NBsSWZHA=

– -e: Specifies an encryption algorithm. Currently, the SCRAM_SHA256 (used to


encrypt user passwords) and AES-256 algorithms (used to encrypt SSL private key
passwords) are supported.
– -f: Specifies the random key factor. This parameter is valid only when the AES-256
algorithm is used or a working key is to be generated. The random key factor is
stored in the key1.properties file, and this file is stored in /opt/software/tools/
GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/sec/key1.properties.
– -k: Specifies the working key. This parameter is valid only when the AES-256
algorithm is used. The working key is stored in the key2.properties file, and this

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 121


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

file is stored in /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/


logicrep/conf/sec/key2.properties.
Step 5 On the primary node, define the source and target databases for the logical replication service
in the conf/datasource.properties file.
1. Go to the conf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf
2. Open the datasource.properties file and press i to enter the insert mode.
vi datasource.properties
3. Define the source and target databases.
Values in italic need to be replaced with actual values. For details about how to generate
a user password ciphertext, see Step 4. For details about how to create a user for the
logical replication service, see Step 3.
# properties of source/destination datasources defined here
# note:
# 1. section name - datasource name
# 2. mandatory properties:
# ds.type - gauss/oracle/kafka, needed for logicrep

[srcdb]
ds.type=gauss
ds.url=jdbc:zenith:@127.0.0.1:1611?useSSL=false
ds.username=lrep
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=
initial.size=5
min.idle=1
max.idle=10
max.active=50
max.wait=100000

[dstdb]
ds.type=oracle
ds.url=jdbc:oracle:thin:@10.185.240.79:1521:ora11g
ds.username=usrSample
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=
initial.size=10
max.idle=20
min.idle=5
max.active=50
max.wait=100000

[dstkafka]
ds.type=kafka
ds.url=10.185.240.79:9092
compression.type=none
max.block.ms=60000
retries=3
batch.size=1048576
linger.ms=1
buffer.memory=33554432
max.request.size=33554432
request.timeout.ms=10000
optimize.batch.send.buffer=5242880
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config.username=userxxx
#kafka sasl encrypted pwd
sasl.jaas.config.password=passxxx
ssl.truststore.location=/home/kafka.client.truststore.jks
#kafka truststore encrypted pwd
ssl.truststore.password=passxxx
ssl.keystore.location=/home/kafka.client.keystore.jks
#kafka keystore encrypted pwd
ssl.keystore.password=passxxx
#kafka key encrypted pwd

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 122


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

ssl.key.password=passxxx
ssl.keystore.type=JKS
ssl.truststore.type=JKS
ssl.protocol=SSL
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer

This example includes parameters for the three data source types supported by logical
replication, and all of them are mandatory. The parameters are as follows:
– [srcdb]/[dstdb]/[dstkafka]: Specifies the section name, indicating the name of the
data source in the section and corresponding to srcName and dstName in the
repconf_db.xml file. Specifically, srcdb indicates the name of the source data
source, and dstdb and dstkafka indicate the name of the target data source.
– ds.type: Specifies the data source type. Currently, the logical replication service
supports the following values: gauss, oracle, and kafka. gauss indicates that the
target data source is GaussDB 100, oracle indicates that the target data source is
Oracle, and kafka indicates that the target data source is a Kafka message queue.
– ds.url: Specifies the URL of the database.
n When ds.type is set to oracle and if SSL is not used, the format of ds.url will
be ds.url=jdbc:oracle:thin:@192.168.0.2:1521:ora11g. In this scenario, if
SSL is used, the format of ds.url will be
ds.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)
(HOST=192.168.0.2)(PORT=2484))
(CONNECT_DATA=(SERVICE_NAME=orcl))). In this case, you need to
configure the SSL certificates on the JDBC client.
n If ds.type is set to gauss, the format of ds.url will be
ds.url=jdbc:zenith:@127.0.0.1:1888?useSSL=false. If useSSL is false,
logical replication will be faster, but there will be security risks. If useSSL is
true, SSL bidirectional authentication will be used. For both of the settings,
SSL certificates need to be configured on the JDBC client. For details, see the
descriptions of "Configuring the SSL Certificate for the JDBC Client" in
Database Development Guide > Development Based on JDBC >
Connecting to a Database in GaussDB 100 V300R001C00 R&D
Documentation (Standalone). If unidirectional authentication is used (clients
do not authenticate servers), the SSL certificates do not need to be configured
on the JDBC client.
n If ds.type is set to kafka, the format of ds.url will be
ds.url=192.168.0.2:9092 where 9092 indicates the port number provided by
the Kafka server for the client.
– If ds.type is set to oracle or gauss, the following parameters need to be configured
in addition to ds.url:
n ds.username: Specifies the name of a logical replication user. The user created
for the logical replication service in the source database is used to read related
system catalogs and views to replay SQL statements and query logical
replication progress tables. The user created for the logical replication service
in the target database is used to access the tables used for SQL replay.
n ds.passwd: Specifies the password ciphertext of a user created for the logical
replication service.
n initial.size: Specifies the initial number of connections in the connection pool.
n max.idle: Specifies the maximum number of idle connections in the
connection pool.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 123


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

n min.idle: Specifies the minimum number of idle connections in the connection


pool.
n max.active: Specifies the maximum number of database connections in the
connection pool.
n max.wait: Specifies the maximum wait time for establishing a connection.
– If ds.type is set to kafka, you need to configure the following Kafka native
parameters in addition to ds.url. For details about the parameter meanings and
values, see related Kafka documents. In addition, you need to perform Step 7 to
configure the topic_table.properties file.
n compression.type: Specifies the message compression type.
n max.block.ms: Specifies the blocking time of KafkaProducer.send() and
KafkaProducer.partitionsFor().
n retries: Specifies the number of attempts to send messages by a producer.
n batch.size: Specifies the size of memory that a producer can use for batch
sending messages.
n linger.ms: Specifies the time when a producer waits for more messages to join
a batch of messages to be sent.
n buffer.memory: Specifies the size of the producer memory buffer.
n max.request.size: Specifies the maximum number of bytes in a request sent
by a producer.
n request.timeout.ms: Specifies the maximum duration from the time when a
producer sends a request to the time when the producer receives the ACK
message.
n optimize.batch.send.buffer: Specifies the buffer for internal messages of
logical replication. The value of this parameter must be smaller than that of
buffer.memory.
n security.protocol: Specifies the authentication mode used by the producer and
server. It can be SASL_PLAINTEXT or SSL.
n sasl.mechanism: Is PLAIN only. This parameter is mandatory when Kafka
uses SASL_PLAINTEXT authentication.
n sasl.jaas.config.username: Specifies the username for authentication. This
parameter is mandatory when Kafka uses SASL_PLAINTEXT
authentication.
n sasl.jaas.config.password: Specifies the password for authentication. The
value is an encrypted password. For details about how to encrypt a password,
see 5 in step 4. This parameter is mandatory when Kafka uses
SASL_PLAINTEXT authentication.
n ssl.truststore.location: Specifies the location of the SSL truststore certificate.
This parameter is mandatory when Kafka uses SSL authentication.
n ssl.truststore.password: Specifies an SSL truststore password (encrypted
password). This parameter is mandatory when Kafka uses SSL authentication.
n ssl.keystore.location: Specifies the location of the SSL keystore certificate.
This parameter is mandatory when Kafka uses SSL authentication.
n ssl.keystore.password: Specifies an SSL keystore password (encrypted
password). This parameter is mandatory when Kafka uses SSL authentication.
n ssl.key.password: Specifies an SSL key password (encrypted password). This
parameter is mandatory when Kafka uses SSL authentication.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 124


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

n ssl.keystore.type: Specifies an SSL keystore type, which can be JKS or


PKCS12. The default value is JKS. This parameter is mandatory when Kafka
uses SSL authentication.
n ssl.truststore.type: Specifies an SSL truststore type, which can be JKS or
PKCS12. The default value is JKS. This parameter is mandatory when Kafka
uses SSL authentication.
n ssl.protocol: Specifies an SSL protocol type, which can be SSL or TLS. The
default value is TLS. This parameter is mandatory when Kafka uses SSL
authentication.
n key.serializer: Specifies the implementation class of the Serializer interface
which is used to serialize keys.
n value.serializer: Specifies the implementation class of the Serializer interface
which is used to serialize values.
4. Press Esc and enter :wq to save the settings and exit.

Step 6 (Optional) If ds.type is set to kafka, download the Kafka 2.0 package from the Kafka official
website and copy the kafka-clients-2.0.0.jar, slf4j-api-1.7.25.jar, and slf4j-
log4j12-1.7.25.jar packages to the lib directory (/opt/software/tools/GAUSSDB100-
V300R001C00-LOGICREP/logicrep/lib) of the logical replication installation package.

Step 7 (Optional) If ds.type is set to kafka, define relationships between topics and tables as well as
the name of the partitioner class to be used in the topic_table.properties file on the primary
node.
1. Go to the topicconf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/topicconf

2. Open the topic_table.properties file and press i to enter the insert mode.
vi topic_table.properties

3. Define relationships between topics and tables as well as the name of the partitioner
class.
The following configuration is only an example. An asterisk (*) in the example is a
wildcard. In the partitioner section in the following example, partitioner is used, which
is the default value for logical replication. A customized partitioner is also supported.
topic1, topic2, and topic3 are the names of topic sections. In each topic section, you
need to configure the number of partitions and the tables whose data will be sent to this
topic.
#topic name and table name mapping relation
[partitioner]
class.name=com.huawei.gauss.logicrep.replayer.kafka.TopicPartitioner

[topic1]
partition.num=3
table.name=user1.t1,usr2.t2,user1.t3

[topic2]
partition.num=5
table.name=user2.t2,user1.t3,user3.t4,use4.*

[topic3]
partition.num=5
table.name=*.*

Step 8 On the primary node, define a replication relationship in the repconf_db.xml file.
1. Go to the repconf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/repconf

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 125


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

2. Open the repconf_db.xml file and press i to enter the insert mode.
vi repconf_db.xml

3. Define a replication relationship.


All information related to logical replication from the source database to the target
database is described in the replication relationship definition file, and the file is stored
in the conf/repconf directory in XML format.
<?xml version="1.0" encoding="UTF-8" ?>
<replicationConfig>
<repName>
<repNameInfo name="logicrep"/>
</repName>

<datasource>
<datasourceInfo srcName="srcdb" dstName="dstdb"/>
</datasource>

<filteredUser>
<userInfo userName="sample"/>
<userInfo userName="lrep"/>
</filteredUser>

<modelMapping>
<tableMapping srcTable="t1" srcSchema="usrSample"
dstTable="t1" dstSchema="usrSample">

<!-- columns not to be updated -->


<ignoreUpdatecolumns>
</ignoreUpdatecolumns>

<!--columns not to be inserted,if configure this, update


also will ignore these columns -->
<ignoreInsertcolumns>
</ignoreInsertcolumns>

<column srcColumn="f_varchar1"
dstColumn="f_varchar1" isKey="true" />
<column srcColumn="f_varchar2"
dstColumn="f_varchar2" />
<column srcColumn="f_varchar3"
dstColumn="f_varchar3" />
<column srcColumn="f_varchar4"
dstColumn="f_varchar4" />
<column srcColumn="f_date1"
dstColumn="f_date1" />
<column srcColumn="f_date2"
dstColumn="f_date2" />
<column srcColumn="f_varchar5"
dstColumn="f_varchar5" />
<column srcColumn="f_number1"
dstColumn="f_number1" />
<column srcColumn="f_varchar6"
dstColumn="f_varchar6" />
</tableMapping>
</modelMapping>
</replicationConfig>

The related tags are as follows:


– repName
Specifies the name of the replication relationship, which is the unique identifier of
the replication relationship and a command line parameter when the replication
process is started. It is used to specify the content to be replicated.
If the conf/repconf directory has multiple definition files, the file names must be
unique.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 126


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

– datasource
Specifies the names of source and target databases for replication. The
datasource.properties file must have definitions for the names.
– filteredUser
Specifies users whose information needs to be filtered. During logical replication,
data generated by the users is not covered. Multiple users can be configured.
The users need to be defined in the source database. If the users do not exist, Warn
logs will be generated, and logical replication will proceed.
It is recommended that user LREP created for the logical replication service in the
source database be configured in the filtered user list. In this way, logs generated
when user LREP performs operations on tables can be filtered out, improving the
logical replication performance.
– modelMapping
Defines a model mapping for the replication relationship. It consists of multiple
tableMapping tags. If the source and target tables in the source and target
databases have the same structure, owner, and name, you do not need to configure a
mapping relationship for the tables. Enabling the table-level logical replication
switch will directly replicate table data. If the source and target tables in the source
and target databases have different owners or names, configure only
"<tableMapping dstTable="orders2018" dstSchema="zuser"
srcTable="orders" srcSchema="zuser">" when configuring a table mapping
relationship. Column mapping relationships do not need to be configured in this
case.
– tableMapping
Defines a table mapping relationship in the model mapping, including the source
table name, source schema name, target table name, and target schema name. It
consists of multiple column mapping relationships.
If the columns in a table do not need to be all replicated, you only need to define the
mapping relationships for the columns to be replicated. If a table has a large number
of columns and only several columns do not need to be replicated, you only need to
configure the mapping relationships of the columns to be ignored in the
<ignoreUpdatecolumns></ignoreUpdatecolumns> tag or
<ignoreInsertcolumns></ignoreInsertcolumns> tag in the model mapping.
Among the <ignoreUpdatecolumns></ignoreUpdatecolumns>,
<ignoreInsertcolumns></ignoreInsertcolumns>, and <column> tags, the
<ignoreInsertcolumns></ignoreInsertcolumns> tag has the highest priority.
– column
Defines a column mapping relationship between a source table and its target table,
including the source column name, source column type, target column name, and
target column type. It is recommended that the source column name be the same as
the target column name and the source column type be the same as the target
column type.
For primary key columns, also set isKey to true. If isKey is not set, the value false
will be used.
4. Press Esc and enter :wq to save the settings and exit.

Step 9 Replicate the modified conf and lib folders from the primary node to the standby node.
1. Log in to the standby GaussDB 100 node as user gaussdba.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 127


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

2. Replicate the conf and lib folders to the standby node.


Assume that the IP address of the primary node is 192.168.0.1.
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/conf /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

root@192.168.0.1's password:
datasource.xml
100% 667 0.7KB/s 00:00
init.properties
100% 760 0.7KB/s 00:00
key2.properties
100% 100 0.1KB/s 00:00
key1.properties
100% 38 0.0KB/s 00:00
repconf_db.xml
100% 850 0.8KB/s 00:00
log4j.xml
100% 3449 3.4KB/s 00:00
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/lib /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

Step 10 Enable the table-level logical replication switch and global logical replication switch.
The global logical replication switch must be enabled on both the primary and standby nodes.
The table-level logical replication switch needs to be enabled only on the primary node. The
table-level logical replication switch on the standby node is enabled synchronously with that
on the primary node.
-- Run the following command on the primary and standby nodes to enable the
global logical replication switch:
zsql gaussdba/database_123@127.0.0.1:1888 -c "ALTER DATABASE
ENABLE_LOGIC_REPLICATION ON;"
-- Enable the table-level logical replication switch.
zsql gaussdba/database_123@127.0.0.1:1888 -c "ALTER TABLE
[schema_name.]table_name ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS;"

NOTE

l The table to be replicated must have a primary key. Otherwise, the error message "GS-01213, error
message = 'object index on table TRAINING does not exist'" will be displayed when the table-level
logical replication switch is enabled.
l To ensure data consistency between source and target tables, you need to set, in the target table, the
primary key attribute for the column corresponding to the primary key column of the source table.
l Currently, logical replication supports only primary key–based replication. Therefore, when the
table-level logical replication switch is enabled, COLUMNS can be set only to PRIMARY KEY.
l Data in a table is replicated only when both the table-level and global logical replication switches are
enabled.

You can log in to the primary and standby nodes as user gaussdba to check the status of the
global logical replication switch there. The procedure is as follows:
1. Log in to the database.
zsql gaussdba/database_123@127.0.0.1:1888

2. Check the status of the global logical replication switch.


SELECT lrep_point, lrep_mode FROM sys.DV_DATABASE;

-- The status of the global logical replication switch on the primary node is
as follows:
LREP_POINT LREP_MODE
-------------------- --------------------
0-2-422-50b ON

1 rows fetched.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 128


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

-- The status of the global logical replication switch on the standby node is
as follows:
LREP_POINT LREP_MODE
-------------------- --------------------
0-2-f3c9-a549 ON

1 rows fetched.

You can log in to the primary and standby nodes as user gaussdba, and run the following
command to check the status of the table-level logical replication switch:
zsql gaussdba/database_123@127.0.0.1:1888 -c "SELECT l.status FROM
sys.sys_logic_repl l, sys.sys_tables t WHERE t.name='ORDERS' AND t.id=l.table#;"

SQL>
STATUS
------------
1

1 rows fetched.

NOTE

When you use the zsql gaussdba/database_123@127.0.0.1:1888 -c "SELECT l.status FROM


sys.sys_logic_repl l, sys.sys_tables t WHERE t.name='ORDERS' AND t.id=l.table#;" command to
check the logical replication switch of a table, the table name must be in uppercase. Otherwise, the query
result will be empty.
STATUS
------------

0 rows fetched.

Step 11 On the primary and standby nodes, start the logical replication service.
1. Go to the logicrep directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep

2. Start the logical replication service.


NOTE

Running the startup.sh and shutdown.sh scripts requires a database installation account.
-- Start the logical replication service on the primary node:
sh startup.sh -n logicrep -a 0-2-422-50b

program start successfully

-- Start the logical replication service on the standby node:


sh startup.sh -n logicrep -a 0-2-f3c9-a549

program start successfully

-n rep_name is a mandatory parameter. It specifies the logical replication relationship to


be started. rep_name has been defined in a replication relationship definition file. The
name is used as the unique identifier of a series of subsequent operations, such as
restarting the logical replication service and querying the replication progress. Therefore,
the name must be unique and cannot be modified when in use. When the logical
replication service is started, all replication relationship definition files in the conf/
repconf directory are checked. If the value of rep_name in a replication relationship
definition file of this logical replication service is the same as that of a started logical
replication service, this service will be forcibly exited.
-a lrep_point is an optional parameter. It specifies the start log point when logical
replication starts. When the table-level and global logical replication switches of the
source database are enabled and logical replication is started for the first time, this
parameter must be used to specify the start point of replication. The value of lrep_point
can be obtained by running the zsql gaussdba/database_123@127.0.0.1:1888 -c

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 129


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

"SELECT lrep_point, lrep_mode FROM sys.DV_DATABASE;" command to query


the DV_DATABASE view after the global logical replication switch of the source
database is enabled.

Step 12 (Optional) On the primary and standby nodes, check the replication progress of the logical
replication service.
zsql gaussdba/database_123@127.0.0.1:1888 -c "SELECT id, committed_scn, logpoint,
update_time FROM LREP.logicrep_progress;"

SQL>
ID
COMMITTED_SCN
LOGPOINT UPDATE_TIME
----------------------------------------------------------------
--------------------
----------------------------------------------------------------
--------------------------------
LOGICREP
391439205040129 0-2-1ddc00-1ddce4-
c27 2019-01-16 17:22:56.470883

1 rows fetched.

----End

Procedure – Routinely Checking Logical Replication


You can periodically view logs in the log directory to check whether there are errors. In this
way, you can discover and resolve problems in time. In addition, you can view performance
logs to check whether there are performance problems. If there are, adjust startup parameters
to improve performance. Perform the routine check on logical replication only on primary
nodes.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 On the primary node, go to the log directory.


cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/logicrep/logicrep/
logicrep

Step 3 View logs in the log directory to check whether the logical replication service is running
properly.

Logs of the logical replication service include alarm logs, run logs, audit logs, and
performance logs.

View logs in the alarm directory to check whether there are critical errors, such as a thread or
process exit. If there are, fix the errors by referring to other log information and restart the
service.

View run logs in the run directory to check whether there are runtime errors.

View audit logs in the audit directory to check whether there are SQL execution errors.

View performance logs in the perf directory to check whether there are performance problems
and whether the startup parameters need to be adjusted.

If the logical replication service is running properly, the check is complete. If the logical
replication service is abnormal, go to Step 4.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 130


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Step 4 On the primary and standby nodes, stop the logical replication service.

Running the shutdown.sh script requires a database installation account.


sh shutdown.sh -n logicrep

Process is stopping, please wait......


Close logicRepName=logicrep logic process successfully.

If the logical replication service cannot be stopped, run the following command to forcibly
stop it:
sh shutdown.sh -n logicrep -f

Close logicRepName=logicrep logic process successfully with -f.

Step 5 On the primary and standby nodes, restart the logical replication service.

Running the startup.sh and shutdown.sh scripts requires a database installation account.

When restarting a logical replication service, you can continue replication based on the
progress saved in the last stop of the service.
sh startup.sh -n logicrep

program start successfully

When restarting a logical replication service, you can also forcibly ignore the previous
replication progress.
sh startup.sh -n logicrep -a 0-2-1ddc00-1ddce4-c27 -c

The -c parameter specifies the previous replication progress. The replication will continue
from the start point specified by the -a parameter. When this method is used to restart a
logical replication service, all logical logs from the start point will be parsed and replicated to
the target database. If some replication data already exists in the target database, a conflict
may occur. Therefore, this method is applicable only to some exception handling scenarios.
For example, if forcible re-replication is required, ensure that certain data in the target
database has been deleted or the conflict does not affect the service.

----End

Procedure – Modifying the Startup Parameters of Logical Replication


The startup parameters are stored in the init.properties file. When configuring a logical
replication service for the first time, you can use the default settings of the startup parameters.
Later, you can determine whether to modify the startup parameters by observing the HWM
for buffering performance logs. All modifications take effect only after the logical replication
service is restarted.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 On the primary node, modify the startup parameters of the logical replication service process.
1. Go to the conf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf

2. Open the init.properties file and press i to enter the insert mode.
vi init.properties

3. Change the values of the startup parameters.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 131


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

All modifications take effect only after the logical replication service is restarted. The
conf/init.properties file template is as follows (italic indicates an example value, and an
actual value is needed):
#unit: number of replayer threads
#value range:[1,32]
replayer.thread.number=1

#specify which kind of replayer is used


replayer.class=com.huawei.gauss.logicrep.replayer.jdbc.JdbcReplayer
#replayer.class=com.huawei.gauss.logicrep.replayer.kafka.KafkaReplayer

#unit: number of slots


#value range:[1024,2048]
dispatch.queue.size=1024

#unit: number of transactions


#value range:[100,300]
transaction.buffer.size=100

#unit: MB
#value range:[100,500]
transaction.buffer.memory.size=100

#unit: MB
#value range:[300,800]
logentry.buffer.size=500

#checkpoint interval: millisecond


#value range:[3000,30000]
checkpoint.interval=3000

#where checkpoint is persisted:


# sourcedb - logic_rep_progress table on source db
checkpoint.location=sourcedb

#logic_rep_progress table version.


#it is for compatibility, since some deployments use old table version now.
#for new deployment, don't need to change this.
#if it is not set, v1 used.
# v1 - old version: ID,COMMITTED_SCN,LOGPOINT,UPDATE_TIME
# v2 - new columns used:
ID,COMMITTED_TX_SCN,COMMITTED_TX_TIME,LOGPOINT,UPDATE_TIME
checkpoint.table.version=v2

#byte order of redo logfiles to be extracted


# little - logfiles generated on little endian platform
# big - logfiles generated on big endian platform
logfile.endian.type=little

#path_to_keystore_file(for zenith)
javax.net.ssl.keyStore=

#encrypted keyStorePassword(for zenith)


javax.net.ssl.keyStorePassword=

#path_to_trustStore_file(for oracle)
javax.net.ssl.trustStore=

#encrypted trustStorePassword(for oracle)


javax.net.ssl.trustStorePassword=

The parameters are as follows:


– replayer.thread.number
Specifies the number of replay threads. It is evaluated based on the size of
transactions that can be concurrently executed. When the requirements for
performance are low, use the default configuration, that is, single-thread replay.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 132


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

– replayer.class
Specifies the replay class in use. When you customize a plug-in based on the
software development kit (SDK) of logical replication, set this parameter to the
name of the replay class that is implemented.
– dispatch.queue.size
Specifies the size of the work queue. It is evaluated based on the size of transactions
that can be concurrently executed. When the requirements for performance are low,
use the default configuration.
– transaction.buffer.size
Specifies the maximum number of transactions that can be stored in the transaction
buffer. When the buffer is full, the system waits for a replay thread to process. Use
the default configuration in the initial phase. Later, you can adjust the value of this
parameter by observing the high-water mark (HWM) for buffering performance
logs.
– transaction.buffer.memory.size
Specifies the maximum memory space occupied by each transaction. When the
space occupied by a transaction exceeds the default value, logical replication fails.
In this case, increase the value of this parameter to ensure that transactions
occupying large space perform the replication correctly.
– logentry.buffer.size
Specifies the size of the logentry buffer. Use the default configuration in the initial
phase. Later, you can adjust the value of this parameter by observing the HWM for
buffering performance logs.
– checkpoint.interval
Specifies an interval for storing the replay progress. The default configuration is
recommended. If this parameter is set too small, the progress may be frequently
stored, affecting performance.
– checkpoint.location
Specifies the location for storing the parsing and replay progress of physical logs. It
stores the location of the physical log where the logical replication service stopped
parsing and the latest transaction SCN that is committed to the target database. The
value can only be sourcedb, indicating that the progress information of the logical
replication service is stored in the LOGICREP_PROGRESS table of the logical
replication service user created in the source database.
– checkpoint.table.version
Specifies the version of the logical replication progress table stored in the source
database. In an old version of the table, there are ID, COMMITTED_SCN,
LOGPOINT, and UPDATE_TIME columns. In an upgraded version of the table,
the COMMITTED_TX_TIME column is added. This version is identified by v2.
For a logical replication service that has been launched and running, you do not
need to specify this parameter, or you can set this parameter to v1, indicating the
old version of the logical replication progress table in the source database.
For a logical replication service that is newly launched, this parameter in the
parameter file of the logical replication installation package has been set to v2 by
default. The logical replication progress table in the source database will be created
based on the structure of the new version of the table.
– logfile.endian.type

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 133


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Specifies whether to use the big endian or little endian mode for storing data in
memory. The big endian or little endian mode refers to the configuration of the
machine that generates the log files required by the logical replication tool. When
the big endian mode is used, the high byte of data is stored in the low address of
memory, and the low byte of data is stored in the high address of memory. When
the little endian mode is used, the high byte of data is stored in the high address of
memory, and the low byte of data is stored in the low address of memory.
– javax.net.ssl.keyStore
Specifies the path of the keystore file, which must contain the file name. This
parameter is used only when useSSL is set to true and the client needs to be
authenticated.
– javax.net.ssl.keyStorePassword
Specifies the ciphertext of the keystore password. This parameter is used only when
useSSL is set to true and the client needs to be authenticated. For details about how
to generate the ciphertext, see Step 4.
– javax.net.ssl.trustStore=
Specifies the path of the truststore file, which must contain the file name. This
parameter is used only when SSL is configured for the Oracle database.
– javax.net.ssl.trustStorePassword=
Specifies the ciphertext of the truststore password. This parameter is used only
when SSL is configured for the Oracle database. For details about how to generate
the ciphertext, see Step 4.
4. Press Esc and enter :wq to save the settings and exit.

Step 3 Log in to the standby GaussDB 100 node as user gaussdba.

Step 4 Replicate the modified conf folder from the primary node to the standby node.
Assume that the IP address of the primary node is 192.168.0.1.
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/conf /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

root@192.168.0.1's password:
datasource.xml
100% 667 0.7KB/s 00:00
init.properties
100% 760 0.7KB/s 00:00
key2.properties
100% 100 0.1KB/s 00:00
key1.properties
100% 38 0.0KB/s 00:00
repconf_db.xml
100% 850 0.8KB/s 00:00
log4j.xml
100% 3449 3.4KB/s 00:00

Step 5 On the primary and standby nodes, stop the logical replication service.
Running the shutdown.sh script requires a database installation account.
sh shutdown.sh -n logicrep

Process is stopping, please wait......


Close logicRepName=logicrep logic process successfully.

If the logical replication service cannot be stopped, run the following command to forcibly
stop it:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 134


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

sh shutdown.sh -n logicrep -f

Close logicRepName=logicrep logic process successfully with -f.

Step 6 On the primary and standby nodes, restart the logical replication service.
Running the startup.sh script requires a database installation account.
When restarting a logical replication service, you can continue replication based on the
progress saved in the last stop of the service.
sh startup.sh -n logicrep

program start successfully

When restarting a logical replication service, you can also forcibly ignore the previous
replication progress.
sh startup.sh -n logicrep -a 0-2-1ddc00-1ddce4-c27 -c

The -c parameter specifies the previous replication progress. The replication will continue
from the start point specified by the -a parameter.
When this method is used to restart a logical replication service, all logical logs from the start
point will be parsed and replicated to the target database. If some replication data already
exists in the target database, a conflict may occur. Therefore, this method is applicable only to
some exception handling scenarios. For example, if forcible re-replication is required, ensure
that certain data in the target database has been deleted or the conflict does not affect the
service.

----End

Procedure – Modifying the datasource.properties File


If the environment information of the source and target databases changes, for example,
ds.url or the password of a logical replication user is changed, you need to modify the
datasource.xml file. Any modifications to datasource.xml take effect only after the logical
replication service is restarted.

Step 1 Log in to the primary GaussDB 100 node as user gaussdba.

Step 2 On the primary node, modify the datasource.properties file.


1. Go to the conf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf

2. Open the datasource.properties file and press i to enter the insert mode.
vi datasource.properties

3. Define the source and target databases.


Values in italic need to be replaced with actual values. For details about how to generate
a user password ciphertext, see Step 4. For details about how to create a user for the
logical replication service, see Step 3.
# properties of source/destination datasources defined here
# note:
# 1. section name - datasource name
# 2. mandatory properties:
# ds.type - gauss/oracle/kafka, needed for logicrep

[srcdb]
ds.type=gauss
ds.url=jdbc:zenith:@127.0.0.1:1611?useSSL=false
ds.username=lrep
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 135


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

initial.size=5
min.idle=1
max.idle=10
max.active=50
max.wait=100000

[dstdb]
ds.type=oracle
ds.url=jdbc:oracle:thin:@10.185.240.79:1521:ora11g
ds.username=usrSample
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=
initial.size=10
max.idle=20
min.idle=5
max.active=50
max.wait=100000

[dstkafka]
ds.type=kafka
ds.url=10.185.240.79:9092
compression.type=none
max.block.ms=60000
retries=3
batch.size=1048576
linger.ms=1
buffer.memory=33554432
max.request.size=33554432
request.timeout.ms=10000
optimize.batch.send.buffer=5242880
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config.username=userxxx
#kafka sasl encrypted pwd
sasl.jaas.config.password=passxxx
ssl.truststore.location=/home/kafka.client.truststore.jks
#kafka truststore encrypted pwd
ssl.truststore.password=passxxx
ssl.keystore.location=/home/kafka.client.keystore.jks
#kafka keystore encrypted pwd
ssl.keystore.password=passxxx
#kafka key encrypted pwd
ssl.key.password=passxxx
ssl.keystore.type=JKS
ssl.truststore.type=JKS
ssl.protocol=SSL
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer

This example includes parameters for the three data source types supported by logical
replication, and all of them are mandatory. The parameters are as follows:
– [srcdb]/[dstdb]/[dstkafka]: Specifies the section name, indicating the name of the
data source in the section and corresponding to srcName and dstName in the
repconf_db.xml file. Specifically, srcdb indicates the name of the source data
source, and dstdb and dstkafka indicate the name of the target data source.
– ds.type: Specifies the data source type. Currently, the logical replication service
supports the following values: gauss, oracle, and kafka. gauss indicates that the
target data source is GaussDB 100, oracle indicates that the target data source is
Oracle, and kafka indicates that the target data source is a Kafka message queue.
– ds.url: Specifies the URL of the database.
n When ds.type is set to oracle and if SSL is not used, the format of ds.url will
be ds.url=jdbc:oracle:thin:@192.168.0.2:1521:ora11g. In this scenario, if
SSL is used, the format of ds.url will be
ds.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)
(HOST=192.168.0.2)(PORT=2484))

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 136


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

(CONNECT_DATA=(SERVICE_NAME=orcl))). In this case, you need to


configure the SSL certificates on the JDBC client.
n If ds.type is set to gauss, the format of ds.url will be
ds.url=jdbc:zenith:@127.0.0.1:1888?useSSL=false. If useSSL is false,
logical replication will be faster, but there will be security risks. If useSSL is
true, SSL bidirectional authentication will be used. For both of the settings,
SSL certificates need to be configured on the JDBC client. For details, see the
descriptions of "Configuring the SSL Certificate for the JDBC Client" in
Database Development Guide > Development Based on JDBC >
Connecting to a Database in GaussDB 100 V300R001C00 R&D
Documentation (Standalone). If unidirectional authentication is used (clients
do not authenticate servers), the SSL certificates do not need to be configured
on the JDBC client.
n If ds.type is set to kafka, the format of ds.url will be
ds.url=192.168.0.2:9092 where 9092 indicates the port number provided by
the Kafka server for the client.
– If ds.type is set to oracle or gauss, the following parameters need to be configured
in addition to ds.url:
n ds.username: Specifies the name of a logical replication user. The user created
for the logical replication service in the source database is used to read related
system catalogs and views to replay SQL statements and query logical
replication progress tables. The user created for the logical replication service
in the target database is used to access the tables used for SQL replay.
n ds.passwd: Specifies the password ciphertext of a user created for the logical
replication service.
n initial.size: Specifies the initial number of connections in the connection pool.
n max.idle: Specifies the maximum number of idle connections in the
connection pool.
n min.idle: Specifies the minimum number of idle connections in the connection
pool.
n max.active: Specifies the maximum number of database connections in the
connection pool.
n max.wait: Specifies the maximum wait time for establishing a connection.
– If ds.type is set to kafka, you need to configure the following Kafka native
parameters in addition to ds.url. For details about the parameter meanings and
values, see related Kafka documents. In addition, you need to perform Step 7 to
configure the topic_table.properties file.
n compression.type: Specifies the message compression type.
n max.block.ms: Specifies the blocking time of KafkaProducer.send() and
KafkaProducer.partitionsFor().
n retries: Specifies the number of attempts to send messages by a producer.
n batch.size: Specifies the size of memory that a producer can use for batch
sending messages.
n linger.ms: Specifies the time when a producer waits for more messages to join
a batch of messages to be sent.
n buffer.memory: Specifies the size of the producer memory buffer.
n max.request.size: Specifies the maximum number of bytes in a request sent
by a producer.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 137


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

n request.timeout.ms: Specifies the maximum duration from the time when a


producer sends a request to the time when the producer receives the ACK
message.
n optimize.batch.send.buffer: Specifies the buffer for internal messages of
logical replication. The value of this parameter must be smaller than that of
buffer.memory.
n security.protocol: Specifies the authentication mode used by the producer and
server. It can be SASL_PLAINTEXT or SSL.
n sasl.mechanism: Is PLAIN only. This parameter is mandatory when Kafka
uses SASL_PLAINTEXT authentication.
n sasl.jaas.config.username: Specifies the username for authentication. This
parameter is mandatory when Kafka uses SASL_PLAINTEXT
authentication.
n sasl.jaas.config.password: Specifies the password for authentication. The
value is an encrypted password. For details about how to encrypt a password,
see 5 in step 4. This parameter is mandatory when Kafka uses
SASL_PLAINTEXT authentication.
n ssl.truststore.location: Specifies the location of the SSL truststore certificate.
This parameter is mandatory when Kafka uses SSL authentication.
n ssl.truststore.password: Specifies an SSL truststore password (encrypted
password). This parameter is mandatory when Kafka uses SSL authentication.
n ssl.keystore.location: Specifies the location of the SSL keystore certificate.
This parameter is mandatory when Kafka uses SSL authentication.
n ssl.keystore.password: Specifies an SSL keystore password (encrypted
password). This parameter is mandatory when Kafka uses SSL authentication.
n ssl.key.password: Specifies an SSL key password (encrypted password). This
parameter is mandatory when Kafka uses SSL authentication.
n ssl.keystore.type: Specifies an SSL keystore type, which can be JKS or
PKCS12. The default value is JKS. This parameter is mandatory when Kafka
uses SSL authentication.
n ssl.truststore.type: Specifies an SSL truststore type, which can be JKS or
PKCS12. The default value is JKS. This parameter is mandatory when Kafka
uses SSL authentication.
n ssl.protocol: Specifies an SSL protocol type, which can be SSL or TLS. The
default value is TLS. This parameter is mandatory when Kafka uses SSL
authentication.
n key.serializer: Specifies the implementation class of the Serializer interface
which is used to serialize keys.
n value.serializer: Specifies the implementation class of the Serializer interface
which is used to serialize values.
4. Press Esc and enter :wq to save the settings and exit.

Step 3 (Optional) If ds.url is modified to use SSL (from useSSL=false to useSSL=true) in the
datasource.properties file, configure the certificate name and password in the conf/
init.properties file and restart the logical replication service for the modification to take
effect. If bidirectional authentication is used, configure SSL certificates on the JDBC client.
For details, see the descriptions of "Configuring the SSL Certificate for the JDBC Client" in
Database Development Guide > Development Based on JDBC > Connecting to a

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 138


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Database in GaussDB 100 V300R001C00 R&D Documentation (Standalone). If


unidirectional authentication is used (clients do not authenticate servers), the SSL certificates
do not need to be configured on the JDBC client.
Step 4 (Optional) If ds.type is set to kafka, download the Kafka 2.0 package from the Kafka official
website and copy the kafka-clients-2.0.0.jar, slf4j-api-1.7.25.jar, and slf4j-
log4j12-1.7.25.jar packages to the lib directory (/opt/software/tools/GAUSSDB100-
V300R001C00-LOGICREP/logicrep/lib) of the logical replication installation package.
Step 5 (Optional) If ds.type is set to kafka, define relationships between topics and tables as well as
the name of the partitioner class to be used in the topic_table.properties file on the primary
node.
1. Go to the topicconf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/topicconf

2. Open the topic_table.properties file and press i to enter the insert mode.
vi topic_table.properties

3. Define relationships between topics and tables as well as the name of the partitioner
class.
The following configuration is only an example. An asterisk (*) in the example is a
wildcard. In the partitioner section in the following example, partitioner is used, which
is the default value for logical replication. A customized partitioner is also supported.
topic1, topic2, and topic3 are the names of topic sections. In each topic section, you
need to configure the number of partitions and the tables whose data will be sent to this
topic.
#topic name and table name mapping relation
[partitioner]
class.name=com.huawei.gauss.logicrep.replayer.kafka.TopicPartitioner

[topic1]
partition.num=3
table.name=user1.t1,usr2.t2,user1.t3

[topic2]
partition.num=5
table.name=user2.t2,user1.t3,user3.t4,use4.*

[topic3]
partition.num=5
table.name=*.*

Step 6 Log in to the standby GaussDB 100 node as user gaussdba.


Step 7 Replicate the modified conf folder from the primary node to the standby node.
Assume that the IP address of the primary node is 192.168.0.1.
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/conf /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

root@192.168.0.1's password:
datasource.xml
100% 667 0.7KB/s 00:00
init.properties
100% 760 0.7KB/s 00:00
key2.properties
100% 100 0.1KB/s 00:00
key1.properties
100% 38 0.0KB/s 00:00
repconf_db.xml
100% 850 0.8KB/s 00:00
log4j.xml
100% 3449 3.4KB/s 00:00

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 139


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Step 8 On the primary and standby nodes, stop the logical replication service.
Running the shutdown.sh script requires a database installation account.
sh shutdown.sh -n logicrep

Process is stopping, please wait......


Close logicRepName=logicrep logic process successfully.

If the logical replication service cannot be stopped, run the following command to forcibly
stop it:
sh shutdown.sh -n logicrep -f

Close logicRepName=logicrep logic process successfully with -f.

Step 9 On the primary and standby nodes, restart the logical replication service.
Running the startup.sh script requires a database installation account.
When restarting a logical replication service, you can continue replication based on the
progress saved in the last stop of the service.
sh startup.sh -n logicrep

program start successfully

When restarting a logical replication service, you can also forcibly ignore the previous
replication progress.
sh startup.sh -n logicrep -a 0-2-1ddc00-1ddce4-c27 -c

The -c parameter specifies the previous replication progress. The replication will continue
from the start point specified by the -a parameter.
When this method is used to restart a logical replication service, all logical logs from the start
point will be parsed and replicated to the target database. If some replication data already
exists in the target database, a conflict may occur. Therefore, this method is applicable only to
some exception handling scenarios. For example, if forcible re-replication is required, ensure
that certain data in the target database has been deleted or the conflict does not affect the
service.

----End

Procedure – Modifying the repconf_db.xml File


You can modify a configured table mapping relationship in the repconf_db.xml file or add a
mapping relationship to a new table. Any modifications to repconf_db.xml take effect only
after the logical replication service is restarted.

Step 1 Log in to the primary GaussDB 100 node as user gaussdba.

Step 2 On the primary node, modify the repconf_db.xml file.


1. Go to the repconf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf/repconf

2. Open the repconf_db.xml file and press i to enter the insert mode.
vi repconf_db.xml

3. Define a replication relationship.


All information related to logical replication from the source database to the target
database is described in the replication relationship definition file, and the file is stored
in the conf/repconf directory in XML format.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 140


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

<?xml version="1.0" encoding="UTF-8" ?>


<replicationConfig>
<repName>
<repNameInfo name="logicrep"/>
</repName>

<datasource>
<datasourceInfo srcName="srcdb" dstName="dstdb"/>
</datasource>

<filteredUser>
<userInfo userName="sample"/>
<userInfo userName="lrep"/>
</filteredUser>

<modelMapping>
<tableMapping srcTable="t1" srcSchema="usrSample"
dstTable="t1" dstSchema="usrSample">

<!-- columns not to be updated -->


<ignoreUpdatecolumns>
</ignoreUpdatecolumns>

<!--columns not to be inserted,if configure this, update


also will ignore these columns -->
<ignoreInsertcolumns>
</ignoreInsertcolumns>

<column srcColumn="f_varchar1"
dstColumn="f_varchar1" isKey="true" />
<column srcColumn="f_varchar2"
dstColumn="f_varchar2" />
<column srcColumn="f_varchar3"
dstColumn="f_varchar3" />
<column srcColumn="f_varchar4"
dstColumn="f_varchar4" />
<column srcColumn="f_date1"
dstColumn="f_date1" />
<column srcColumn="f_date2"
dstColumn="f_date2" />
<column srcColumn="f_varchar5"
dstColumn="f_varchar5" />
<column srcColumn="f_number1"
dstColumn="f_number1" />
<column srcColumn="f_varchar6"
dstColumn="f_varchar6" />
</tableMapping>
</modelMapping>
</replicationConfig>

The related tags are as follows:


– repName
Specifies the name of the replication relationship, which is the unique identifier of
the replication relationship and a command line parameter when the replication
process is started. It is used to specify the content to be replicated.
If the conf/repconf directory has multiple definition files, the file names must be
unique.
– datasource
Specifies the names of source and target databases for replication. The
datasource.properties file must have definitions for the names.
– filteredUser
Specifies users whose information needs to be filtered. During logical replication,
data generated by the users is not covered. Multiple users can be configured.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 141


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

The users need to be defined in the source database. If the users do not exist, Warn
logs will be generated, and logical replication will proceed.
It is recommended that user LREP created for the logical replication service in the
source database be configured in the filtered user list. In this way, logs generated
when user LREP performs operations on tables can be filtered out, improving the
logical replication performance.
– modelMapping
Defines a model mapping for the replication relationship. It consists of multiple
tableMapping tags. If the source and target tables in the source and target
databases have the same structure, owner, and name, you do not need to configure a
mapping relationship for the tables. Enabling the table-level logical replication
switch will directly replicate table data. If the source and target tables in the source
and target databases have different owners or names, configure only
"<tableMapping dstTable="orders2018" dstSchema="zuser"
srcTable="orders" srcSchema="zuser">" when configuring a table mapping
relationship. Column mapping relationships do not need to be configured in this
case.
– tableMapping
Defines a table mapping relationship in the model mapping, including the source
table name, source schema name, target table name, and target schema name. It
consists of multiple column mapping relationships.
If the columns in a table do not need to be all replicated, you only need to define the
mapping relationships for the columns to be replicated. If a table has a large number
of columns and only several columns do not need to be replicated, you only need to
configure the mapping relationships of the columns to be ignored in the
<ignoreUpdatecolumns></ignoreUpdatecolumns> tag or
<ignoreInsertcolumns></ignoreInsertcolumns> tag in the model mapping.
Among the <ignoreUpdatecolumns></ignoreUpdatecolumns>,
<ignoreInsertcolumns></ignoreInsertcolumns>, and <column> tags, the
<ignoreInsertcolumns></ignoreInsertcolumns> tag has the highest priority.
– column
Defines a column mapping relationship between a source table and its target table,
including the source column name, source column type, target column name, and
target column type. It is recommended that the source column name be the same as
the target column name and the source column type be the same as the target
column type.
For primary key columns, also set isKey to true. If isKey is not set, the value false
will be used.
4. Press Esc and enter :wq to save the settings and exit.
Step 3 (Optional) When adding a table mapping relationship for the newly created table in the
repconf_db.xml file, that is, adding the <tableMapping></tableMapping> tag, you need to
enable the logical replication switch of the table on the primary node.
-- Enable the table-level logical replication switch.
zsql gaussdba/database_123@127.0.0.1:1888 -c "ALTER TABLE
[schema_name.]table_name ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS;"

Step 4 Log in to the standby GaussDB 100 node as user gaussdba.


Step 5 Replicate the modified conf folder from the primary node to the standby node.
Assume that the IP address of the primary node is 192.168.0.1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 142


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/conf /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

root@192.168.0.1's password:
datasource.xml
100% 667 0.7KB/s 00:00
init.properties
100% 760 0.7KB/s 00:00
key2.properties
100% 100 0.1KB/s 00:00
key1.properties
100% 38 0.0KB/s 00:00
repconf_db.xml
100% 850 0.8KB/s 00:00
log4j.xml
100% 3449 3.4KB/s 00:00

Step 6 On the primary and standby nodes, stop the logical replication service.

Running the shutdown.sh script requires a database installation account.


sh shutdown.sh -n logicrep

Process is stopping, please wait......


Close logicRepName=logicrep logic process successfully.

If the logical replication service cannot be stopped, run the following command to forcibly
stop it:
sh shutdown.sh -n logicrep -f

Close logicRepName=logicrep logic process successfully with -f.

Step 7 On the primary and standby nodes, restart the logical replication service.

Running the startup.sh script requires a database installation account.

When restarting a logical replication service, you can continue replication based on the
progress saved in the last stop of the service.
sh startup.sh -n logicrep

program start successfully

When restarting a logical replication service, you can also forcibly ignore the previous
replication progress.
sh startup.sh -n logicrep -a 0-2-1ddc00-1ddce4-c27 -c

The -c parameter specifies the previous replication progress. The replication will continue
from the start point specified by the -a parameter.

When this method is used to restart a logical replication service, all logical logs from the start
point will be parsed and replicated to the target database. If some replication data already
exists in the target database, a conflict may occur. Therefore, this method is applicable only to
some exception handling scenarios. For example, if forcible re-replication is required, ensure
that certain data in the target database has been deleted or the conflict does not affect the
service.

----End

Procedure – Invoking a User-Developed Replication Plug-In


Logical replication provides the replication capability of supported data sources and also an
SDK, which allows users to develop replication plug-ins that meet their own requirements.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 143


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Such a plug-in can be invoked by the logical replication service to meet the customization
requirements of users.

Step 1 Develop a logical replication plug-in.


1. Obtain the SDK development package.
The SDK development package provided by logical replication is named
com.huawei.gauss.logicrep.sdk-V300R001C00SPC100B200.jar and stored in the lib
directory of the logical replication installation package GAUSSDB100-V300R001C00-
TOOLS/GAUSSDB100-V300R001C00-LOGICREP.tar.gz. The version number is
determined by actual version packaging. When developing a plug-in, you need to
reference the JAR package.
The SDK package provides a callback function interface for SQL replay and various data
acquisition interfaces. The SDK package is completely decoupled from the logical
replication framework.
public interface LogicrepPlugin
{
/**
* Plug-in configuration
* @param Plug-in context where various information can be obtained, such as
metadata and configurations
* LogicRepContext
*/
public abstract void configure(LogicRepContext context) throws Exception;
/**
* Plug-in initialization
*
* @throws Exception
* Initialization error
*/
public abstract void init() throws Exception;
/**
* Plug-in exit
*/
public abstract void exit() throws Exception;
}

public interface Replayer extends LogicrepPlugin {


/**
* Replay a transaction.
* @param trx
* A complete transaction of the source database is contained.
* @return
* true: returned when the transaction is successfully executed
* false: returned when the transaction is not executed due to certain
reasons, for example, the connection is not obtained
* @throws Exception
* The transaction encounters any error during execution.
*/
boolean replay(Transaction trx) throws Exception;
}

Related functions are as follows:


– configure(): Receives the plug-in context provided by the logical replication
framework to obtain various configuration class information and metadata class
information.
– init(): Implements the plug-in initialization logic, which is invoked by the logical
replication framework during plug-in loading.
– exit(): Implements the plug-in exit logic, which is invoked by the logical replication
framework during plug-in exit.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 144


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

– replay(): Customizes data. It implements the main plug-in logic.


You can implement the four functions to process transaction object data, implementing
customized replication functionality. For example, flush data to files, or replicate data to
other target data sources that are not supported by the current logical replication service.
2. Develop a plug-in to implement the replay interface above.
To implement a replay plug-in, you need to implement the replay interface provided in
the SDK package and complete the replay logic for each piece of transaction data in the
implementation class. For example, write transaction data to a text file or replicate data
to a specific third-party data source.
The following is an example of implementing replayer:
public class kafkaReplayerDemo implements Replayer {
@Override
public void configure(LogicRepContext context) throws Exception
{
// TODO Auto-generated method stub
}
@Override
public void init() throws Exception
{
// TODO Auto-generated method stub
}
@Override
public void exit() throws Exception
{
// TODO Auto-generated method stub
}
@Override public boolean replay(Transaction trx) throws Exception
{
int entriesSize = trx.logEntrySize();
long scn = trx.getTrxSCN();
for (int i = 1; i < entriesSize; i++)
{
LogEntry entry = trx.getLogEntry(i);
if (!entry.isDML())
{
continue;
}
LogEntryDML entry1 = (LogEntryDML) entry;
if (entry.getLogEntryType() == LogEntryDML.LOGENTRY_TYPE_INSERT)
{
LogEntryInsert insertEntry = (LogEntryInsert) entry1;
HashMap<Integer, Column> columns =
insertEntry.getColumns();
insertEntry.getUserID();
insertEntry.getTableID();
}
}
return true;
}
}

When plug-in code needs to read the attribute value of a data source, it can first obtain
the ConfigInfo object through getConfigInfo() provided by the LogicRepContext
interface, then obtain the DataSourceInfo object of the data source, and finally read the
corresponding attribute value by using the attribute name over the Get interface.
3. After the development is complete, put the plug-in JAR package in the plugin directory
of logical replication.
The plugin path is /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/plugin.

Step 2 On the primary node, configure the replication plug-in.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 145


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

1. Go to the conf directory.


cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf

2. Open the init.properties file and press i to enter the insert mode.
vi init.properties

3. Configure the replayer.class attribute in the init.properties file to specify the class of
the replication plug-in.
#specify which kind of replayer is used
replayer.class=com.huawei.gauss.logicrep.replayer.SampleReplayer

4. Configure the number of concurrent replay threads.


Logical replication allows multiple transactions that do not conflict to be concurrently
replayed. You can use replayer.thread.number to set the number of replay threads to be
started. When obtaining a group of such concurrent transactions after parsing, the logical
replication service distributes the transactions to each replay thread.
When configuring this number, you need to evaluate whether concurrent transaction
processing meets specific service requirements and evaluate the number of possible
concurrent transactions for services.
#unit: number of replayer threads
#value range:[1,32]
replayer.thread.number=1

5. Press Esc and enter :wq to save the settings and exit.

Step 3 On the primary node, configure the replication data source.


1. Go to the conf directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/conf

2. Open the datasource.properties file and press i to enter the insert mode.
vi datasource.properties

3. Add a section to configure the replication data source parameters for the plug-in.
To name the customized parameters, see the naming convention of existing parameters.
# properties of source/destination datasources defined here
# note:
# 1. section name - datasource name
# 2. mandatory properties:
# ds.type - gauss/oracle/kafka, needed for logicrep

[srcdb]
ds.type=gauss
ds.url=jdbc:zenith:@127.0.0.1:1611?useSSL=false
ds.username=lrep
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=
initial.size=5
min.idle=1
max.idle=10
max.active=50
max.wait=100000

[dstdb]
ds.type=oracle
ds.url=jdbc:oracle:thin:@10.185.240.79:1521:ora11g
ds.username=usrSample
ds.passwd=8W6qr0rX2PwQR3Uf3g/bLcu++haPqbKWXpW7M9nNlAI=
initial.size=10
max.idle=20
min.idle=5
max.active=50
max.wait=100000

[dstkafka]
ds.type=kafka
ds.url=10.185.240.79:9092

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 146


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

compression.type=none
max.block.ms=60000
retries=3
batch.size=1048576
linger.ms=1
buffer.memory=33554432
max.request.size=33554432
request.timeout.ms=10000
optimize.batch.send.buffer=5242880
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config.username=userxxx
#kafka sasl encrypted pwd
sasl.jaas.config.password=passxxx
ssl.truststore.location=/home/kafka.client.truststore.jks
#kafka truststore encrypted pwd
ssl.truststore.password=passxxx
ssl.keystore.location=/home/kafka.client.keystore.jks
#kafka keystore encrypted pwd
ssl.keystore.password=passxxx
#kafka key encrypted pwd
ssl.key.password=passxxx
ssl.keystore.type=JKS
ssl.truststore.type=JKS
ssl.protocol=SSL
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer

4. Press Esc and enter :wq to save the settings and exit.
Step 4 Replicate the modified conf, lib, and plugin folders from the primary node to the standby
node.
1. Log in to the standby GaussDB 100 node as user gaussdba.
2. Replicate the conf, lib, and plugin folders to the standby node.
Assume that the IP address of the primary node is 192.168.0.1.
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/conf /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/lib /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/
scp -r root@192.168.0.1:/opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/
logicrep/plugin /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep/

Step 5 On the primary and standby nodes, start the logical replication service.
The logical replication service loads the replication plug-in by using the replayer.class
attribute and invokes the user-developed replication logic.
1. Go to the logicrep directory.
cd /opt/software/tools/GAUSSDB100-V300R001C00-LOGICREP/logicrep

2. Start the logical replication service.


NOTE

Running the startup.sh and shutdown.sh scripts requires a database installation account.
-- Start the logical replication service on the primary node:
sh startup.sh -n logicrep -a 0-2-422-50b

program start successfully

-- Start the logical replication service on the standby node:


sh startup.sh -n logicrep -a 0-2-f3c9-a549

program start successfully

-n rep_name is a mandatory parameter. It specifies the logical replication relationship to


be started. rep_name has been defined in a replication relationship definition file. The

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 147


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

name is used as the unique identifier of a series of subsequent operations, such as


restarting the logical replication service and querying the replication progress. Therefore,
the name must be unique and cannot be modified when in use. When the logical
replication service is started, all replication relationship definition files in the conf/
repconf directory are checked. If the value of rep_name in a replication relationship
definition file of this logical replication service is the same as that of a started logical
replication service, this service will be forcibly exited.
-a lrep_point is an optional parameter. It specifies the start log point when logical
replication starts. When the table-level and global logical replication switches of the
source database are enabled and logical replication is started for the first time, this
parameter must be used to specify the start point of replication. The value of lrep_point
can be obtained by running the zsql gaussdba/database_123@127.0.0.1:1888 -c
"SELECT lrep_point, lrep_mode FROM sys.DV_DATABASE;" command to query
the DV_DATABASE view after the global logical replication switch of the source
database is enabled.
----End

4.2.5 HA Switchovers
HA switchovers include switchovers and failovers.

Switchovers
1. Application scenarios of switchovers are as follows:
l To upgrade databases, stop the standby server, upgrade the database on the standby
server, and start the standby server. When the primary and standby relationship becomes
stable, switch over the primary and standby servers. Then, upgrade the database on the
original primary server. This way, services remain running properly and no data is lost,
providing high-reliability database services.
l A complex application system involves the database software and other application
processes. If these application processes are abnormal, a switchover will be performed to
prevent data loss, and the primary and standby databases also need to be switched over.
2. The normal switchover procedure is as follows:
Step 1 Query for the role and status of a node.
SQL> SELECT DATABASE_ROLE, DATABASE_CONDITION, SWITCHOVER_STATUS FROM DV_DATABASE;

DATABASE_ROLE DATABASE_CONDITION SWITCHOVER_STATUS


------------------------------ ------------------ --------------------
PHYSICAL_STANDBY NORMAL TO PRIMARY

1 rows fetched.

If the query result shows a standby node and the status is normal, the switchover can be
performed there.
Step 2 Issue the switchover command.
SQL> ALTER DATABASE SWITCHOVER;

Succeed.

Switchovers can be performed only on standby nodes, rather than primary and cascaded
standby nodes.
----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 148


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Failovers
Failovers are designed for scenarios where a primary node encounters a fault which cannot be
rectified in a short time. In primary/standby/cascaded standby deployment, if the primary
node and all standby nodes are faulty, you can perform a failover on a cascaded standby node
to promote it to primary. The procedure is as follows:
Query the standby node status.

Step 1 Query for node status.


SQL> SELECT DATABASE_ROLE, DATABASE_CONDITION, SWITCHOVER_STATUS FROM DV_DATABASE;

DATABASE_ROLE DATABASE_CONDITION SWITCHOVER_STATUS


------------------------------ ------------------ --------------------
PHYSICAL_STANDBY DISCONNECTED TO PRIMARY

If the query result shows a standby node and the status is disconnected, the failover can be
performed there.
Step 2 Issue the failover command.
SQL> ALTER DATABASE FAILOVER;

Succeed.

----End

4.2.6 Common Troubleshooting Methods


Database Building Failure
1. Symptom
When a standby database is built, an error "GS-00323, RFS is not ready, can not get %s."
is reported.
SQL> build database;

GS-00323, RFS is not ready, can not get %s.

2. Locating method
– The firewall is enabled on the primary and standby nodes, and the primary node
cannot connect to the standby node.
– The configuration links are incorrectly configured in zengine.ini on the primary and
standby nodes. As a result, the primary node cannot find the standby node.

Dual Primary Nodes


1. Symptom
Two nodes become primary. In this case, the original standby node is promoted to
primary through a failover, and the original primary node is also started. As a result,
there are two primary nodes.
2. Troubleshooting method
a. Stop the original primary node.
shutdown immediate

b. Start the original primary node in MOUNT mode.


zengine mount

c. Run the following command on the original primary node:

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 149


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

ALTER DATABASE CONVERT TO PHYSICAL STANDBY;

Standby Node in the need repair State


1. Symptom
In maximum performance or maximum availability mode, if a failover is performed on a
standby node and the original primary node is demoted to standby, this new standby
node may be in the need repair state. In this case, you need to rebuild the standby node.
2. Troubleshooting method
a. Stop the standby node.
shutdown immediate

b. Clear the archive directory and data directory on the standby node.
c. Start the standby node in NOMOUNT mode.
zengine nomount

d. Run the following command on the standby node:


build database;

4.3 System Monitoring

4.3.1 Monitoring Metrics


Table 4-8 Metric parameters
Parameter Viewing Description Recommended Alarm
Method Threshold
(View)

SESSIONS DV_SESSION Number of concurrent 4096


S sessions

DATA BUFFER DV_GMA Size of a buffer for The value depends on the
lately accessed data system memory. For
example, if the memory
size is 8 GB, you are
advised to set this
parameter to a value no
greater than 128 MB.

SHARED POOL DV_GMA Total size of space The value depends on the
shared by XPG pools, system memory. For
Lock pools, SQL example, if the memory
pools, and DC pools size is 8 GB, you are
advised to set this
parameter to a value no
greater than 128 MB.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 150


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Parameter Viewing Description Recommended Alarm


Method Threshold
(View)

USED_SIZE ADM_TABLE Usage of resources, The value depends on the


SPACES such as data files in the size specified during
tablespace tablespace creation and
whether the specified size
can be automatically
increased.

4.3.2 Monitoring the Database Status


select * from DV_DATABASE;

NAME STATUS OPEN_COUNT


INIT_TIME CURRENT_SCN RCY_POINT
LRP_POINT CKPT_ID LSN
LFN LOG_COUNT LOG_FIRST LOG_LAST
LOG_MODE SPACE_COUNT DEVICE_COUNT DW_START
DW_END PROTECTION_MODE DATABASE_ROLE
DATABASE_CONDITION SWITCHOVER_STATUS ARCHIVELOG_CHANGE
--------------------------------- ------------------------------ ------------
------------------------------ -------------------- --------------------
-------------------- -------------------- --------------------
-------------------- ------------ ------------ ------------
------------------------------ ------------ ------------ ------------
------------ -------------------- ------------------------------
------------------ ----------------- -----------------
NOAH OPEN 3
2018-02-28 17:48:59 1067883519008768 1-149000
1-149000 10 3229
111 3 0 0
NOARCHIVELOG 4 4 6362
6362 MAXIMUM_PERFORMANCE PRIMARY
NORMAL NOT ALLOWED 1
1 rows fetched.

4.3.3 Monitoring Resource Usage


Check the memory usage.
select * from DV_GMA;

NAME VALUE
---------------------------------------- ----------------------------------------
data buffer 128.00M
shared pool 128.03M
large pool 8.00M
log buffer 4.00M
dbwr buffer 8.00M
lgwr buffer 2.00M
transaction pool 18.19M
temporary buffer 32.00M
8 rows fetched.

Check the data file usage.


select * from DV_DATA_FILES;

ID TABLESPACE_ID STATUS TYPE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 151


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

FILE_NAME BYTES
AUTO_EXTEND AUTO_EXTEND_SIZE MAX_SIZE
------------ ------------- -------------------- --------------------
------------------------------------------------------- --------------------
----- --------------- -------------------- --------------------
0 0 ONLINE FILE /home/
gaussdba/data/data/system 1073741824
FALSE 0 8796093022208
1 1 ONLINE FILE /home/
gaussdba/data/data/temp1_01 167772160
TRUE 33554432 8796093022208
2 1 ONLINE FILE /home/
gaussdba/data/data/temp1_02 167772160
TRUE 33554432 8796093022208
3 2 ONLINE FILE /home/
gaussdba/data/data/undo 1073741824
FALSE 0 34359738368
4 3 ONLINE FILE /home/
gaussdba/data/data/user1 1073741824
TRUE 33554432 8796093022208
5 3 ONLINE FILE /home/
gaussdba/data/data/user2 1073741824
TRUE 33554432 8796093022208
6 3 ONLINE FILE /home/
gaussdba/data/data/user3 1073741824
TRUE 33554432 8796093022208
7 3 ONLINE FILE /home/
gaussdba/data/data/user4 1073741824
TRUE 33554432 8796093022208
8 3 ONLINE FILE /home/
gaussdba/data/data/user5 1073741824
TRUE 33554432 8796093022208
9 4 ONLINE FILE /home/
gaussdba/data/data/temp2_01 167772160
TRUE 33554432 8796093022208
10 4 ONLINE FILE /home/
gaussdba/data/data/temp2_02 167772160
TRUE 33554432 8796093022208
11 5 ONLINE FILE /home/
gaussdba/data/data/temp2_undo 1073741824
FALSE 0 8796093022208

12 rows fetched.

Check the log file usage.


select * from DV_LOG_FILES;

ID STATUS TYPE
FILE_NAME BYTES
WRITE_POS FREE_SIZE RESET_ID ASN BLOCK_SIZE
CURRENT_POINT
------------ -------------------- --------------------
------------------------------------------------------- --------------------
-------------------- -------------------- ------------ ------------ ------------
----------------------------------------------------------------
0 CURRENT ONLINE /home/gaussdba/data/data/
log1 2147483648 14676992
2132806656 0 1 512 0-1/28666/2333
1 INACTIVE ONLINE /home/gaussdba/data/data/
log2 2147483648 512
2147483136 0 0 512
2 INACTIVE ONLINE /home/gaussdba/data/data/
log3 2147483648 512
2147483136 0 0 512
3 INACTIVE ONLINE /home/gaussdba/data/data/
log4 2147483648 512
2147483136 0 0 512
4 INACTIVE ONLINE /home/gaussdba/data/data/

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 152


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

log5 2147483648 512


2147483136 0 0 512
5 INACTIVE ONLINE /home/gaussdba/data/data/
log6 2147483648 512
2147483136 0 0 512

6 rows fetched.

Check the tablespace usage.


select * from DV_TABLESPACES;

ID NAME
TEMPORARY IN_MEMORY AUTO_PURGE EXTENT_SIZE SEGMENT_COUNT FILE_COUNT STATUS
------------ ----------------------------------------------------------------
--------- --------- ---------- ------------ ------------- ------------ --------
0 SYSTEM
FALSE FALSE FALSE 8 143 1 ONLINE
1 TEMP
TRUE FALSE FALSE 16 0 2 ONLINE
2 UNDO
FALSE FALSE FALSE 1 0 1 ONLINE
3 USERS
FALSE FALSE TRUE 8 0 5 ONLINE
4 TEMP2
TRUE FALSE TRUE 8 0 2 ONLINE
5 TEMP2_UNDO
TRUE FALSE FALSE 1 0 1 ONLINE

6 rows fetched.

Check system information.


select * from DV_SYSTEM;

4.3.4 Monitoring Logs


A large number of log files are generated during database running. They can help you with
problem locating, but occupy much disk space. Therefore, you are advised to regularly back
up logs.
l Run log: log/run/zengine.rlog
l Debug log: log/debug/zengine.dlog
l Audit log: log/audit/zengine.aud
l Alarm log: log/zenith_alarm.log During database running, some alarms are generated
and recorded in alarm logs. For details about the alarms, see Managing Logs and section
"Monitoring Alarms" in GaussDB 100 V300R001C00 Database Reference (Standalone).

4.3.5 Collecting Statistics


Statistical information is a set of more detailed descriptions of a database and its objects. It is
used for the query optimizer to select an optimal execution plan for each SQL statement.

4.3.5.1 Manual Collection

Scenario
Databases provide the ANALYZE statement and the advanced DBMS_STATS package to
collect statistics. For example, collect statistics about tables and their indexes.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 153


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

If the data of a table changes greatly, the earlier statistics may become inaccurate. In this case,
you need to collect statistics about the table again. The database provides the
ADM_TAB_MODIFICATIONS and MY_TAB_MODIFICATIONS views to monitor the
number of changes (including insertion, deletion, and update) in a table. You can query the
views to determine whether to collect statistics again.

Precautions
l ANALYZE and DBMS_STATS.GATHER_TABLE_STATS can be used to collect
statistics about temporary tables, and the statistical results will be all 0.
l ANALYZE cannot be used to collect statistics about the following columns: LOB
columns (skipped) and columns of the LONG or object type.
l ANALYZE and DBMS_STATS.GATHER_TABLE_STATS can also be used to collect
statistics about partitioned tables.
l The DBMS_STATS advanced package can be used to collect statistics about all columns
or only indexed columns. However, ANALYZE cannot be used to collect index statistics
independently. If ANALYZE is used to collect table statistics, the index statistics will be
collected together.

Table Statistics
You can collect the following statistics about a table. The table statistics are displayed in the
data dictionary views MY_TABLES, DB_TABLES, and ADM_TABLES.

l Number of rows (NUM_ROWS)


l * Number of data blocks below the HWM, that is, data blocks that have been formatted
to those of received data, no matter whether they are empty (BLOCKS)
l * Number of data blocks allocated to empty tables (EMPTY_BLOCKS)
l Average row length (unit: byte), including the row overhead (AVG_ROW_LEN)

Note: The asterisk (*) indicates that a precise value is required.

Index Statistics
The database provides statistics about collected indexes. Statistics about common indexes are
displayed in the data dictionary views SYS_INDEXES, SYS_INDEX_PARTS,
SYS_INDEX_PARTS, MY_INDEXES, DB_INDEXES, and ADM_INDEXES during
calculation or statistics estimation. For details, see section "Data Dictionary and Views" in
GaussDB 100 V300R001C00 Database Reference (Standalone).

l * Depth of an index from its root block to its leaf block (BLEVEL)
l Number of leaf blocks (LEAF_BLOCKS)
l Number of distinct index keys (DISTINCT_KEYS)
l Average number of leaf blocks for each index key
(AVG_LEAF_BLOCKS_PER_KEY)
l Average number of data blocks for each table index key
(AVG_DATA_BLOCKS_PER_KEY)
l Clustering factor, a sorting order of row and index values (CLUFAC)
l Number of distinct key values of the composite index on the first two columns among
more than two columns (COMB_COLS_2_NDV)

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 154


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

l Number of distinct key values of the composite index on the first three columns among
more than three columns (COMB_COLS_3_NDV)
l Number of distinct key values of the composite index on the first four columns among
more than four columns (COMB_COLS_4_NDV)
Note: The asterisk (*) indicates that a precise value is required.

Column Statistics
A histogram is a special type of column statistics. It provides more detailed information about
the data distribution in a table column. A histogram sorts values into buckets. A bucket
contains values within a certain range.
Based on the number of distinct values (NDV) and data distribution, the database chooses the
type of histogram to create. The types of histograms are as follows:
l Frequency histogram: In a frequency histogram, each distinct column value corresponds
to a single bucket of the histogram. Because each value has its own dedicated bucket,
some buckets may have many values, whereas others have few.
l Height-balanced histogram: In a height-balanced histogram, column values are divided
into buckets so that each bucket contains approximately the same number of rows.
Column statistics are collected together with table statistics. The database determines the type
of a histogram based on the number of values in each column. If the NDV is less than 254, the
database will create a frequency histogram. Otherwise, the database will create a height-
balanced histogram.

Updating and Deleting Statistics


DBMS_STATS.DELETE_TABLE_STATS and
DBMS_STATS.DELETE_SCHEMA_STATS can be used to delete table statistics.
Repeatedly running ANALYZE or DBMS_STATS.GATHER_TABLE_STATS will delete
statistics collected last time and generate new statistics.

4.3.5.2 Automatic Collection

Scenario
If the data of a table changes greatly, the earlier statistics may become inaccurate. In this case,
running an SQL statement on this table may use an inaccurate execution plan determined
based on costs, resulting in low execution efficiency.
Databases allow table statistics to be automatically collected. Users can execute customized
statistics collection jobs periodically or according to the change rate of table data. In this way,
the statistics are collected more accurately, increasing SQL statement execution efficiency.

Scheduled Automatic Collection Jobs


When a database is created, two scheduled jobs are created for user SYS by default.
l Scheduled job 1: Collects statistics on the entire database. This job is executed at 1:00
every day, and the default sampling rate is 10%.
l Scheduled job 2: Collects statistics on changed data tables. This job is executed at an
interval of 15 minutes. The system determines the change rate of all table data in the

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 155


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

database. It collects statistics only when the data change rate of a table is greater than or
equal to 10%. The default sampling rate is 10%.

Running the SELECT * FROM DB_JOBS; statement as user SYS can view the two
scheduled jobs.

The two scheduled jobs for collecting statistics are closed by default. To start them, make the
following preparations:

l Invoke the DBMS_JOB.RUN interface to start a scheduled job. The value of jobid can
be obtained by SELECT * FROM SYS_JOBS;.
exec DBMS_JOB.RUN(jobid);
commit;

l Set the system parameter CBO to ON.


ALTER SYSTEM SET CBO=ON SCOPE=BOTH;

Stored Procedures for Collecting Statistics


The system has two built-in stored procedures, GATHER_DB_STATS and
GATHER_CHANGE_STATS.

l GATHER_DB_STATS: Collects statistics on an entire database table (except system


catalogs) according to a specified sampling rate.
l GATHER_CHANGE_STATS: Collects statistics on data tables that reach a specified
change rate in the system in quasi-real time according to a specified sampling rate.

4.4 Routine Maintenance


Database administrators need to regularly inspect the database status to ensure that the
database is running properly and to detect and avoid potential risks.

Perform a manual inspection by following the instructions provided in Table 1.

Table 4-9 Inspection items


Inspection Item Inspection Method

Check status of the Query the DV_DATABASE and DV_INSTANCE views.


database and instances.

Check the alarm log file. Check whether new alarms are recorded to the alarm log file
zenith_alarm.log.

Check whether the Query the ADM_TABLESPACES view.


available tablespace is
sufficient.

Check the system CPU Query the DV_SYSTEM view.


status.

Check the status and size Query the DV_LOG_FILES view.


of log files.

Check the status and size Query the DV_DATA_FILES view.


of data files.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 156


GaussDB 100
User Guide (Standalone) 4 Routine O&M Management

Inspection Item Inspection Method

Check the requested Query the DV_GMA view.


memory.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 157


GaussDB 100
User Guide (Standalone) 5 Database Usage

5 Database Usage

This chapter describes how to manage database objects, import and export data, manage
transactions, manage logs, and manage database security.

5.1 Configuring Client Access Authentication


Scenario
You can configure client access authentication to allow remote host access. You can configure
a user whitelist, IP address whitelist, or IP address blacklist to control remote connections to
GaussDB 100. By default, only local access is allowed.
l User whitelist: You can add users to zhba.conf so that these users access the database
only through the IP addresses specified in zhba.conf.
l IP address whitelist: Only the IP addresses specified by TCP_INVITED_NODES can
be used to access the database.
l IP address blacklist: The IP addresses specified by TCP_EXCLUDED_NODES cannot
be used to access the database.
The IP address blacklist has the highest priority. If an IP address is configured in all the three
lists, it cannot be used for remote access.
When the user whitelist, IP address whitelist, and IP address blacklist are all enabled:
l Users in the user whitelist can use the IP addresses in the user whitelist and IP address
whitelist to remotely connect to databases (the IP addresses must not be in the IP address
blacklist).
l If the IP address of a client is in the user whitelist (zhba.conf) or IP address whitelist and
not in the IP address blacklist, it will pass the verification for login regardless of whether
the user is in the user whitelist.
For details about remote access policies, see Figure 5-1.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 158


GaussDB 100
User Guide (Standalone) 5 Database Usage

Figure 5-1 Access authentication

NOTE

If user SYS locally logs in to a database in password-free mode, the login will not be limited by the user
whitelist, IP address whitelist, or IP address blacklist.
If user SYS logs in to a database using an encrypted password, the login will be limited by the IP
address blacklist.

Precautions
l Before enabling IP address whitelist checking, ensure that at least one of
TCP_INVITED_NODES and TCP_EXCLUDED_NODES is set. Otherwise, the error
message "GS-00254: For invited and excluded nodes is both empty, ip whitelist function
can't be enabled" will be displayed.
l User SYS can only locally log in to a database.

Prerequisites
Before configuring a user whitelist, IP address blacklist, or IP address whitelist, ensure that
LSNR_ADDR and LSNR_PORT have been configured. Otherwise, the configuration will
not take effect. Do as follows:
Method 1:

Step 1 Check whether the listening IP address and port have been configured on the server.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 159


GaussDB 100
User Guide (Standalone) 5 Database Usage

SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_ADDR';


SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_PORT';

l If they have been configured, finish the procedure.


Step 2 If they have not been configured, run the following statement to enable the floating IP address
of the database: (The setting takes effect immediately.)
ALTER SYSTEM ADD LSNR_ADDR '192.168.1.1';

----End
Method 2:

Step 1 Check whether the listening IP address and port have been configured on the server.
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_ADDR';
SELECT NAME,VALUE FROM DV_PARAMETERS WHERE NAME = 'LSNR_PORT';

l If they have been configured, finish the procedure.


l If they have not been configured, run the following statements to configure them, and
then go to Step 2:
ALTER SYSTEM SET LSNR_ADDR='127.0.0.1,192.168.1.1';
ALTER SYSTEM SET LSNR_PORT = 1888;

Step 2 Restart the database for the configurations of the listening IP address and listening port
number to take effect.
cd ${GSDB_DATA}/bin
python zctl.py -t stop
python zctl.py -t start

----End

Procedure – User Whitelist Configuration


Assume that the IP address of a server is 192.168.1.1 and the listening port number is 1888.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.

Step 2 Query for a configured user whitelist.


zsql gaussdba/database_123@127.0.0.1:1888
SELECT * FROM SYS.DV_HBA;

Step 3 Add an HBA entry (TYPE, USER, and ADDRESS) to the zhba.conf file.
cd ${GSDB_DATA}/cfg
vim zhba.conf
host user 127.0.0.1,192.168.3.222,20AB::9217:acff:feab:fcd0/64

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 160


GaussDB 100
User Guide (Standalone) 5 Database Usage

NOTE

l ADDRESS lists the IP addresses allowed for database connections. Separate multiple IP addresses
with commas (,). HBA entries are independent from each other and their order in the whitelist does
not affect the whitelist functionality.
l If a username contains special characters such as number sign (#) and tab characters, enclose the
name with double quotation marks (""). In host "#abc" 127.0.0.1 and host "abc" 127.0.0.1, the
strings enclosed in the double quotation marks are usernames.
l If a string is "*" or *, all users will be listed.
l The IP addresses can be IPv4 or IPv6 addresses, or a network segment with the subnet mask or
prefix length specified. All the following formats are valid:
– 192.168.3.222 indicates an IPv4 host.
– 192.168.3.0/24 indicates an IPv4 segment with the specified subnet mask length 24.
– 20AB::9217:acff:feab:fcd0 indicates an IPv6 host.
– 20AB::9217:acff:feab:fcd0/64 indicates an IPv6 segment with the specified subnet prefix
length 64.
l When editing the zhba.conf file, do not press Tab to enter a space. Otherwise, the error message
"GS-00220, hba line(20) format is not correct" will be displayed when you load the user whitelist
online.

Step 4 Load the user whitelist online.


1. Use zsql to connect to the database.
zsql gaussdba/database_123@127.0.0.1:1888

2. Run the following statement to load the user whitelist online. The whitelist takes effect
immediately after the statement is executed.
ALTER SYSTEM RELOAD HBA CONFIG;

3. Query the DV_HBA view to check whether the user whitelist is configured successfully.
SELECT * FROM SYS.DV_HBA;

----End

Procedure – IP Address Whitelist and Blacklist Configuration


Assume that the IP address of a server is 192.168.1.1 and the listening port number is 1888.
Configure 192.168.2.* as whitelisted IP addresses and 192.168.10.* and 192.168.2.225 as
blacklisted IP addresses.

Step 1 Log in to the server where GaussDB 100 is deployed as the OS user who installs the
GaussDB 100 database.
Step 2 Query for a configured IP address whitelist and a configured IP address blacklist.
zsql gaussdba/database_123@127.0.0.1:1888
SELECT VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_INVITED_NODES';
SELECT VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_EXCLUDED_NODES';

Step 3 Configure the IP address whitelist or blacklist online. The configuration takes effect
immediately, and you do not need to restart the database.
NOTE

The IP addresses specified by TCP_INVITED_NODES cannot exceed 1024 bytes. Otherwise, an error
will be reported.

l Configure the IP address whitelist.


ALTER SYSTEM SET TCP_INVITED_NODES = '(127.0.0.1,192.168.1.1, 192.168.2.*)';

l Configure the IP address blacklist.


ALTER SYSTEM SET TCP_EXCLUDED_NODES = '(192.168.10.*, 192.168.2.225)';

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 161


GaussDB 100
User Guide (Standalone) 5 Database Usage

Step 4 Enable IP address whitelist checking online. The function takes effect immediately, and you
do not need to restart the database.
ALTER SYSTEM SET TCP_VALID_NODE_CHECKING = true;

Run the following command to check whether the function takes effect:
SELECT NAME, VALUE FROM DV_PARAMETERS WHERE NAME = 'TCP_VALID_NODE_CHECKING';
NAME VALUE
----------------------------------------------------------------
--------------------
TCP_VALID_NODE_CHECKING TRUE

----End

5.2 Connecting to a Database


You can log in to GaussDB 100 in either of the following ways:
l Remote password-authentication login: The password can be an encrypted password for
remote connection or a non-encrypted password for local connection.
l Local password-free login: You log in as a Linux system user that has passed the
authentication. Therefore, you can use zsql to log in to the database running on the local
host. You can reset the password of user SYS after logging in as this user.

If you have logged in to a database through zsql in non-interactive mode, there would be a
large number of plaintext passwords in the environment. Therefore, you are advised to log in
to GaussDB 100 in interactive mode.
If no IP address is specified during password-free login, the first IP address of LSNR_ADDR
in the local configuration file will be used.

Scenario
Use zsql to connect to a GaussDB 100 server. Then, you can run SQL statements and perform
database operations.

Prerequisites
l The zsql tool has been installed on the client.
l The user for connection must have permission to access the database.
l Before remotely accessing a database through APIs such as zsql or JDBC, set LSNR_IP
and LSNR_PORT in the zengine.ini file. A maximum of eight listening IP addresses
can be set at a time, and they must be separated by commas (,). For details, see
Configuring Client Access Authentication.
l Before remotely accessing a database, configure access authentication on the local client.
For details about how to configure client access authentication, see Configuring Client
Access Authentication in GaussDB 100 V300R001C00 User Guide (Standalone).

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 162


GaussDB 100
User Guide (Standalone) 5 Database Usage

Precautions
If the password of a database user contains the special character $, use the escape character \
to connect to the database through zsql. Otherwise, the login will fail.

Procedure
l Log in as a database administrator. (Only database administrators can use password-free
login.)
zsql
{ CONNECT | CONN } / AS SYSDBA [ip:port] [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

[ip:port] is optional. If it is not specified, the local host will be connected by default.
If a database administrator has started multiple database instances, you need to specify
the database directory (-D) when connecting to a specified database.
The -q parameter is used to cancel the SSL login authentication check. The -s parameter
is used to set the silent mode (no prompt) for SQL statement execution.
The -w parameter is used to set the timeout period for the client to wait for a connection
response from the database. Its values are -1, indicating that the client keeps waiting
without timeout restrictions; 0, indicating that the client does not wait and the server
directly returns a failure result; and n, indicating that the client waits for n seconds. The
default value is 10s. After this parameter is used, its value will be the response waiting
timeout period when the zsql process is started to connect to the database. After the
process startup, the timeout period will be used in waiting for a response for establishing
or reestablishing a new connection as well as that in queries. After the zsql process is
exited, the setting becomes invalid.
l Log in as a common database user.
GaussDB 100 supports the following login modes:
– Interactive login mode 1:
zsql user@ip:port [-D /home/gaussdba/data1] [-q] [-s "silent_file"] [-w
connect_timeout]

Enter the password as prompted.


Please enter password:

– Interactive login mode 2:


zsql
conn user/user_password@ip:port [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

– Non-interactive login mode:


zsql user/user_password@ip:port [-D /home/gaussdba/data1] [-q] [-s
"silent_file"] [-w connect_timeout]

In this command, user indicates the name of the database user and password indicates
the password of the user. ip:port indicates the IP address and port number of the host
where the database resides. The default port number is 1888.
If a database administrator has started multiple database instances, you need to specify
the database directory (-D) when connecting to a specified database.
The -q parameter is used to cancel the SSL login authentication check. The -s parameter
is used to set the silent mode (no prompt) for SQL statement execution.
The -w parameter is used to set the timeout period for the client to wait for a connection
response from the database. Its values are -1, indicating that the client keeps waiting
without timeout restrictions; 0, indicating that the client does not wait and the server
directly returns a failure result; and n, indicating that the client waits for n seconds. The
default value is 10s. After this parameter is used, its value will be the response waiting

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 163


GaussDB 100
User Guide (Standalone) 5 Database Usage

timeout period when the zsql process is started to connect to the database. After the
process startup, the timeout period will be used in waiting for a response for establishing
or reestablishing a new connection as well as that in queries. After the zsql process is
exited, the setting becomes invalid.

Examples
l Locally log in to a database as user gaussdba.
gaussdba@plat1~> zsql
SQL> CONN gaussdba/database_123@127.0.0.1:1888

connected.

l Start the zsql process and set a response waiting timeout period.
-- Start the zsql process and set the response waiting timeout period to 20s.
After the process is started, the timeout period for waiting for a connection
setup response will be 20s.
zsql gaussdba/database_123@127.0.0.1:1888 -w 20
connected.
-- Create a user jim and grant the CREATE SESSION permission to the user.
DROP USER IF EXISTS jim;
CREATE USER jim IDENTIFIED BY database_123;
GRANT CREATE SESSION TO jim;
-- Switch to the user. The timeout period for waiting for a reconnection
setup response will be also 20s.
CONN jim/database_123@127.0.0.1:1888
connected.
-- Exit the zsql process. The timeout period setting becomes invalid, and the
timeout period for waiting for a new connection setup response will be 10s
(default value).
EXIT

5.3 Managing Database Objects


Database objects include users, tables, tablespaces, partitioned tables, indexes, sequences,
synonyms, and views. Database objects can be managed only by users having corresponding
permissions. For details about permission management, see Database Security Maintenance
> Managing Users and Their Permissions > Managing User Permissions in GaussDB 100
Security Maintenance Guide. This section describes how to create, modify, and delete a
database object.

5.3.1 Managing Tablespaces


In GaussDB 100, a database administrator uses tablespaces to define the storage locations of
database object files. After administrators create a tablespace, the tablespace can be
referenced during database object creation.

Related Concepts
A GaussDB 100 database tablespace consists of one or more data files. Database objects are
logically stored in tablespaces and physically stored in data files.

A schema is a collection of database objects. A schema can exist in multiple tablespaces, and
a tablespace can contain multiple schemas. By default, a user corresponds to a schema. When
a user is created, the database creates a default schema with the same name as the user to store
the objects created by the user. Therefore, the number of schemas in a database is the same as
the number of users. If the schema name of a table is not explicitly specified when the table is
accessed, the database will automatically append the default schema name to the table.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 164


GaussDB 100
User Guide (Standalone) 5 Database Usage

During GaussDB 100 database creation, the following tablespaces are automatically created:
l SYSTEM tablespace
It stores GaussDB 100 metadata. To ensure stable database running, you are advised not
to store user data in the SYSTEM tablespace. By default, the SYSTEM tablespace is not
automatically extended. If it is full, manually add data files or extend the tablespace.
l TEMP tablespace
It is automatically maintained by GaussDB 100. When SQL statements apply for disk
space, the GaussDB 100 database allocates temporary segments from the TEMP
tablespace. The TEMP tablespace is also used for index creation, data sorting that
cannot be executed in the memory, intermediate result sets of SQL statements, and
temporary tables.
l UNDO tablespace
It stores undo data. When a DML operation (INSERT, UPDATE, or DELETE) is
performed, old data before the operation is written into the UNDO tablespace. Such a
tablespace is mainly used for transaction rollback, database instance restoration, read
consistency, and flashback query.
l USERS tablespace
It is the default tablespace. When a user is created with no tablespace specified, all
information about the user is stored in the USER tablespace.
l TEMP2 tablespace
It stores NOLOGGING Tables data, and is automatically maintained by GaussDB 100.
l TEMP2_UNDO tablespace
It stores NOLOGGING Tables undo data.
Database administrators can use tablespaces to control the layout of disks for installing a
database. This has the following advantages:
l If the disk partition or volume initially allocated to the database is full and the space
cannot be logically extended, you can create and use tablespaces in other partitions until
the system space is reconfigured.
l Tablespaces allow database administrators to arrange storage locations for database
objects as needed, improving database performance.
– A frequently used index can be placed in a disk having stable performance and high
computing speed.
– A table that stores archived data and is rarely used or has low performance
requirements can be placed in a disk with a slow computing speed.
l Database administrators can specify physical disk space for data by using tablespaces.
When multiple application services share one server, database administrators can use
tablespaces to limit the volume of accessed data and prevent the tablespaces from
occupying other spaces in the same partition. This prevents application service
breakdown caused by disk space exhaustion.

Creating a Tablespace
When using the CREATE TABLESPACE statement to create a tablespace, you can specify
the EXTENTS parameter, which specifies the number of pages in an extent.
l EXTENTS
Specifies the number of pages in an extent.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 165


GaussDB 100
User Guide (Standalone) 5 Database Usage

The value must be an integral power of 2 in the range [8, 1024]. If EXTENTS is omitted, an
extent will contain 8 pages.

Increasing the number of pages in a single extent can improve I/O performance. However, if
there are small tables in the tablespace and the table data volume does not reach the size of an
extent, space will be wasted.

l Use the tablespace human_resource as an example. Assume that an extent contains 128
pages. In human_resource, the data file is humanspace_1, and its size is 128 MB. The
tablespace is also enabled with automatic extension (128 MB), that is, the tablespace will
be automatically extended by 128 MB after it is full.
– Run the CREATE TABLESPACE statement to create a tablespace.
CREATE TABLESPACE human_resource EXTENTS 128 DATAFILE 'humanspace_1'
SIZE 128M AUTOEXTEND ON NEXT 128M;

– Create an object in the tablespace. The following describes how to create a table
education.
To create a database object in a tablespace, you must have the CREATE
TABLESPACE permission for the tablespace.
CREATE TABLE education
(
staff_id INT,
higest_degree CHAR(8) NOT NULL,
graduate_school VARCHAR(64),
graduate_date DATETIME,
education_note VARCHAR(70)
)
TABLESPACE human_resource;

Viewing Tablespaces
Database administrators can query the ADM_TABLESPACES view to observe information
about all tablespaces.

Common users can query the ADM_TABLESPACES view to observe information about the
current tablespace.

Extending a Tablespace
Run the ALTER TABLESPACE statement to add a data file to a tablespace.
ALTER TABLESPACE human_resource ADD DATAFILE 'new_datafile' SIZE 128M;

Shrinking a Tablespace
Run the ALTER TABLESPACE statement to shrink a tablespace. In RESTRICT mode,
TEMP and UNDO tablespaces can be shrank.

To shrink an UNDO tablespace, ensure there is no residual transaction.


ALTER TABLESPACE human_resource SHRINK SPACE KEEP 200M;

Modifying a Tablespace
Run the following statement to change the name of the tablespace human_resource to
staff_resource:
ALTER TABLESPACE human_resource RENAME TO staff_resource;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 166


GaussDB 100
User Guide (Standalone) 5 Database Usage

Deleting a Tablespace
Run the DROP TABLESPACE command to delete the tablespace human_resource.
-- Check tablespace usage:
SELECT * FROM adm_objects WHERE tablespace_name= 'HUMAN_RESOURCE';
SELECT * FROM adm_segments WHERE tablespace_name='HUMAN_RESOURCE';

-- Delete the table education:


DROP TABLE education;
-- Clear the tablespace:
PURGE TABLESPACE human_resource;
-- Delete the tablespace human_resource:
DROP TABLESPACE human_resource;

l The SYSTEM, UNDO, and TEMP tablespaces cannot be deleted.


l A tablespace that has been used cannot be deleted.
l Tablespaces in offline mode can be deleted only when the database is in OPEN status.

5.3.2 Managing Tables


Tablespaces have a lower-level logical structure, data tables. A table is the basic unit of data
storage in a database, consisting of rows and columns. Each row represents a record, and each
column contains a fixed attribute.
This section uses a table staffs as an example to describe how to create a data table in
GaussDB 100 and how to modify the table structure. For details about statements and
restrictions, see GaussDB 100 R&D Documentation.

5.3.2.1 Creating a Table

Prerequisites
If a user needs to create a table in its schema, it must have the CREATE TABLE permission.
If a user needs to create a table in another user's schema, the user must have the CREATE
ANY TABLE permission.

Related Concepts
A table definition includes a table name (such as staffs) and a set of columns. Each column
has two attributes, a column name and a data type. For example, a column name is
STAFF_ID, with a data type of NUMBER(6); and another column name is FIRST_NAME,
with a data type of VARCHAR(20 BYTE). Each column allows for an integrity constraint
(such as NOT NULL). This constraint ensures that each row in the column contains a value.
After creating a table, you can run the INSERT statement to insert data, use a data import and
export tool to load data, or run CREATE TABLE AS Query to create a table with data.
l Columns and their data types
The data type of a column determines the type of values in the column. Select a data type
that requires the least space and does not affect data storage. For example, select a
VARCHAR type for storing character strings, a DATE or TIMESTAMP type for storing
dates, and a NUMERIC type for storing numbers. For the CHAR, VARCHAR, and
TEXT data types, if spaces are entered as values, no performance differences will be
generated. In most cases, TEXT and VARCHAR are prior to CHAR.
To join two tables, the join key columns must have the same data type. In most cases, the
primary key of one table and the foreign key of the other table are used as join key

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 167


GaussDB 100
User Guide (Standalone) 5 Database Usage

columns. If the data types are different, the database will convert either of the data types
and verify the value correctness, leading to unnecessary overheads.
l Table and column constraints (If you define constraints for tables and columns, data
contained in the tables and columns will be restricted.)
– [ NOT ] NULL
Specifies whether a column can hold NULL values.
– UNIQUE
Specifies that values in a column must be unique. NULL values are allowed. The
UNIQUE constraint can be added to multiple columns in a table.
– PRIMARY KEY
Specifies a primary key. A primary key column cannot hold NULL values, and a
table can have only one primary key.

Ordinary Tables
Create the staffs table in the human_resource tablespace, and forbid NULL values in the
STAFF_ID column.
CREATE TABLE hr.staffs
(
staff_id NUMBER(6) NOT NULL,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
)
TABLESPACE human_resource;

Temporary Tables
In GaussDB 100, you can create temporary tables. A temporary table holds data that exists
only for the duration of a transaction or session when there are complex queries. When a
session ends or a user commits or rolls back a transaction, the temporary table will be
automatically cleared, but the table structure will remain. Temporary tables are classified into
session-level temporary tables and transaction-level temporary tables. If the ON COMMIT
{DELETE | PRESERVE} ROWS clause is not specified when a temporary table is created,
a transaction-level temporary table will be created.
Global temporary tables allow users to create temporary indexes, and to update, insert, and
delete data. Data in such an index has the same session or transaction scope as data in the
temporary table. A local temporary table supports only ON COMMIT PRESERVE ROWS
and the table name must start with a number sign (#). In addition,
LOCAL_TEMPORARY_TABLE_ENABLED=TRUE must be used. The
LOCAL_TEMPORARY_TABLE_ENABLED parameter specifies whether to enable local
temporary tables.
l Session-level temporary tables (ON COMMIT PRESERVE ROWS)
Data in a temporary table exists only for the duration of a session. When the session
ends, the temporary table is automatically cleared. The TRUNCATE statement is

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 168


GaussDB 100
User Guide (Standalone) 5 Database Usage

executed to delete data from only the current temporary table, instead of the temporary
tables specific to other sessions.
Create a session-level global temporary table staff_history_session.
CREATE GLOBAL TEMPORARY TABLE staff_history_session
(startdate DATE,
enddate DATE
)
ON COMMIT PRESERVE ROWS;

l Transaction-level temporary tables (ON COMMIT DELETE ROWS)


Data in a temporary table exists only for the duration of a transaction. When a
transaction ends (committed or rolled back), the temporary table is automatically cleared.
Create a transaction-level global temporary table staff_history_session.
CREATE GLOBAL TEMPORARY TABLE staff_history_session
(startdate DATE,
enddate DATE
)
ON COMMIT DELETE ROWS;

NOLOGGING Tables
A NOLOGGING table does not record redo logs. A smaller number of logs will improve
system performance. However, since there is no redo log, a database cannot be restored by
replaying logs after a restart. Table definitions are reserved but data is deleted. Non-core data
that does not require high reliability can be saved in a NOLOGGING table. The tablespace of
a NOLOGGING table must be the NOLOGGING tablespace. If the tablespace is not
specified, the TEMP2 tablespace will be used.
NOLOGGING tables:
l Allow users to replicate table definitions, not table data, between primary and standby
databases.
l Allow users to back up and restore table definitions, not table data.
l Support MVCC and rollback, as well as DDL and DML operations that ordinary tables
support.
A NOLOGGING table can be created by specifying the keyword NOLOGGING or the
tablespace NOLOGGING.
l Specify the keyword NOLOGGING to create a table staffs_nologging.
CREATE TABLE staffs_nologging
(
staff_id NUMBER(6) NOT NULL,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
)NOLOGGING;

l Specify the tablespace TEMP2 to create a NOLOGGING table staffs_temp2.


CREATE TABLE staffs_temp2(
staff_id NUMBER(6) NOT NULL,
first_name VARCHAR2(20),
last_name VARCHAR2(25),

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 169


GaussDB 100
User Guide (Standalone) 5 Database Usage

email VARCHAR2(25),
phone_number VARCHAR2(20),
hire_date DATE,
employment_id VARCHAR2(10),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
manager_id NUMBER(6),
section_id NUMBER(4),
graduated_name VARCHAR2(60)
) TABLESPACE temp2;

5.3.2.2 Viewing Table Information

Scenario
In GaussDB 100, you can view the definition of a table and all data in the table.

Prerequisites
When the SELECT statement is used to view a table, authorization is not required if the user
is the owner of the table. Otherwise, the SELECT permission for the table or the SELECT
ANY TABLE permission is required.

Procedure
l View table data.
SELECT * FROM staffs;

l View a table definition.


In GaussDB 100, you can run the DESC statement to view the definition of a table.
View information about the staffs table.
DESC staffs;
Name Null? Type
----------------------------------- --------
------------------------------------
STAFF_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR(20 BYTE)
LAST_NAME VARCHAR(25 BYTE)
EMAIL VARCHAR(25 BYTE)
PHONE_NUMBER VARCHAR(20 BYTE)
HIRE_DATE DATE
EMPLOYMENT_ID VARCHAR(10 BYTE)
SALARY NUMBER(8, 2)
COMMISSION_PCT NUMBER(2, 2)
MANAGER_ID NUMBER(6)
SECTION_ID NUMBER(4)

5.3.2.3 Modifying a Table

Scenario
After a table is created, you can run the ALTER TABLE statement to change the table
definition if the service scenario changes. Typical functions are as follows:

l Renaming a table
l Adding, modifying, and deleting a column
l Imposing constraints on adding, renaming, and deleting

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 170


GaussDB 100
User Guide (Standalone) 5 Database Usage

l Enabling and disabling a constraint


l Modifying foreign key information
l Modify partition information (For details, see Managing Partitioned Tables. This
section includes no further illustration.)
l Shrinking LOB columns

Prerequisites
When the ALTER TABLE statement is used to modify a table, authorization is not required
if the user is the owner of the table. Otherwise, the ALTER permission for the table or the
ALTER ANY TABLE permission is required.

Precautions
l Users can modify the names of only the tables in their schemas.
l Common users cannot modify the objects of database administrators.
l The unique index, primary key, and foreign key inline constraints cannot be contained in
a statement for adding or modifying the attributes of a column.
l Table definitions cannot be changed during database restart or rollback.

Procedure
The following illustrates the above functions. Unless otherwise specified, the ordinary table
created in Creating a Table is used as the example.
Renaming a table
Rename the staffs table to staffs_group.
ALTER TABLE hr.staffs RENAME TO hr.staffs_group;

Adding, modifying, and deleting a column


l Add the graduated_time column to the staffs_group table, with the data type set to
DATE.
ALTER TABLE hr.staffs_group ADD graduated_time DATE;

l Change the data type of the phone_number column in the staffs_group table to
BIGINT.
ALTER TABLE hr.staffs_group MODIFY phone_number BIGINT;

l Delete the commission_pct column from the staffs_group table.


ALTER TABLE hr.staffs_group DROP commission_pct;

Imposing constraints on adding, renaming, and deleting


l Add a constraint to the staffs_group table, limiting salary to be no less than 1000 and
staff_id to be unique.
ALTER TABLE hr.staffs_group ADD CONSTRAINT ck_staffs CHECK(salary>1000);
ALTER TABLE hr.staffs_group ADD CONSTRAINT uq_staffs UNIQUE(staff_id);

l Rename the uq_staffs constraint of the staffs_group table.


ALTER TABLE hr.staffs_group RENAME CONSTRAINT uq_staffs TO uq_staffs_new ;

l Delete the uq_staffs_new constraint from the staffs_group table.


ALTER TABLE hr.staffs_group DROP CONSTRAINT uq_staffs_new ;

Enabling and disabling a constraint


l Disable the constraint on the staffs_group table, and check whether existing data meets
the constraint.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 171


GaussDB 100
User Guide (Standalone) 5 Database Usage

ALTER TABLE hr.staffs_group DISABLE VALIDATE;

l Enable the constraint on the staffs_group table.


ALTER TABLE hr.staffs_group ENABLE;

Adding and modifying foreign key information

1. Delete existing tables named staffs_f or employeeinfo_f, if any.


DROP TABLE IF EXISTS staffs_f;
DROP TABLE IF EXISTS employeeinfo_f;

2. Create ordinary tables staffs_f and employeeinfo_f.


-- Create a basic employee information table.
CREATE TABLE staffs_f
(
staff_id NUMBER(6) PRIMARY KEY,
first_name VARCHAR2(20),
last_name VARCHAR2(25),
email VARCHAR2(25),
phone_number VARCHAR2(20),
graduated_name VARCHAR2(60)
);

-- Create an employment information table.


CREATE TABLE employeeinfo_f
(
staff_id NUMBER(6),
employment_id VARCHAR2(10) PRIMARY KEY,
hire_date DATE,
salary NUMBER(8,2),
);

staff_id in the employeeinfo_f table is the primary key of the staffs_f table. Therefore,
staff_id is the foreign key of the employeeinfo_f table.
3. Add the foreign key staff_id to the employeeinfo_f table.
ALTER TABLE employeeinfo_f ADD CONSTRAINT fk FOREIGN KEY (staff_id)
REFERENCES staffs_f(staff_id);

4. Change the foreign key constraint name of the employeeinfo_f table to fk_cons.
ALTER TABLE employeeinfo_f RENAME CONSTRAINT fk fk_cons;

Shrinking LOB columns

1. Add the profile column (about personal profile information) to the hr.staffs_group table
and set the data type to CLOB.
ALTER TABLE hr.staffs_group ADD profile CLOB;

2. As a database runs, the space occupied by CLOB columns may slowly increase. You can
run the following statement to reduce the space occupied by the CLOB columns:
ALTER TABLE hr.staffs_group MODIFY LOB profile (SHRINK SPACE);

5.3.2.4 Clearing a Table

Scenario
When table data is no longer used, delete all the rows of the table, that is, clear the table.

Prerequisites
When the DELETE or TRUNCATE statement is used to clear a table, authorization is not
required if the user is the owner of the table. Otherwise, the DELETE permission for the
table or the DROP ANY TABLE permission is required.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 172


GaussDB 100
User Guide (Standalone) 5 Database Usage

Procedure
l Run the DELETE statement to delete rows from the staffs table.
– Delete the rows whose staff_id is 198 from the staffs table.
DELETE FROM staffs WHERE staff_id = '198';

– Delete all rows from the staffs table.


DELETE FROM staffs;

l Run the TRUNCATE statement to delete all rows from the table.

The TRUNCATE statement does not support rollback.

TRUNCATE TABLE staffs;

5.3.2.5 Deleting a Table

Scenario
When the data or definition of a table is no longer needed, you can run the DROP TABLE
statement to delete the table.

Prerequisites
When the DROP TABLE statement is used to drop a table, authorization is not required if the
user is the owner of the table. Otherwise, the DROP permission for the table or the DROP
ANY TABLE permission is required.

Procedure
Step 1 Delete the hr.staffs_group table.
DROP TABLE IF EXISTS hr.staffs_group;

----End

5.3.3 Managing Partitioned Tables


Scenario
GaussDB 100 supports range partitioning, list partitioning, hash partitioning, and interval
partitioning. Table partitioning can improve database query performance, enhance availability,
facilitate maintenance, and balance I/O.

Related Concepts
GaussDB 100 supports range partitioned tables, list partitioned tables, hash partitioned tables,
and interval partitioned tables.
l Range partitioned table: Data within a specific range is mapped onto each partition. The
range is determined by the partition key specified when the partitioned table is created.
This partitioning mode is most commonly used. The partition key is usually a date. For
example, sales data is partitioned by month.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 173


GaussDB 100
User Guide (Standalone) 5 Database Usage

l Interval partitioned table: It is a special type of range partitioned table. If common range
partitions have been created and data not in the partitions is inserted, the database will
report an error. In this case, you can manually add a partition or use an interval partition.
A user can create range partitioned tables by day. For example, during service
deployment, a batch of partitions (like three months) are created for future use. However,
the table needs to be created again three months later. Otherwise, an error will be
reported when service data is saved to the database. The range partitioning mode
increases maintenance costs, and the kernel is required to support automatic partition
creation. If interval partitioning is used, you do not need to concern about subsequent
partition creation, which reduces design costs and partition maintenance costs.
l List partitioned table: A large table is split into small, easy-to-manage blocks.
l Hash partitioned table: Usually, users cannot predict the range of data changes on a
column and therefore cannot create a fixed number of range partitions or list partitions.
Hash partitioning provides a method for evenly grouping data in a specified quantity of
partitions. In this way, data written to a table is evenly distributed in each partition, and
users cannot predict the partition where the data is written. For example, sales cities are
spreading across a country, and the table can barely support list partitioning. In this case,
hash partitioning is recommended.
A partitioned table has the following advantages over an ordinary table:
l High query performance: Users can specify partitions when querying partitioned tables,
improving query efficiency.
l High availability: If a partition in a partitioned table is faulty, data in the other partitions
is still available.
l Easy maintenance: If a partition in a partitioned table is faulty, only this partition needs
to be repaired.
l Balanced I/O: Partitions can be mapped to different disks to balance I/O and improve the
overall system performance.

Procedure
Perform the following operations on a range partitioned table:
l Delete existing tables named staffs_p, if any.
DROP TABLE IF EXISTS staffs_p;

l Create a partitioned table staffs_p.


CREATE TABLE staffs_p
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
)
PARTITION BY RANGE (staff_ID)
(
partition P_050_BEFORE values less than (50),
partition P_100 values less than (100) ,
partition P_150 values less than (150) ,
partition P_200 values less than (200)
);

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 174


GaussDB 100
User Guide (Standalone) 5 Database Usage

l Delete the P_200_AFTER partition.


ALTER TABLE staffs_p DROP PARTITION P_200_AFTER;

l Add the P_250 partition. The value range is 200 <= P_250 <= 250.
ALTER TABLE staffs_p ADD PARTITION P_250 VALUES LESS THAN (250);

l Query the P_150 partition.


SELECT * FROM staffs_p PARTITION (P_150);

l Create an index for the partitioned table.


– Create a partitioned table index HR_staffS_p1_index1, without specifying index
partitions.
CREATE INDEX HR_staffS_p1_index1 ON staffs_p (staff_ID) LOCAL;

– Create a partitioned table index HR_staffS_p1_index2, with index partitions


specified.
CREATE INDEX HR_staffS_p1_index2 ON staffs_p (section_ID) LOCAL
(
PARTITION section_ID1_index,
PARTITION section_ID2_index TABLESPACE USERS,
PARTITION section_ID3_index TABLESPACE USERS,
PARTITION section_ID4_index,
PARTITION staff_ID5_index
) TABLESPACE USERS;

Perform the following operations on a hash partitioned table:


l Delete existing tables named staffs_p2017 or staffs_p2018, if any.
DROP TABLE IF EXISTS staffs_p2017;
DROP TABLE IF EXISTS staffs_p2018;

l Create a partitioned table.


– Creates a hash partitioned table, with partition names specified but the number of
partitions not specified.
CREATE TABLE staffs_p2017
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
)
PARTITION BY HASH(staff_ID)
(
PARTITION P_01 tablespace USERS,
PARTITION P_02 tablespace USERS,
PARTITION P_03 tablespace USERS,
PARTITION P_04 tablespace USERS,
PARTITION P_05 tablespace USERS
);

– Creates a hash partitioned table, with the number of partitions specified but partition
names not specified.
CREATE TABLE staffs_p2018
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 175


GaussDB 100
User Guide (Standalone) 5 Database Usage

COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
)
PARTITION BY HASH (staff_ID) PARTITIONS 5 STORE IN(USERS,USERS);
l Delete a partition.
When the COALESCE operation is performed, data of the last partition is inserted into
a previous partition, and then the last partition is deleted. If there is only one partition
left, deleting this partition will report an error.
ALTER TABLE staffs_p2017 COALESCE PARTITION;
ALTER TABLE staffs_p2018 COALESCE PARTITION;
l Add the part_06 partition.
ALTER TABLE staffs_p2017 ADD PARTITION part_06;
l Query a partition.
– Query a partition of the hash partitioned table with partition names specified.
Run the following statement to query P_04:
SELECT * FROM staffs_p2017 PARTITION(P_04);
– Query a partition of the hash partitioned table with the number of partitions
specified.
-- Query the SYS.SYS_TABLE_PARTS and SYS.SYS_TABLES system catalogs to
obtain partition names:
SELECT * FROM SYS.SYS_TABLE_PARTS WHERE TABLE# = (SELECT ID FROM
SYS.SYS_TABLES WHERE NAME='STAFFS_P2018');

USER# TABLE# PART#


NAME
HIBOUNDLEN
HIBOUNDVAL
SPACE# ORG_SCN ENTRY INITRANS
PCTFREE FLAGS
BHIBOUNDVAL
ROWCNT BLKCNT EMPCNT AVGRLN SAMPLESIZE
ANALYZETIME
------------ ------------ ------------
----------------------------------------------------------------
------------
----------------------------------------------------------------
------------ -------------------- -------------------- ------------
------------ ------------
----------------------------------------------------------------
------------ ------------ ------------ ------------ ------------
----------------------
2 71 10
SYS_P1023
0
3 2189599603179522 4393751543808 2
8
0

2 71 20
SYS_P1024
0
3 2189599603179523 4393751543808 2
8
0

2 71 30
SYS_P1025
0
3 2189599603179524 4393751543808 2
8
0

2 71 40

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 176


GaussDB 100
User Guide (Standalone) 5 Database Usage

SYS_P1026
0
3 2189599603179525 4393751543808 2
8 0

4 rows fetched.
-- Query the partition named SYS_P1024:
SELECT * FROM STAFFS_P2018 PARTITION(SYS_P1024);

l Create an index for the partitioned table.


– Create a partitioned table index HR_staffS_p1_index_2017, without specifying
index partitions.
CREATE INDEX HR_staffS_p1_index_2017 ON staffs_p2017 (staff_ID) LOCAL;

– Create a partitioned table index HR_staffS_p1_index_2017_1, with index


partitions specified.
CREATE INDEX HR_staffS_p1_index_2017_1 ON staffs_p2017 (employment_ID)
LOCAL
(
PARTITION employment_ID1_index,
PARTITION employment_ID2_index TABLESPACE USERS,
PARTITION employment_ID3_index TABLESPACE USERS,
PARTITION employment_ID4_index,
PARTITION employment_ID5_index
) TABLESPACE USERS;

Perform the following operations on an interval partitioned table:


l Delete existing tables named staffs_p2016, if any.
DROP TABLE IF EXISTS staffs_p2016;

l Create a partitioned table staffs_p2016.


CREATE TABLE staffs_p2016
(
staff_ID NUMBER(6) not null,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25),
PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,
employment_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
section_ID NUMBER(4)
)
PARTITION BY RANGE (staff_ID)
INTERVAL (2)
(
partition P_50 values less than (50),
partition P_100 values less than (100),
partition P_150 values less than (150)
);

l Delete a partition.
-- Query the SYS.SYS_TABLE_PARTS and SYS.SYS_TABLES system catalogs to obtain
partition names:
SELECT * FROM SYS.SYS_TABLE_PARTS WHERE TABLE# = (SELECT ID FROM
SYS.SYS_TABLES WHERE NAME='STAFFS_P2016');

USER# TABLE# PART#


NAME HIBOUNDLEN
HIBOUNDVAL SPACE#
ORG_SCN ENTRY INITRANS PCTFREE
FLAGS BHIBOUNDVAL
ROWCNT BLKCNT EMPCNT AVGRLN SAMPLESIZE ANALYZETIME
------------ ------------ ------------
---------------------------------------------------------------- ------------
---------------------------------------------------------------- ------------
-------------------- -------------------- ------------ ------------

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 177


GaussDB 100
User Guide (Standalone) 5 Database Usage

------------ ----------------------------------------------------------------
------------ ------------ ------------ ------------ ------------
----------------------
2 70 10
P_50 2
50 3
47529132593153 4393751543808 2 8
0
2 70 20
P_100 3
100 3
47529132687361 4393751543808 2 8
0
2 70 30
P_150 3
150 3
47529132744705 4393751543808 2 8
0

3 rows fetched.
-- Delete the partition named P_50:
ALTER TABLE staffs_p2016 DROP PARTITION P_50;

l Add a partition.
An interval partitioned table is dynamically extended with data insertion, and no manual
operation is needed. The name of an automatically generated partition can be obtained
from the SYS.SYS_TABLE_PARTS table.
l Query a partition.
-- Query the SYS.SYS_TABLE_PARTS and SYS.SYS_TABLES system catalogs to obtain
partition names:
SELECT * FROM SYS.SYS_TABLE_PARTS WHERE TABLE# = (SELECT ID FROM
SYS.SYS_TABLES WHERE NAME='STAFFS_P2016');

USER# TABLE# PART#


NAME HIBOUNDLEN
HIBOUNDVAL SPACE#
ORG_SCN ENTRY INITRANS PCTFREE
FLAGS BHIBOUNDVAL
ROWCNT BLKCNT EMPCNT AVGRLN SAMPLESIZE ANALYZETIME
------------ ------------ ------------
---------------------------------------------------------------- ------------
---------------------------------------------------------------- ------------
-------------------- -------------------- ------------ ------------
------------ ----------------------------------------------------------------
------------ ------------ ------------ ------------ ------------
----------------------
0 242 20
P_100 3
100 0
6386343436210177 4393751543808 2 8
0
0 242 30
P_150 3
150 0
6386343436247041 4393751543808 2 8
0

2 rows fetched.
-- Query the partition named P_150:
SELECT * FROM STAFFS_P2016 PARTITION(P_150);

l Create an index for the partitioned table.


– Create a partitioned table index HR_staffS_p1_index_2016, without specifying
index partitions.
CREATE INDEX HR_staffS_p1_index_2016 ON staffs_p2016 (staff_ID) LOCAL;

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 178


GaussDB 100
User Guide (Standalone) 5 Database Usage

– Create a partitioned table index HR_staffS_p1_index_20162, with index partitions


specified.
CREATE INDEX HR_staffS_p1_index_20162 ON staffs_p2016 (section_ID) LOCAL
(
PARTITION section_ID2_index,
PARTITION section_ID3_index
) TABLESPACE USERS;

Perform the following operations on a list partitioned table:


l Delete existing tables named education, if any.
DROP TABLE IF EXISTS education;

l Create a partitioned table education.


CREATE TABLE education(staff_id INT NOT NULL, higest_degree CHAR(12),
graduate_school VARCHAR(64), graduate_date DATETIME, education_note
VARCHAR(70))
PARTITION BY LIST(higest_degree)
(
PARTITION doctor VALUES ('doctor') TABLESPACE USERS,
PARTITION master VALUES ('master') TABLESPACE USERS,
PARTITION undergraduate VALUES ('undergraduate') TABLESPACE USERS
);

l Delete a partition undergraduate.


ALTER TABLE education DROP PARTITION undergraduate;

l Add a partition postdoctor.


ALTER TABLE education ADD PARTITION postdoctor VALUES('postdoctor');

l Query the postdoctor partition.


SELECT * FROM education PARTITION (postdoctor);

l Create an index for the partitioned table.


– Create the partitioned table index idx_education1 without specifying partition
names.
CREATE INDEX idx_education1 ON education(staff_id) LOCAL;

– Create the partitioned table index idx_education2 with partition names specified.
CREATE INDEX idx_education2 ON education(higest_degree) LOCAL
(
PARTITION higest_degree1_index,
PARTITION higest_degree4_index,
PARTITION higest_degree5_index
) TABLESPACE USERS;

5.3.4 Managing Indexes


Indexes accelerate data access but increase the processing time of table insertion, update, and
deletion operations. Therefore, before creating an index, consider whether it is necessary and
select the columns where indexes are to be created. Analyze the service processing and data
usage of applications. Based on the analysis results, create indexes for columns that are
frequently used as search criteria or arranged into a sequence. This section describes the index
types supported by GaussDB 100 and briefly introduces how to use the indexes. For details
about the indexes-related commands, see descriptions of INDEX in GaussDB 100 R&D
Documentation.

Related Concepts
Based on the number of columns within an index, indexes are classified into single-column
indexes and multi-column indexes (composite index).
l Single-column index
An index is created on only one column.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 179


GaussDB 100
User Guide (Standalone) 5 Database Usage

l Multi-column index
This index is also called a composite index. An index contains multiple columns. The
index is used only when the first column during index creation is used in the query
condition. In GaussDB 100, a multi-column index supports a maximum of 16 columns
and the total length cannot exceed 3900 bytes. It is calculated based on data types with
the maximum length.

Based on the usage, indexes are classified as follows:

l Common index: The B-Tree index is created by default.


l Unique index: An index whose column value or column value combination is unique.
When a table is created, a unique index is automatically created on the primary key.
l Function-based index: An index is created based on the function.
l Partitioned index: An index is independently created on a table partition. Deleting a
partition does not influence the use of other partitioned indexes.

Principles for Creating Indexes


After creation, using indexes properly during queries can improve database performance.
However, it takes time to create indexes and maintain indexes. Index files occupy physical
space. In addition, indexes need to be maintained when INSERT, UPDATE, and DELETE
statements are executed on tables, which reduces data maintenance efficiency. Therefore, you
are advised to create indexes on:

l Columns that are frequently searched. The search efficiency can be improved.
l Columns that function as primary keys. The uniqueness of the columns and the data
sequence structures are ensured.
l Columns that function as foreign keys and are used for connections. Then the connection
efficiency is improved.
l Columns that are searched for by specified scope. These indexes have been arranged in a
sequence, and the specified scope is contiguous.
l Columns that need to be arranged in a sequence. These indexes have been arranged in a
sequence, so the sequence query time is accelerated.
l Columns that use the WHERE clause. Then, the condition decision efficiency is
increased.
l Columns that are frequently used after keywords, such as ORDER BY, GROUP BY,
and DISTINCT.
l After an index is created, the system automatically determines when to reference it. If the
system determines that indexing is faster than sequenced scanning, the index will be
used.
l The index must be synchronized with the associated table to ensure that data can be
located accurately, which increases the data operation load. Therefore, delete
unnecessary indexes periodically.

Creating an Index
Run the CREATE INDEX statement to create an index.

The following describes how to create an index staffs_ind in the STAFF_ID column of the
staffs table. The tablespace used by the index is human_resource. ONLINE indicates online

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 180


GaussDB 100
User Guide (Standalone) 5 Database Usage

index creation, which reduces the impact on table use by other users and does not block online
services.
CREATE INDEX staffs_ind ON staffs(staff_id) TABLESPACE human_resource ONLINE;

Rebuilding an Index
After a large number of tables are added, deleted, or modified, the table data may be
fragmented on the physical file of the disk, affecting the access speed. Using the ALTER
INDEX statement to rebuild indexes can reassemble index data and release unused space,
improving data access efficiency and space usage.

Indexes cannot be rebuilt during database restart or rollback.

The following statement uses the staffs_ind index as an example:


ALTER INDEX staffs_ind REBUILD ONLINE;

Renaming an Index
If you need to generalize about the naming style of indexes, use the RENAME syntax to
modify the index names without changing other attributes of the indexes.

Indexes cannot be renamed during database restart or rollback.

The following statement uses the staffs_ind index as an example:


ALTER INDEX staffs_ind RENAME TO staffs_ind_new;

Deleting an Index
Run the DROP INDEX statement to delete an index. Restrictions on deleting an index are as
follows:

l Indexes cannot be deleted during database restart or rollback.


l After ENABLE_IDX_CONFS_NAME_DUPL is enabled, different tables support the
same index name. When deleting an index, you must specify the table name.
l Indexes related to existing UNIQUE KEY or PRIMARY KEY constraints cannot be
deleted.
l When a table is deleted, its indexes are also deleted.

Run the following command to delete the staffs_ind_new index from the staffs table:
DROP INDEX staffs_ind_new ON staffs;

Viewing Index Information


After an index is created, you can query the DB_INDEXES or ADM_INDEXES view for
index information based on your permissions.

5.3.5 Managing Views


If certain columns in one or more tables in a database are frequently searched for, an
administrator can define a view for these columns, and then users can directly access these
columns in the view without entering search criteria.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 181


GaussDB 100
User Guide (Standalone) 5 Database Usage

Related Concepts
A view is different from a base table. It is only a virtual object rather than a physical one. A
database only stores the definition of a view and does not store its data. The data is still stored
in the original base table. If data in the base table changes, the data queried from the view
changes accordingly. In this sense, a view is like a window through which users can know
their interested data and data changes in the database. A view is triggered every time it is
referenced.

Managing Views
l Run the CREATE VIEW command to create a view.
CREATE OR REPLACE VIEW MyView AS SELECT * FROM hr.staffs WHERE section_id =
10;

The OR REPLACE parameter in this command is optional. It indicates that if the view
exists, the new view will replace the existing view.
l Run the SELECT command to query the data in a view.
Example: Query the MyView view.
SELECT * FROM MyView;

l Run the DROP VIEW command to delete a view.


Example: Delete the MyView view.
DROP VIEW MyView;

l Query the system catalog my_views for the view in the current schema.
SELECT * FROM my_views;

l Query the system catalog DB_VIEWS for all views.


SELECT * FROM db_views;

l Run the desc view_name command to query the information about a specified view.
SQL> desc db_views;

COLUMN_NAME NULL? TYPE


---------------------------------------------------------------- --------
-------------------------------------------------------
OWNER
VARCHAR(30)
VIEW_NAME
VARCHAR(30)
VIEW_TYPE
CHAR(7)
COLUMN_COUNT
INTEGER
TEXT CLOB
TEXT_LENGTH
INTEGER
CREATED_TIME DATE
LAST_DDL_TIME DATE

5.4 Exporting and Importing Data


When a database is added or scaled out, the export and import functions of the database can
be used to completely, securely, and quickly migrate data, which reduces the workload of
database administrators.

5.4.1 Overview of Export and Import


A database administrator needs to set different parameters to export data of different types and
content and to import the data to a new database.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 182


GaussDB 100
User Guide (Standalone) 5 Database Usage

When data needs to be migrated from one platform to another, the database administrator
must start data export and import to first export and save the original database information
and then import the data to the new platform.

Data can be exported in the following two ways:

l Data export: The exported file is a .csv file, which offers compatibility for the import
operations of different databases. For example, move data information from one platform
to another.
l Logical export: The exported file is a binary file, which enables faster export and
import. For example, when there is a large amount of data to be migrated, you can use
logical export and import to accelerate the operation.

Data Types
You can define the type of the exported file as TXT or BIN. A TXT file allows exported data
to be visible and also allows multiple threads to export table data simultaneously. A BIN file
occupies less disk space.

5.4.2 Solution of Export and Import


You can set different parameters for exporting and importing data, and select a solution as
required.

Export and Import Modes


Database information can be exported and imported in either of the following ways:

l Data export and import: Exported user data and table data are visible.
l Logical export and import: Metadata about user creation, user roles, and permission
granting can be exported based on specific parameter settings.

Precautions
l Both export and import occupy disk space. You must ensure sufficient disk space
beforehand.
l Export and import occupy CPU resources, which may affect the database processing
speed. Therefore, you are advised to perform the operations during off-peak hours.

5.4.3 Exporting Data

Prerequisites
l Ensure that disk space is sufficient.
l Ensure that CPU resources are sufficient.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 183


GaussDB 100
User Guide (Standalone) 5 Database Usage

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.
Step 2 Run the export command.
l Export the training table.
DUMP TABLE training INTO FILE '/home/gaussdba/data/training_backup' ;

l Export the specified rows in the training table (results returned by SELECT).
DUMP QUERY "SELECT course_name,score,exam_date FROM training WHERE
course_name = 'SQL majorization'"
INTO FILE '/home/gaussdba/data/training_query_backup '
COLUMNS ENCLOSED BY ''''
COLUMNS TERMINATED BY '|';

For details about the DUMP command, see SQL Syntax Reference > Function Syntax
> DUMP in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

----End

5.4.4 Importing Data

Prerequisites
l Ensure that disk space is sufficient.
l Ensure that CPU resources are sufficient.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.
Step 2 Run the import command.
l Import the data file training_backup to the training_new table.
LOAD DATA INFILE "/home/gaussdba/data/training_backup" INTO TABLE
training_new FIELDS ENCLOSED BY '|';

l Import the data file training_backup to a specified column course_name in the


training_new table.
LOAD DATA INFILE "/home/gaussdba/data/training_backup" INTO TABLE
training_new TRAILING COLUMNS(course_name);

For details about the LOAD command, see SQL Syntax Reference > Function Syntax >
LOAD in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

----End

5.4.5 Logically Exporting Data

Prerequisites
l Ensure that disk space is sufficient.
l Ensure that CPU resources are sufficient.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 184


GaussDB 100
User Guide (Standalone) 5 Database Usage

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Run the export command.


l Export data from tab1 and tab2 of the current user.
EXP TABLES=tab1,tab2 FILE="file1.dmp";

l Export the data of users EMP, DEPT, and MGR.


EXP USERS = EMP,DEPT,MGR FILE="file1.dmp";

l Export user, role, and table structure information of the user.


EXP USERS = TEST_USER CONTENT = METADATA_ONLY CREATE_USER = Y ROLE = Y GRANT
= Y FILE = "file1.dmp";

The user performing export must have related permissions.


l Export tablespaces.
EXP USERS = TEST_USER CONTENT = METADATA_ONLY TABLESPACE= Y FILE =
"file1.dmp";

l Export data from a tablespace that is filtered out.


EXP USERS = TEST_USER TABLESPACE_FILTER = A,B FILE = "file1.dmp";

For details about the EXP command, see SQL Syntax Reference > Function Syntax > EXP
in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

----End

5.4.6 Logically Importing Data

Prerequisites
l Ensure that disk space is sufficient.
l Ensure that CPU resources are sufficient.

Procedure
Step 1 Log in to the GaussDB 100 database as a database administrator.
zsql
conn gaussdba/database_123@192.168.0.1:1888

gaussdba/database_123 indicates the system administrator created after the installation and
the administrator password. 192.168.0.1 indicates the IP address of the database server. 1888
indicates the connected port.

Step 2 Run the import command.


l Import data from tab1 and tab2 of the current user.
IMP TABLES=tab1,tab2 FILE="file1.dmp";

l Import the data of users EMP, DEPT, and MGR.


IMP USERS=EMP,DEPT,MGR FILE="file1.dmp";

l Import only the table structure.


IMP USERS=TEST_USER CONTENT=METADATA_ONLY FILE = "file1.dmp";

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 185


GaussDB 100
User Guide (Standalone) 5 Database Usage

l Import only user data.


IMP USERS=USR1,USR2 FILE="file1.dmp" CONTENT=DATA_ONLY;

For details about the IMP command, see SQL Syntax Reference > Function Syntax > IMP
in GaussDB 100 V300R001C00 R&D Documentation (Standalone).

----End

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 186


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

6 Interface Mapping (Basic Packages vs.


Compatible Packages)

6.1 Data Dictionary Tables


Table 6-1 Name mapping of data dictionary tables (basic packages vs. compatible packages)
Basic Package Compatible Package

SYS_BACKUP_SETS BACKUP_SET$

SYS_COLUMNS COLUMN$

SYS_COMMENTS COMMENT$

SYS_CONSTRAINT_DEFS CONSDEF$

SYS_DATA_NODES DATA_NODES$

EXP_TAB_ORDERS DBA_EXP$TBL_ORDER

EXP_TAB_RELATIONS DBA_EXP$TBL_RELATIONS

SYS_DEPENDENCIES DEPENDENCY$

SYS_DISTRIBUTE_RULES DISTRIBUTE_RULE$

SYS_DISTRIBUTE_STRATEGIES DISTRIBUTE_STRATEGY$

SYS_DUMMY DUAL

SYS_EXTERNAL_TABLES EXTERNAL$

SYS_GARBAGE_SEGMENTS GARBAGE_SEGMENT$

SYS_HISTGRAM_ABSTR HIST_HEAD$

SYS_HISTGRAM HISTGRAM$

SYS_INDEXES INDEX$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 187


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

SYS_INDEX_PARTS INDEXPART$

SYS_JOBS JOB$

SYS_LINKS LINK$

SYS_LOBS LOB$

SYS_LOB_PARTS LOBPART$

SYS_LOGIC_REPL LOGIC_REP$

SYS_DML_STATS MON_MODS_ALL$

SYS_OBJECT_PRIVS OBJECT_PRIVS$

SYS_PART_COLUMNS PARTCOLUMN$

SYS_PART_OBJECTS PARTOBJECT$

SYS_PART_STORES PARTSTORE$

SYS_PENDING_DIST_TRANS PENDING_DISTRIBUTED_TRANS$

SYS_PENDING_TRANS PENDING_TRANS$

SYS_PROCS PROC$

SYS_PROC_ARGS PROC_ARGS$

SYS_PROFILE PROFILE$

SYS_RECYCLEBIN RECYCLEBIN$

SYS_ROLES ROLES$

SYS_SEQUENCES SEQUENCE$

SYS_SHADOW_INDEXES SHADOW_INDEX$

SYS_SHADOW_INDEX_PARTS SHADOW_INDEXPART$

SYS_SYNONYMS SYNONYM$

SYS_PRIVS SYS_PRIVS$

SYS_TABLES TABLE$

SYS_TABLE_PARTS TABLEPART$

SYS_TMP_SEG_STATS TMP_SEG_STAT$

SYS_USERS USER$

SYS_USER_HISTORY USER_HISTORY$

SYS_USER_ROLES USER_ROLES$

SYS_VIEWS VIEW$

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 188


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

SYS_VIEW_COLS VIEWCOL$

SYS_SQL_MAPS SQL_MAP$

WSR_PARAMETER WRH$_PARAMETER

WSR_SQLAREA WRH$_SQLAREA

WSR_SYS_STAT WRH$_SYSSTAT

WSR_SYSTEM WRH$_SYSTEM

WSR_SYSTEM_EVENT WRH$_SYSTEM_EVENT

WSR_SNAPSHOT WRM$_SNAPSHOT

WSR_CONTROL WRM$_WR_CONTROL

WSR_DBA_SEGMENTS WSR$_DBA_SEGMENTS

WSR_LATCH WSR$_LATCH

WSR_LIBRARYCACHE WSR$_LIBRARYCACHE

WSR_SEGMENT WSR$_SEGMENT

WSR_SQL_LIST WSR$SQL_LIST

WSR_WAITSTAT WSR$_WAITSTAT

6.2 DBA Views


Table 6-2 Name mapping of DBA views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_DB_LINKS ALL_DB_LINKS

DB_IND_STATISTICS ALL_IND_STATISTICS

DB_JOBS ALL_JOBS

DB_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS

DB_USERS ALL_USERS

DB_USER_SYS_PRIVS ALL_USER_SYS_PRIVS

ADM_ARGUMENTS DBA_ARGUMENTS

ADM_BACKUP_SET DBA_BACKUP_SET

ADM_COL_COMMENTS DBA_COL_COMMENTS

ADM_CONSTRAINTS DBA_CONSTRAINTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 189


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

ADM_DATA_FILES DBA_DATA_FILES

ADM_DBLINK_TABLES DBA_DBLINK_TABLES

ADM_DBLINK_TAB_COLUMNS DBA_DBLINK_TAB_COLUMNS

ADM_DEPENDENCIES DBA_DEPENDENCIES

ADM_FREE_SPACE DBA_FREE_SPACE

ADM_HISTOGRAMS DBA_HISTOGRAMS

ADM_HIST_DBASEGMENTS DBA_HIST_DBASEGMENTS

ADM_HIST_LATCH DBA_HIST_LATCH

ADM_HIST_LIBRARYCACHE DBA_HIST_LIBRARYCACHE

ADM_HIST_LONGSQL DBA_HIST_LONGSQL

ADM_HIST_PARAMETER DBA_HIST_PARAMETER

ADM_HIST_SEGMENT DBA_HIST_SEGMENT

ADM_HIST_SNAPSHOT DBA_HIST_SNAPSHOT

ADM_HIST_SQLAREA DBA_HIST_SQLAREA

ADM_HIST_SYSSTAT DBA_HIST_SYSSTAT

ADM_HIST_SYSTEM DBA_HIST_SYSTEM

ADM_HIST_SYSTEM_EVENT DBA_HIST_SYSTEM_EVENT

ADM_HIST_WAITSTAT DBA_HIST_WAITSTAT

ADM_HIST_WR_CONTROL DBA_HIST_WR_CONTROL

ADM_INDEXES DBA_INDEXES

ADM_IND_COLUMNS DBA_IND_COLUMNS

ADM_IND_PARTITIONS DBA_IND_PARTITIONS

ADM_IND_STATISTICS DBA_IND_STATISTICS

ADM_JOBS DBA_JOBS

ADM_JOBS_RUNNING DBA_JOBS_RUNNING

ADM_OBJECTS DBA_OBJECTS

ADM_PART_COL_STATISTICS DBA_PART_COL_STATISTICS

ADM_PART_KEY_COLUMNS DBA_PART_KEY_COLUMNS

ADM_PART_STORE DBA_PART_STORE

ADM_PART_TABLES DBA_PART_TABLES

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 190


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

ADM_PROCEDURES DBA_PROCEDURES

ADM_PROFILES DBA_PROFILES

ADM_ROLES DBA_ROLES

ADM_ROLE_PRIVS DBA_ROLE_PRIVS

ADM_SEGMENTS DBA_SEGMENTS

ADM_SEQUENCES DBA_SEQUENCES

ADM_SOURCE DBA_SOURCE

ADM_SYNONYMS DBA_SYNONYMS

ADM_SYS_PRIVS DBA_SYS_PRIVS

ADM_TABLES DBA_TABLES

ADM_TABLESPACES DBA_TABLESPACES

ADM_TAB_COLS DBA_TAB_COLS

ADM_TAB_COLUMNS DBA_TAB_COLUMNS

ADM_TAB_COL_STATISTICS DBA_TAB_COL_STATISTICS

ADM_TAB_COMMENTS DBA_TAB_COMMENTS

ADM_TAB_DISTRIBUTE DBA_TAB_DISTRIBUTE

ADM_TAB_MODIFICATIONS DBA_TAB_MODIFICATIONS

ADM_TAB_PARTITIONS DBA_TAB_PARTITIONS

ADM_TAB_PRIVS DBA_TAB_PRIVS

ADM_TAB_STATISTICS DBA_TAB_STATISTICS

ADM_TRIGGERS DBA_TRIGGERS

ADM_USERS DBA_USERS

ADM_VIEWS DBA_VIEWS

ADM_VIEW_COLUMNS DBA_VIEW_COLUMNS

6.3 User Views


Table 6-3 Name mapping of user views (basic packages vs. compatible packages)

Basic Package Compatible Package

DB_ARGUMENTS ALL_ARGUMENTS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 191


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

DB_COL_COMMENTS ALL_COL_COMMENTS

DB_CONSTRAINTS ALL_CONSTRAINTS

DB_DBLINK_TABLES ALL_DBLINK_TABLES

DB_DBLINK_TAB_COLUMNS ALL_DBLINK_TAB_COLUMNS

DB_DEPENDENCIES ALL_DEPENDENCIES

DB_DISTRIBUTE_RULES ALL_DISTRIBUTE_RULES

DB_DIST_RULE_COLS ALL_DIST_RULE_COLS

DB_HISTOGRAMS ALL_HISTOGRAMS

DB_INDEXES ALL_INDEXES

DB_IND_COLUMNS ALL_IND_COLUMNS

DB_IND_PARTITIONS ALL_IND_PARTITIONS

DB_OBJECTS ALL_OBJECTS

DB_PART_COL_STATISTICS ALL_PART_COL_STATISTICS

DB_PART_KEY_COLUMNS ALL_PART_KEY_COLUMNS

DB_PART_STORE ALL_PART_STORE

DB_PART_TABLES ALL_PART_TABLES

DB_PROCEDURES ALL_PROCEDURES

DB_SEQUENCES ALL_SEQUENCES

DB_SOURCE ALL_SOURCE

DB_SYNONYMS ALL_SYNONYMS

DB_TABLES ALL_TABLES

DB_TAB_COLS ALL_TAB_COLS

DB_TAB_COLUMNS ALL_TAB_COLUMNS

DB_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS

DB_TAB_COMMENTS ALL_TAB_COMMENTS

DB_TAB_DISTRIBUTE ALL_TAB_DISTRIBUTE

DB_TAB_PARTITIONS ALL_TAB_PARTITIONS

DB_TAB_STATISTICS ALL_TAB_STATISTICS

DB_TRIGGERS ALL_TRIGGERS

DB_VIEWS ALL_VIEWS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 192


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

DB_VIEW_COLUMNS ALL_VIEW_COLUMNS

ROLE_SYS_PRIVS ROLE_SYS_PRIVS

MY_ARGUMENTS USER_ARGUMENTS

MY_COL_COMMENTS USER_COL_COMMENTS

MY_CONSTRAINTS USER_CONSTRAINTS

MY_CONS_COLUMNS USER_CONS_COLUMNS

MY_DEPENDENCIES USER_DEPENDENCIES

MY_FREE_SPACE USER_FREE_SPACE

MY_HISTOGRAMS USER_HISTOGRAMS

MY_INDEXES USER_INDEXES

MY_IND_COLUMNS USER_IND_COLUMNS

MY_IND_PARTITIONS USER_IND_PARTITIONS

MY_IND_STATISTICS USER_IND_STATISTICS

MY_JOBS USER_JOBS

MY_OBJECTS USER_OBJECTS

MY_PART_COL_STATISTICS USER_PART_COL_STATISTICS

MY_PART_KEY_COLUMNS USER_PART_KEY_COLUMNS

MY_PART_STORE USER_PART_STORE

MY_PART_TABLES USER_PART_TABLES

MY_PROCEDURES USER_PROCEDURES

MY_ROLE_PRIVS USER_ROLE_PRIVS

MY_SEGMENTS USER_SEGMENTS

MY_SEQUENCES USER_SEQUENCES

MY_SOURCE USER_SOURCE

MY_SQL_MAPS USER_SQL_MAPS

MY_SYNONYMS USER_SYNONYMS

MY_SYS_PRIVS USER_SYS_PRIVS

MY_TABLES USER_TABLES

MY_TAB_COLS USER_TAB_COLS

MY_TAB_COLUMNS USER_TAB_COLUMNS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 193


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

MY_TAB_COL_STATISTICS USER_TAB_COL_STATISTICS

MY_TAB_COMMENTS USER_TAB_COMMENTS

MY_TAB_DISTRIBUTE USER_TAB_DISTRIBUTE

MY_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS

MY_TAB_PARTITIONS USER_TAB_PARTITIONS

MY_TAB_PRIVS USER_TAB_PRIVS

MY_TAB_STATISTICS USER_TAB_STATISTICS

MY_TRIGGERS USER_TRIGGERS

MY_USERS USER_USERS

MY_VIEWS USER_VIEWS

MY_VIEW_COLUMNS USER_VIEW_COLUMNS

6.4 Dynamic Performance Views


Table 6-4 Name mapping of dynamic performance views (basic packages vs. compatible
packages)
Basic Package Compatible Package

NLS_SESSION_PARAMETERS NLS_SESSION_PARAMETERS

DV_ALL_TRANS V$ALL_TRANSACTION

DV_ARCHIVED_LOGS V$ARCHIVED_LOG

DV_ARCHIVE_DEST_STATUS V$ARCHIVE_DEST_STATUS

DV_ARCHIVE_GAPS V$ARCHIVE_GAP

DV_ARCHIVE_THREADS V$ARCHIVE_PROCESSES

DV_BACKUP_PROCESSES V$BACKUP_PROCESS

DV_BUFFER_POOLS V$BUFFER_POOL

DV_BUFFER_POOL_STATS V$BUFFER_POOL_STATISTICS

DV_CONTROL_FILES V$CONTROLFILE

DV_DATABASE V$DATABASE

DV_DATA_FILES V$DATAFILE

DV_OBJECT_CACHE V$DB_OBJECT_CACHE

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 194


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

DV_DC_POOLS V$DC_POOL

DV_DYNAMIC_VIEWS V$DYNAMIC_VIEW

DV_DYNAMIC_VIEW_COLS V$DYNAMIC_VIEW_COLUMN

DV_FREE_SPACE V$FREE_SPACE

DV_HA_SYNC_INFO V$HA_SYNC_INFO

DV_HBA V$HBA

DV_INSTANCE V$INSTANCE

DV_RUNNING_JOBS V$JOBS_RUNNING

DV_LATCHS V$LATCH

DV_LIBRARY_CACHE V$LIBRARYCACHE

DV_LOCKS V$LOCK

DV_LOCKED_OBJECTS V$LOCKED_OBJECT

DV_LOG_FILES V$LOGFILE

DV_LONG_SQL V$LONGSQL

DV_STANDBYS V$MANAGED_STANDBY

DV_ME V$ME

DV_OPEN_CURSORS V$OPEN_CURSOR

DV_PARAMETERS V$PARAMETER

DV_PL_MANAGER V$PL_MANAGER

DV_PL_REFSQLS V$PL_REFSQLS

DV_REACTOR_POOLS V$REACTOR_POOL

DV_REPL_STATUS V$REPL_STATUS

DV_RESOURCE_MAP V$RESOURCE_MAP

DV_SEGMENT_STATS V$SEGMENT_STATISTICS

DV_SESSIONS V$SESSION

DV_SESSION_EVENTS V$SESSION_EVENT

DV_SESSION_WAITS V$SESSION_WAIT

DV_GMA V$SGA

DV_GMA_STATS V$SGASTAT

DV_SPINLOCKS V$SPINLOCK

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 195


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

DV_SQLS V$SQLAREA

DV_SQL_POOL V$SQLPOOL

DV_SYS_STATS V$SYSSTAT

DV_SYSTEM V$SYSTEM

DV_SYS_EVENTS V$SYSTEM_EVENT

DV_TABLESPACES V$TABLESPACE

DV_TEMP_POOLS V$TEMP_POOL

DV_TEMP_UNDO_SEGMENT V$TEMP_UNDO_SEGMENT

DV_TRANSACTIONS V$TRANSACTION

DV_UNDO_SEGMENTS V$UNDO_SEGMENT

DV_USER_ADVISORY_LOCKS V$USER_ADVISORY_LOCKS

DV_USER_ASTATUS_MAP V$USER_ASTATUS_MAP

DV_USER_PARAMETERS V$USER_PARAMETER

DV_VERSION V$VERSION

DV_VM_FUNC_STACK V$VM_FUNC_STACK

DV_WAIT_STATS V$WAITSTAT

DV_XACT_LOCKS V$XACT_LOCK

6.5 Configuration Parameters


Table 6-5 Name mapping of configuration parameters (basic packages vs. compatible
packages)
Basic Package Compatible Package

JOB_THREADS JOB_QUEUE_PROCESSES

COMMIT_MODE COMMIT_LOGGING

COMMIT_WAIT_LOGGING COMMIT_WAIT

PAGE_CHECKSUM DB_BLOCK_CHECKSUM

ARCHIVE_CONFIG LOG_ARCHIVE_CONFIG

ARCHIVE_DEST_N LOG_ARCHIVE_DEST_n

ARCHIVE_DEST_STATE_N LOG_ARCHIVE_DEST_STATE_n

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 196


GaussDB 100 6 Interface Mapping (Basic Packages vs. Compatible
User Guide (Standalone) Packages)

Basic Package Compatible Package

ARCHIVE_FORMAT LOG_ARCHIVE_FORMAT

ARCHIVE_MAX_THREADS LOG_ARCHIVE_MAX_PROCESSES

ARCHIVE_MIN_SUCCEED_DEST LOG_ARCHIVE_MIN_SUCCEED_DEST

ARCHIVE_TRACE LOG_ARCHIVE_TRACE

CHECKPOINT_PERIOD CHECKPOINT_TIMEOUT

CHECKPOINT_PAGES CHECKPOINT_INTERVAL

TIMED_STATS TIMED_STATISTICS

STATS_LEVEL STATISTICS_LEVEL

FILE_OPTIONS FILESYSTEMIO_OPTIONS

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 197


GaussDB 100
User Guide (Standalone) 7 Glossary

7 Glossary

Term Description

A–E

ACID Atomicity, Consistency, Isolation, and Durability (ACID). These are a set of
features of database transactions in a DBMS.

archive A thread started when the archive function is enabled on a database. The
thread thread is used to archive database logs to a specified path.

atomicity One of the ACID features of database transactions. Atomicity means that a
transaction is composed of an indivisible unit of work. All operations
performed in a transaction must either be committed or uncommitted. If an
error occurs during transaction execution, the transaction will be rolled
back to the state when it was not committed.

backup A backup, or the process of backing up, refers to the copying and archiving
of computer data. Backup data can be used for restoration in case of data
loss.

bit The smallest unit of information handled by a computer. One bit is


expressed as a 1 or a 0 in a binary numeral, or as a true or a false logical
condition. A bit is physically represented by an element such as high or low
voltage at one point in a circuit, or a small spot on a disk that is magnetized
in one way or the other. A single bit conveys little information a human
would consider meaningful. A group of eight bits, however, makes up a
byte, which can be used to represent many types of information, such as a
letter of the alphabet, a decimal digit, or other character.

checkpoint A mechanism that stores data in the database memory to disks at a certain
time. GaussDB 100 periodically stores the data of committed transactions
and data of uncommitted transactions to disks. The data and redo logs can
be used for database restoration if a database restarts or breaks down.

CLI Command-line interface (CLI). Users use the CLI to interact with
applications. Its input and output are based on texts. Commands are entered
through keyboards or similar devices and are compiled and executed by
applications. The results are displayed in text or graphic forms on the
terminal interface.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 198


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

coding Coding is representing data and information using code so that it can be
processed and analyzed by a computer. Characters, digits, and other objects
can be converted into digital code, or information and data can be converted
into the required electrical pulse signals based on predefined rules.

column An equivalent concept of field. A database table consists of one or more


columns.

compression Data compression, source coding, or bit-rate reduction involves encoding


information that uses fewer bits than the original representation.
Compression can be either lossy or lossless. Lossless compression reduces
bits by identifying and eliminating statistical redundancy. No information is
lost in lossless compression. Lossy compression reduces bits by identifying
and removing unnecessary or less important information. The process of
reducing the size of a data file is commonly referred as data compression,
although its formal name is source coding (coding done at the source of
data, before it is stored or transmitted).

concurrency A DBMS service that ensures data integrity when multiple transactions are
control concurrently executed in a multi-user environment. In a multi-threaded
GaussDB 100 environment, concurrency control ensures that database
operations are safe and all database transactions remain consistent at any
given time.

consistency One of the ACID features of database transactions. Consistency is a


database state. In such a state, integrity constraints on tables are not
damaged.

convergence Downlink to uplink bandwidth ratio of a switch. A high convergence ratio


ratio indicates a highly converged traffic environment and severe packet loss.

core dump When a program stops abnormally, core dump, memory dump, or system
dump records the state of working memory of the program at that point in
time. The states of key programs are often dumped at the same time. For
example, information about processor registers, including program metrics,
stack pointers, memory management, other processors, and OS flags are
often dumped at the same time. A core dump is often used to assist
diagnosis and computer program debugging.

core file A file that is created when memory overwriting, assertion failures, or access
to invalid memory occurs in a process, causing it to fail. This file is then
used for further analysis.
A core file stores memory dump data, and supports binary mode and
specified ports. The name of a core file consists of the word "core" and the
OS process ID.
The core file is available regardless of the type of platform.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 199


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

crash A crash (or system crash) is when a computer or program, such as a


software application or an operating system, stops functioning properly.
Often the program will exit after encountering this type of error. The
program experiencing the crash can hang or freeze until a crash reporting
service reports the crash and any details relating to it. If the program is a
critical part of the operating system and crashes, the entire system may be
paralyzed, often resulting in a fatal system error.

data A representation of facts or directives for manual or automatic


communication, explanation, or processing. Data includes constants,
variables, arrays, and strings.

data A set of read-only tables that provide database information. The


dictionary information includes database design information, stored procedure
information, user rights, user statistics, database process information,
database increase statistics, and database performance statistics.

data flow An operator that exchanges data among query fragments. By their input/
operator output relationships, data flows can be categorized into Gather flows,
Broadcast flows, and Redistribution flows. Gather combines multiple query
fragments of data into one. Broadcast forwards the data of one query
fragment to multiple query fragments. Redistribution reorganizes the data
of multiple query fragments and then redistributes the reorganized data to
multiple query fragments.

data A division of a logical database or its constituent elements into multiple


partitioning parts (partitions) whose data does not overlap based on ranges or lists. The
target storage location is mapped based on the range of the values in the
column that is specified in the tuple.

database A collection of data that is stored together and can be accessed, managed,
and updated. Data in a view in a database can be classified into the
following types: numeral, full text, digit, and image.

database file A binary file that stores user data and the internal data of a database system.

database HA GaussDB 100 provides a highly reliable HA solution. Every logical node in
GaussDB 100 is identified as a primary or standby node. At the same time,
only one GaussDB 100 node is identified as the primary server. In
GaussDB 100, standby nodes first perform full synchronization from the
primary node and later incremental synchronization. When the HA system
is running, the primary node can receive data read and write requests in
GaussDB 100.

database A database instance consists of a process in GaussDB 100 and files


instance controlled by the process. GaussDB 100 allows multiple database instances
to be installed on one physical node.

DBA A database administrator (DBA) instructs or executes database maintenance


operations.

DBLINK An object of the path from one database to another. A remote database
object can be queried with DBLINK.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 200


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

DBMS A Database Management System (DBMS) is a piece of system


management software that allows users to access information in a database.
It is a collection of programs that allows users to access, manage, and query
data in a database. A DBMS can be classified as memory DBMS or disk
DBMS based on the location of data.

DCL Data control language

DDL Data definition language

deadlock Unresolved contention for the use of resources.

dirty page A page that has been modified and is not written to a permanent device.

DML Data manipulation language

dump file A specific type of trace file. A dump file contains diagnostic data during an
event response, whereas a trace file contains continuously generated
diagnostic data.

durability One of the ACID features of database transactions. Transactions that have
been committed will permanently survive and not be rolled back.

encryption A function hiding information content during data transmission to prevent


unauthorized use of the information.

environment An environment variable defines a part of the environment in which a


variable process runs. For example, it can define a main directory, command search
path, terminal that is in use, or the current time zone.

error A technique that automatically detects and corrects errors in software and
correction data streams to improve system stability and reliability.

F–J

failover Automatic switchover from a faulty node to its standby node. Reversely,
automatic switchback from the standby node to the primary node is called
failback.

failover Automatic substitution of a functionally equivalent system component for a


failed one. The system component can be a processor, server, network, or
database.

free space A mechanism for managing free space in a table. This mechanism enables a
management database system to record free space in each table and establish an easy-to-
find data structure, accelerating operations (such as INSERT) performed on
the free space.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 201


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

freeze An operation automatically performed by the AutoVacuum Worker process


when transaction IDs are exhausted. GaussDB 100 records transaction IDs
in the row heading. When a transaction reads a row, the transaction ID in
the row heading and the actual transaction ID are compared to determine
whether this row is explicit. Transaction IDs are integers containing no
symbols. If exhausted, transaction IDs are re-calculated outside of the
integer range, causing the explicit rows to become implicit. To prevent such
a problem, the freeze operation marks a transaction ID as a special ID.
Rows marked with these special transaction IDs are explicit to all
transactions.

full A data synchronization mechanism specified in the GaussDB 100 HA


synchronizat solution. Used to synchronize all data from the primary server to a standby
ion server.

GNU The GNU Project was publicly announced on September 27, 1983 by
Richard Stallman, aiming at building an OS composed wholly of free
software. GNU is a recursive acronym for "GNU's Not Unix!". Stallman
announced that GNU should be pronounced as Guh-NOO. Technically,
GNU is similar to Unix in design, a widely used commercial OS. However,
GNU is free software and contains no Unix code.

GTS Global Time Server (GTS). It is used to provide a logical clock for each
node in the case of strong consistency.

HA High availability (HA) is a solution. It helps minimize the duration of


service interruptions caused by routine maintenance (planned) or sudden
system breakdowns (unplanned), improving system and application
usability.

HBA Host-based authentication (HBA) allows hosts to authenticate on behalf of


all or some of the system users.

incremental Incremental backup stores all file changes since the last valid backup.
backup

index An ordered data structure in a DBMS. An index accelerates data query and
update in database tables.

isolation One of the ACID features of database transactions. Isolation means that the
operations inside a transaction and data used are isolated from other
concurrent transactions. Concurrent transactions do not disturb each other.

JDBC Java database connectivity (JDBC) is used to implement the Java APIs of
SQL statements. It provides unified access to multiple relational databases,
consisting of a set of classes and interfaces written in Java language.

junk tuple A tuple that is deleted using the DELETE and UPDATE statements. When
deleting a tuple, GaussDB 100 only marks the tuples that are to be cleared.
The VACUUM thread will then periodically clear these junk tuples.

K–O

log file A file to which a computer system writes a record of its activities.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 202


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

metadata Data that provides information about other data. Metadata describes the
source, size, format, or other characteristics of data. In database columns,
metadata explains the content of a data warehouse.

MVCC Multi-Version Concurrency Control (MVCC) is a protocol that allows a


tuple to have multiple versions, on which different query operations can be
performed. One basic advantage is that read and write operations do not
conflict.

network Network backup provides a comprehensive, flexible data protection


backup solution for Microsoft Windows, UNIX, and Linux platforms. Network
backup can back up, archive, and restore files, folders, directories, volumes,
and partitions on a computer.

OS An operating system (OS) manages applications or application programs on


a computer.

P–T

page Smallest memory unit for row storage in the relational object structure in
GaussDB 100. The default size of a page is 8 KB.

physical A physical machine or device.


node

PITR Point-In-Time Recovery (PITR) is a backup and restoration feature of


GaussDB 100. Data can be restored to a specified point in time if backup
data and WALs are normal.

primary A node that receives data read and write requests in the GaussDB 100 HA
server system and works with all standby servers. At any time, only one node in
the HA system is identified as the primary server.

process An instance of a computer program that is being executed. A process may


be made up of one or more threads. A process cannot use a thread occupied
by another process.

QPS Query Per Second (QPS) means the number of queries that a server can
respond to per second.

query Each query job can be split into one or more query fragments. Each query
fragment fragment consists of one or more query operators and can independently
run on a node. Query fragments exchange data through data flow operators.

query An iterator or a query tree node, which is a basic unit for the execution of a
operator query. Execution of a query can be split into one or more query operators.
Common query operators include scan, join, and aggregation.

record In a relational database, a record corresponds to data in each row of a table.

redo log A log that contains information required for performing an operation again
in a database. If a database is faulty, redo logs can be used to restore the
database to its original state.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 203


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

relational A database created using the relational model. It processes data using
database methods of set algebra.

resource A collection of resources that can be accessed to obtain information.


library

RPO Recovery point objective (RPO) refers to the latest status that a database
system and the data can be restored to after a disaster, and it is usually
represented by time.

RTO Recovery time objective (RTO) refers to the duration between the database
system failure caused by a disaster and its restoration to proper running.

schema A database object set that includes the logical structure, such as tables,
views, sequences, stored procedures, synonyms, clusters, and database
links.

segment A segment in a database indicates a part containing one or more extents. An


extent is the smallest range of a database and consists of data blocks. One
or more segments comprise a tablespace.

session A job created by a database system for connection purposes when an


application attempts to connect to the database. Sessions are managed by
the session manager. They execute initial jobs to perform all user
operations.

SGA System global area (SGA). It is the cache management framework of


GaussDB 100. It contains most cache management components of the
storage engine and SQL engine, including PlanCache, DataBuffer,
DcCache, RedoBuffer, CkptBuffer, LockBuffer, TransactionBuffer, and
ReplicationBuffer.

shared pool A shared pool is created for repeatedly executed SQL statements to save
memory. It contains the explain trees and execution plans of given SQL
statements.

SQL Structured Query Language (SQL) is a standard database query language. It


consists of DDL, DML, and DCL.

SSL Secure Sockets Layer (SSL) is a network security protocol first used by
Netscape. It is based on the TCP/IP protocol and uses public key
technology. SSL supports a wide range of networks and provides three
basic security services, all of which use the public key technology. SSL
ensures the security of service communication through a network by
establishing a secure connection between a client and a server and then
sending data through this connection.

standby A node in the GaussDB 100 HA solution. It functions as a backup of the


server primary server. If the primary server is behaving abnormally, the standby
server is promoted to primary, ensuring uninterrupted data services.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 204


GaussDB 100
User Guide (Standalone) 7 Glossary

Term Description

statistics Information that is automatically collected by databases, including table-


level information (number of tuples and number of pages) and column-level
information (column value range distribution histograms). Statistics in
databases are used to estimate the costs of query plans to find the plan with
the lowest cost.

stop word In computing, stop words are words which are filtered out before or after
processing of natural language data (text), saving storage space and
improving search efficiency.

stored A group of SQL statements compiled into a single execution plan and
procedure stored in a large database system. Users can specify a name and parameters
(if any) for a stored procedure to execute the procedure.

system A table storing meta information about a database. The meta information
catalog includes user tables, indexes, columns, functions, and data types in a
database.

table A set of columns and rows. Each column is referred to as a field. Values in
each field represent a data type. For example, if a table contains three fields
of person names, cities, and states, it has three columns: Name, City, and
State. In every row in the table, the Name column contains a name, the City
column contains a city, and the State column contains a state.

tablespace A tablespace is a logical storage structure that contains tables, indexes, and
objects. A tablespace provides an abstract layer between physical data and
logical data, and provides storage space for all database objects. When you
create an object, you can specify which tablespace it belongs to.

thesaurus Standardized words or phrases that express document themes and are used
for indexing and retrieval.

transaction A logical unit of work performed within a DBMS against a database. A


transaction consists of a limited database operation sequence, and must
have ACID features.

U–Z

WSR Workload Statistics Report (WSR), an automatic load information library. A


WSR is generated by comparing statistics collected by two snapshots.

Xlog A transaction log. A logical node can have only one Xlog file.

zsql GaussDB 100 interactive terminal. zsql enables you to interactively enter
queries, issue them to GaussDB 100, and view the query results. Queries
can also be entered from files. zsql supports many meta commands and
shell-like commands, allowing you to conveniently compile scripts and
automate jobs.

Issue 03 (2019-06-06) Copyright © Huawei Technologies Co., Ltd. 205

You might also like